@babylonjs/viewer
Version:
The Babylon Viewer aims to simplify a specific but common Babylon.js use case: loading, viewing, and interacting with a 3D model.
71 lines • 1.47 MB
JavaScript
"undefined"==typeof Symbol||Symbol.metadata||Object.defineProperty(Symbol,"metadata",{configurable:!0,writable:!0,value:Symbol("Symbol.metadata")});class e extends Error{}e._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const t={MeshInvalidPositionsError:0,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class s extends e{constructor(t,i,r){super(t),this.errorCode=i,this.innerError=r,this.name="RuntimeError",e._setPrototypeOf(this,s.prototype)}}class i extends e{constructor(t="Operation aborted"){super(t),this.name="AbortError",e._setPrototypeOf(this,i.prototype)}}class r{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}class n{constructor(){this._currentOperation=Promise.resolve()}lockAsync(e,t){t?.throwIfAborted();const s=t?()=>(t.throwIfAborted(),e()):e,i=this._currentOperation.then(s);return this._currentOperation=new Promise(e=>{i.then(()=>e(),e)}),i}static async LockAsync(e,t,s){if(s?.throwIfAborted(),0===t.length)return await e();const i=new r;let n=0;for(const r of t)r.lockAsync(async()=>(n++,n===t.length&&i.resolve(await e()),await i.promise),s).catch(e=>i.reject(e));return await i.promise}}class a{static _CheckLimit(e,t){let s=a._LogLimitOutputs[e];return s?s.current++:(s={limit:t,current:1},a._LogLimitOutputs[e]=s),s.current<=s.limit}static _GenerateLimitMessage(e,t=1){const s=a._LogLimitOutputs[e];if(!s||!a.MessageLimitReached)return;const i=this._Levels[t];s.current===s.limit&&a[i.name](a.MessageLimitReached.replace(/%LIMIT%/g,""+s.limit).replace(/%TYPE%/g,i.name??""))}static _AddLogEntry(e){a._LogCache=e+a._LogCache,a.OnNewCacheEntry&&a.OnNewCacheEntry(e)}static _FormatMessage(e){const t=e=>e<10?"0"+e:""+e,s=new Date;return"["+t(s.getHours())+":"+t(s.getMinutes())+":"+t(s.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,s){const i=Array.isArray(t)?t[0]:t;if(void 0!==s&&!a._CheckLimit(i,s))return;const r=a._FormatMessage(i),n=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];n.logFunc&&n.logFunc("BJS - "+r,...o);const h=`<div style='color:${n.color}'>${r}</div><br>`;a._AddLogEntry(h),a._GenerateLimitMessage(i,e)}static get LogCache(){return a._LogCache}static ClearLogCache(){a._LogCache="",a._LogLimitOutputs={},a.errorsCount=0}static set LogLevels(e){a.Log=a._LogDisabled,a.Warn=a._LogDisabled,a.Error=a._LogDisabled;const t=[a.MessageLogLevel,a.WarningLogLevel,a.ErrorLogLevel];for(const s of t)if((e&s)===s){const e=this._Levels[s];a[e.name]=a._LogEnabled.bind(a,s)}}}a.NoneLogLevel=0,a.MessageLogLevel=1,a.WarningLogLevel=2,a.ErrorLogLevel=4,a.AllLogLevel=7,a.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",a._LogCache="",a._LogLimitOutputs={},a._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],a.errorsCount=0,a.Log=a._LogEnabled.bind(a,a.MessageLogLevel),a.Warn=a._LogEnabled.bind(a,a.WarningLogLevel),a.Error=a._LogEnabled.bind(a,a.ErrorLogLevel);const o="undefined"!=typeof WeakRef;class h{constructor(e,t=!1,s,i){this.initialize(e,t,s,i)}initialize(e,t=!1,s,i){return this.mask=e,this.skipNextObservers=t,this.target=s,this.currentTarget=i,this}}class l{constructor(e,t,s=null){this.callback=e,this.mask=t,this.scope=s,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(e=!1){this._remove&&this._remove(e)}}class c{static FromPromise(e,t){const s=new c;return e.then(e=>{s.notifyObservers(e)}).catch(e=>{if(!t)throw e;t.notifyObservers(e)}),s}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new h(0),e&&(this._onObserverAdded=e)}add(e,t=-1,s=!1,i=null,r=!1){if(!e)return null;const n=new l(e,t,i);n.unregisterOnNextCall=r,s?this._observers.unshift(n):this._observers.push(n),this._onObserverAdded&&this._onObserverAdded(n),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(n,this._lastNotifiedValue);const a=o?new WeakRef(this):{deref:()=>this};return n._remove=(e=!1)=>{const t=a.deref();t&&(e?t.remove(n):t._remove(n))},n}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){if(!e)return!1;e._remove=null;return-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0)}removeCallback(e,t){for(let s=0;s<this._observers.length;s++){const i=this._observers[s];if(!i._willBeUnregistered&&(i.callback===e&&(!t||t===i.scope)))return this._deferUnregister(i),!0}return!1}_deferUnregister(e){e._willBeUnregistered||(this._numObserversMarkedAsDeleted++,e.unregisterOnNextCall=!1,e._willBeUnregistered=!0,setTimeout(()=>{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;const s=this._observers.indexOf(e);return-1!==s&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(s,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,s,i,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const n=this._eventState;n.mask=t,n.target=s,n.currentTarget=i,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=r;for(const s of this._observers)if(!s._willBeUnregistered&&(s.mask&t&&(s.unregisterOnNextCall&&this._deferUnregister(s),s.scope?n.lastReturnValue=s.callback.apply(s.scope,[e,n]):n.lastReturnValue=s.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,s=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const i=this._eventState;i.mask=s,i.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,i)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new c;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}function u(...e){for(const t of e)t?.throwIfAborted()}function d(e){(async()=>{try{await e}catch(e){e instanceof i||a.Error(e)}})()}const _=["none","normal","high"],p=["none","standard","aces","neutral"];function f(e){return p.includes(e)}class g{constructor(){this.screenPosition=[NaN,NaN],this.worldPosition=[NaN,NaN,NaN],this.visibility=NaN}}const m={clearColor:[0,0,0,0],autoSuspendRendering:!0,environmentConfig:{intensity:1,blur:.3,rotation:0},environmentLighting:"auto",environmentSkybox:"none",cameraAutoOrbit:{enabled:!1,delay:2e3,speed:.05},animationAutoPlay:!1,animationSpeed:1,shadowConfig:{quality:"none"},postProcessing:{toneMapping:"neutral",contrast:1,exposure:1,ssao:"auto"},useRightHandedSystem:!1,useOpenPBR:!1},T=Math.PI/2,E=Math.PI/2.4;class R{constructor(){this.onEnvironmentChanged=new c,this.onEnvironmentConfigurationChanged=new c,this.onEnvironmentError=new c,this.onShadowsConfigurationChanged=new c,this.onPostProcessingChanged=new c,this.onModelChanged=new c,this.onModelError=new c,this.onLoadingProgressChanged=new c,this.onCameraAutoOrbitChanged=new c,this.onSelectedAnimationChanged=new c,this.onAnimationSpeedChanged=new c,this.onIsAnimationPlayingChanged=new c,this.onAnimationProgressChanged=new c,this.onSelectedMaterialVariantChanged=new c,this.onHotSpotsChanged=new c,this.onCamerasAsHotSpotsChanged=new c,this.onAfterRenderObservable=new c,this.onClearColorChanged=new c,this._loadOperations=new Set,this._isDisposed=!1,this._loadEnvironmentLightingLock=new n,this._loadEnvironmentLightingAbortController=null,this._loadEnvironmentSkyboxLock=new n,this._loadEnvironmentSkyboxAbortController=null,this._environmentIntensity=m.environmentConfig.intensity,this._environmentBlur=m.environmentConfig.blur,this._environmentRotation=m.environmentConfig.rotation,this._autoOrbitEnabled=m.cameraAutoOrbit.enabled,this._autoOrbitSpeed=m.cameraAutoOrbit.speed,this._autoOrbitDelay=m.cameraAutoOrbit.delay,this._clearColor={r:0,g:0,b:0,a:0},this._hotSpots={},this._loadModelLock=new n,this._loadModelAbortController=null,this._updateShadowsLock=new n,this._shadowsAbortController=null,this._shadowQuality=m.shadowConfig.quality}get loadingProgress(){if(this._loadOperations.size>0){let e=0;for(const t of this._loadOperations){if(null==t.progress)return!0;e+=t.progress}return e/this._loadOperations.size}return!1}_beginLoadOperation(){const e=this;let t=null;const s={get progress(){return t},set progress(s){t=s,e.onLoadingProgressChanged.notifyObservers()},dispose:()=>{e._loadOperations.delete(s),e.onLoadingProgressChanged.notifyObservers()}};return this._loadOperations.add(s),this.onLoadingProgressChanged.notifyObservers(),s}_throwIfDisposedOrAborted(...e){if(this._isDisposed)throw new Error("Viewer is disposed.");u(...e)}get _loadEnvironmentLightingAbortSignal(){return this._loadEnvironmentLightingAbortController?.signal}get _loadEnvironmentSkyboxAbortSignal(){return this._loadEnvironmentSkyboxAbortController?.signal}async loadEnvironment(e,t,s){return await this._updateEnvironment(e,t,s)}async resetEnvironment(e,t){return await this._updateEnvironment(void 0,e,t)}async _updateEnvironment(e,t,s){this._throwIfDisposedOrAborted(s);const r=!t||!!t.lighting,a=!t||!!t.skybox;if(!r&&!a)return;const o={...t,lighting:r,skybox:a},h=[],l=[];if(r){this._loadEnvironmentLightingAbortController?.abort(new i("New environment lighting is being loaded before previous environment lighting finished loading."));const e=this._loadEnvironmentLightingAbortController=new AbortController;h.push(this._loadEnvironmentLightingLock),l.push(e)}if(a){this._loadEnvironmentSkyboxAbortController?.abort(new i("New environment skybox is being loaded before previous environment skybox finished loading."));const e=this._loadEnvironmentSkyboxAbortController=new AbortController;h.push(this._loadEnvironmentSkyboxLock),l.push(e)}const c=new AbortController,d=()=>{l.every(e=>e.signal.aborted)&&c.abort(new i(l.map(e=>e.signal.reason).join(" | ")))};for(const e of l)e.signal.addEventListener("abort",d);try{await n.LockAsync(async()=>{u(s,c.signal),await this._loadEnvironmentImpl(e?.trim()??e,o,s,c.signal)},h)}finally{for(const e of l)e.signal.removeEventListener("abort",d)}}get environmentConfig(){return{intensity:this._environmentIntensity,blur:this._environmentBlur,rotation:this._environmentRotation}}set environmentConfig(e){void 0!==e.blur&&e.blur!==this._environmentBlur&&(this._environmentBlur=e.blur,this._applyEnvironmentBlur()),void 0!==e.intensity&&e.intensity!==this._environmentIntensity&&(this._environmentIntensity=e.intensity,this._applyEnvironmentIntensity()),void 0!==e.rotation&&e.rotation!==this._environmentRotation&&(this._environmentRotation=e.rotation,this._applyEnvironmentRotation()),this.onEnvironmentConfigurationChanged.notifyObservers()}get cameraAutoOrbit(){return{enabled:this._autoOrbitEnabled,speed:this._autoOrbitSpeed,delay:this._autoOrbitDelay}}set cameraAutoOrbit(e){let t=!1;void 0!==e.enabled&&e.enabled!==this._autoOrbitEnabled&&(this._autoOrbitEnabled=e.enabled,this._applyCameraAutoOrbitEnabled(),t=!0),void 0!==e.speed&&e.speed!==this._autoOrbitSpeed&&(this._autoOrbitSpeed=e.speed,this._applyCameraAutoOrbitSpeed(),t=!0),void 0!==e.delay&&e.delay!==this._autoOrbitDelay&&(this._autoOrbitDelay=e.delay,this._applyCameraAutoOrbitDelay(),t=!0),t&&this.onCameraAutoOrbitChanged.notifyObservers()}get clearColor(){return this._clearColor}set clearColor(e){this._clearColor.r=e.r,this._clearColor.g=e.g,this._clearColor.b=e.b,this._clearColor.a=e.a,this._applyClearColor(),this.onClearColorChanged.notifyObservers()}get hotSpots(){return this._hotSpots}set hotSpots(e){this._hotSpots=e,this.onHotSpotsChanged.notifyObservers()}get _loadModelAbortSignal(){return this._loadModelAbortController?.signal}async loadModel(e,t,s){return await this._updateModel(e,t,s)}async resetModel(e){return await this._updateModel(void 0,void 0,e)}async _updateModel(e,t,s){this._throwIfDisposedOrAborted(s),this._loadModelAbortController?.abort(new i("New model is being loaded before previous model finished loading."));const r=this._loadModelAbortController=new AbortController;await this._loadModelLock.lockAsync(async()=>{u(s,r.signal),await this._loadModelImpl(e,t,s,r.signal)}),r.signal.aborted||await this._afterLoadModel(e,t,s,r.signal)}async _afterLoadModel(e,t,s,i){}get _shadowsAbortSignal(){return this._shadowsAbortController?.signal}get shadowConfig(){return{quality:this._shadowQuality}}async updateShadows(e,t){if(void 0===e.quality||e.quality===this._shadowQuality)return;const s=this._shadowQuality;this._shadowQuality=e.quality;try{await this._updateShadows(this._shadowQuality,t)}catch(t){throw this._shadowQuality===e.quality&&(this._shadowQuality=s),t}this.onShadowsConfigurationChanged.notifyObservers()}async _updateShadows(e=this._shadowQuality,t){this._throwIfDisposedOrAborted(t),this._shadowsAbortController?.abort(new i("Shadows quality is being changed before previous shadows finished initializing."));const s=this._shadowsAbortController=new AbortController;await this._updateShadowsLock.lockAsync(async()=>{u(t,s.signal),await this._updateShadowsImpl(e,t,s.signal)})}dispose(){this._loadEnvironmentLightingAbortController?.abort(new i("The viewer is being disposed.")),this._loadEnvironmentLightingAbortController=null,this._loadEnvironmentSkyboxAbortController?.abort(new i("The viewer is being disposed.")),this._loadEnvironmentSkyboxAbortController=null,this._loadModelAbortController?.abort(new i("The viewer is being disposed.")),this._loadModelAbortController=null,this._shadowsAbortController?.abort(new i("The viewer is being disposed.")),this._shadowsAbortController=null,this.onEnvironmentChanged.clear(),this.onEnvironmentConfigurationChanged.clear(),this.onEnvironmentError.clear(),this.onShadowsConfigurationChanged.clear(),this.onPostProcessingChanged.clear(),this.onModelChanged.clear(),this.onModelError.clear(),this.onLoadingProgressChanged.clear(),this.onCameraAutoOrbitChanged.clear(),this.onSelectedAnimationChanged.clear(),this.onAnimationSpeedChanged.clear(),this.onIsAnimationPlayingChanged.clear(),this.onAnimationProgressChanged.clear(),this.onSelectedMaterialVariantChanged.clear(),this.onHotSpotsChanged.clear(),this.onCamerasAsHotSpotsChanged.clear(),this.onAfterRenderObservable.clear(),this.onClearColorChanged.clear(),this._isDisposed=!0}reset(...e){this._reset(!0,...e)}_reset(e,...t){const s=0===t.length;(s||t.includes("source"))&&this._resetModel(),(s||t.includes("environment"))&&this._resetEnvironment(),(s||t.includes("shadow"))&&this._resetShadows(),(s||t.includes("animation"))&&this._resetAnimation(),(s||t.includes("camera"))&&this._resetCamera(e),(s||t.includes("post-processing"))&&this._resetPostProcessing(),(s||t.includes("material-variant"))&&this._resetMaterialVariant()}_resetModel(){d(this._updateModel(this._options?.source))}_resetShadows(){d(this.updateShadows({quality:this._options?.shadowConfig?.quality??m.shadowConfig.quality}))}_resetMaterialVariant(){this.selectedMaterialVariant=this._options?.selectedMaterialVariant??null}}function b(e,t,s,i,r,n){function a(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var o,h=i.kind,l="getter"===h?"get":"setter"===h?"set":"value",c=!t&&e?i.static?e:e.prototype:null,u=t||(c?Object.getOwnPropertyDescriptor(c,i.name):{}),d=!1,_=s.length-1;_>=0;_--){var p={};for(var f in i)p[f]="access"===f?{}:i[f];for(var f in i.access)p.access[f]=i.access[f];p.addInitializer=function(e){if(d)throw new TypeError("Cannot add initializers after decoration has completed");n.push(a(e||null))};var g=(0,s[_])("accessor"===h?{get:u.get,set:u.set}:u[l],p);if("accessor"===h){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(o=a(g.get))&&(u.get=o),(o=a(g.set))&&(u.set=o),(o=a(g.init))&&r.unshift(o)}else(o=a(g))&&("field"===h?r.unshift(o):u[l]=o)}c&&Object.defineProperty(c,i.name,u),d=!0}function A(e,t,s){for(var i=arguments.length>2,r=0;r<t.length;r++)s=i?t[r].call(e,s):t[r].call(e);return i?s:void 0}function y(e,t,s){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:s?"".concat(s," ",t):t})}function M(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)}function x(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s}"function"==typeof SuppressedError&&SuppressedError;const S="__bjs_serializable__",v=new WeakMap;function I(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const P=function(){let e=Symbol.metadata;return e||(e=Symbol("Symbol.metadata"),Object.defineProperty(Symbol,"metadata",{configurable:!0,writable:!0,value:e})),e}();function C(e){if(!e)throw new Error(`Decorator metadata is unavailable; the Symbol.metadata (${String(P)}) polyfill must run before decorated classes are evaluated.`);return I(e,S)||(e[S]={}),e[S]}function O(e){const t=function(e){return"function"==typeof e?e:e?.constructor}(e),s=t?t[P]:void 0;if(!s)return{};const i=v.get(s);if(i)return i;const r={},n=[];let a=s;for(;a;)n.push(a),a=Object.getPrototypeOf(a);for(const e of n)if(I(e,S)){const t=e[S];for(const e in t)r[e]=t[e]}return v.set(s,r),r}function D(e,t){return(s,i)=>{if(!i.metadata)return;const r=String(i.name),n=C(i.metadata);n[r]||(n[r]={type:e,sourceName:t})}}function w(e,t=null){return function(e,t=null){return(s,i)=>{const r=t||"_"+String(i.name);return{init(e){return void 0===e&&r in this||(this[r]=e),e},get(){return this[r]},set(t){"function"==typeof this[r]?.equals&&this[r].equals(t)||this[r]!==t&&(this[r]=t,this[e]())}}}}(e,t)}function L(e){return D(0,e)}function F(e){return D(1,e)}function N(e){return D(2,e)}function B(e){return D(3,e)}function U(e){return D(4,e)}function k(e){return D(5,e)}function G(e){return D(6,e)}function V(e){return D(8,e)}function H(e){return D(12,e)}function z(e,t,s){const i=String(t.name);let r=null;const n=function(...a){if(null===r){r=e,"undefined"!=typeof _native&&_native[i]&&(r=s(_native[i],e));const a=this&&(t.static?this:Object.getPrototypeOf(this));a?.[i]===n&&(a[i]=r)}return r.apply(this,a)};return n}function W(e,t){return z(e,t,e=>e)}function X(e,t=null){return(s,i)=>{const r=t||"_"+String(i.name);return{get(){return this[r]?.value},set(t){"function"==typeof this[r]?.value?.equals&&this[r].value.equals(t)||this[r].value!==t&&(this[r].value=t,this[e]())}}}}W.filter=function(e){return(t,s)=>z(t,s,(t,s)=>function(...i){return e(...i)?t(...i):s.apply(this,i)})};const K=1/2.2,Y=2.2;let j=.001;function q(e,t){const s=[];for(let i=0;i<e;++i)s.push(t());return s}function $(e,t){return q(e,t)}const Z=["push","splice","pop","shift","unshift"];function Q(e,t){const s=Z.map(s=>function(e,t,s){const i=e[t];if("function"!=typeof i)return null;const r=function(){const i=e.length,n=r.previous.apply(e,arguments);return s(t,i),n};return i.next=r,r.previous=i,e[t]=r,()=>{const s=r.previous;if(!s)return;const i=r.next;i?(s.next=i,i.previous=s):(s.next=void 0,e[t]=s),r.next=void 0,r.previous=void 0}}(e,s,t));return()=>{for(const e of s)e?.()}}class J{static SetMatrixPrecision(e){if(J.MatrixTrackPrecisionChange=!1,e&&!J.MatrixUse64Bits&&J.MatrixTrackedMatrices)for(let e=0;e<J.MatrixTrackedMatrices.length;++e){const t=J.MatrixTrackedMatrices[e],s=t._m;t._m=new Array(16);for(let e=0;e<16;++e)t._m[e]=s[e]}J.MatrixUse64Bits=e,J.MatrixCurrentType=J.MatrixUse64Bits?Array:Float32Array,J.MatrixTrackedMatrices=null}}J.MatrixUse64Bits=!1,J.MatrixTrackPrecisionChange=!0,J.MatrixCurrentType=Float32Array,J.MatrixTrackedMatrices=[];class ee{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}function te(e,t,s=1401298e-51){return Math.abs(e-t)<=s}function se(e,t){return e===t?e:Math.random()*(t-e)+e}function ie(e,t,s){return e+(t-e)*s}function re(e,t,s,i,r){const n=r*r,a=r*n;return e*(2*a-3*n+1)+s*(-2*a+3*n)+t*(a-2*n+r)+i*(a-n)}function ne(e,t=0,s=1){return Math.min(s,Math.max(t,e))}function ae(e){return e-=2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function oe(e){const t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}function he(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(0===e)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e*=2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}function le(e,t){return e-Math.floor(e/t)*t}function ce(e,t){let s=le(t-e,360);return s>180&&(s-=360),s}function ue(e,t,s){let i;return i=Math.abs(t-e)<=s?t:e+Math.sign(t-e)*s,i}function de(e,t){const s=e%t;return 0===s?t:de(t,s)}ee.Instances=[],ee.OnEnginesDisposedObservable=new c,ee._LastCreatedScene=null,ee.UseFallbackTexture=!0,ee.FallbackTexture="";var _e=Object.freeze({__proto__:null,Clamp:ne,DeltaAngle:ce,Denormalize:function(e,t,s){return e*(s-t)+t},ExtractAsInt:function(e){return parseInt(e.toString().replace(/\W/g,""))},Hermite:re,Hermite1stDerivative:function(e,t,s,i,r){const n=r*r;return 6*(n-r)*e+(3*n-4*r+1)*t+6*(-n+r)*s+(3*n-2*r)*i},HighestCommonFactor:de,ILog2:he,InverseLerp:function(e,t,s){let i;return i=e!=t?ne((s-e)/(t-e)):0,i},Lerp:ie,LerpAngle:function(e,t,s){let i=le(t-e,360);return i>180&&(i-=360),e+i*ne(s)},MoveTowards:ue,MoveTowardsAngle:function(e,t,s){const i=ce(e,t);let r;return r=-s<i&&i<s?t:ue(e,t=e+i,s),r},Normalize:function(e,t,s){return(e-t)/(s-t)},NormalizeRadians:ae,OutsideRange:function(e,t,s,i=1401298e-51){return e<t-i||e>s+i},PercentToRange:function(e,t,s){return(s-t)*e+t},PingPong:function(e,t){const s=le(e,2*t);return t-Math.abs(s-t)},RandomRange:se,RangeToPercent:function(e,t,s){return(e-t)/(s-t)},Repeat:le,SmoothStep:function(e,t,s){let i=ne(s);return i=-2*i*i*i+3*i*i,t*i+e*(1-i)},ToHex:oe,WithinEpsilon:te});class pe{}function fe(e){e.updateFlag=pe._UpdateFlagSeed++}function ge(e,t,s,i=0){const r=e.asArray(),n=t.asArray(),a=r[0],o=r[1],h=r[2],l=r[3],c=r[4],u=r[5],d=r[6],_=r[7],p=r[8],f=r[9],g=r[10],m=r[11],T=r[12],E=r[13],R=r[14],b=r[15],A=n[0],y=n[1],M=n[2],x=n[3],S=n[4],v=n[5],I=n[6],P=n[7],C=n[8],O=n[9],D=n[10],w=n[11],L=n[12],F=n[13],N=n[14],B=n[15];s[i]=a*A+o*S+h*C+l*L,s[i+1]=a*y+o*v+h*O+l*F,s[i+2]=a*M+o*I+h*D+l*N,s[i+3]=a*x+o*P+h*w+l*B,s[i+4]=c*A+u*S+d*C+_*L,s[i+5]=c*y+u*v+d*O+_*F,s[i+6]=c*M+u*I+d*D+_*N,s[i+7]=c*x+u*P+d*w+_*B,s[i+8]=p*A+f*S+g*C+m*L,s[i+9]=p*y+f*v+g*O+m*F,s[i+10]=p*M+f*I+g*D+m*N,s[i+11]=p*x+f*P+g*w+m*B,s[i+12]=T*A+E*S+R*C+b*L,s[i+13]=T*y+E*v+R*O+b*F,s[i+14]=T*M+E*I+R*D+b*N,s[i+15]=T*x+E*P+R*w+b*B}function me(e,t,s,i=0){ge(e,t,s.asArray(),i),fe(s)}function Te(e,t){const s=Ee(e,t.asArray());return s&&fe(t),s}function Ee(e,t){const s=e.asArray(),i=s[0],r=s[1],n=s[2],a=s[3],o=s[4],h=s[5],l=s[6],c=s[7],u=s[8],d=s[9],_=s[10],p=s[11],f=s[12],g=s[13],m=s[14],T=s[15],E=_*T-m*p,R=d*T-g*p,b=d*m-g*_,A=u*T-f*p,y=u*m-_*f,M=u*g-f*d,x=+(h*E-l*R+c*b),S=-(o*E-l*A+c*y),v=+(o*R-h*A+c*M),I=-(o*b-h*y+l*M),P=i*x+r*S+n*v+a*I;if(0===P)return!1;const C=1/P,O=l*T-m*c,D=h*T-g*c,w=h*m-g*l,L=o*T-f*c,F=o*m-f*l,N=o*g-f*h,B=l*p-_*c,U=h*p-d*c,k=h*_-d*l,G=o*p-u*c,V=o*_-u*l,H=o*d-u*h,z=-(r*E-n*R+a*b),W=+(i*E-n*A+a*y),X=-(i*R-r*A+a*M),K=+(i*b-r*y+n*M),Y=+(r*O-n*D+a*w),j=-(i*O-n*L+a*F),q=+(i*D-r*L+a*N),$=-(i*w-r*F+n*N),Z=-(r*B-n*U+a*k),Q=+(i*B-n*G+a*V),J=-(i*U-r*G+a*H),ee=+(i*k-r*V+n*H);return t[0]=x*C,t[1]=z*C,t[2]=Y*C,t[3]=Z*C,t[4]=S*C,t[5]=W*C,t[6]=j*C,t[7]=Q*C,t[8]=v*C,t[9]=X*C,t[10]=q*C,t[11]=J*C,t[12]=I*C,t[13]=K*C,t[14]=$*C,t[15]=ee*C,!0}pe._UpdateFlagSeed=0;const Re={};function be(e,t){Re[e]=t}function Ae(e){return Re[e]}const ye=e=>parseInt(e.toString().replace(/\W/g,""));class Me{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=ye(this.x);return e=397*e^ye(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return Me.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new Me(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new Me(this.x+e.x,this.y+e.y)}subtract(e){return new Me(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new Me(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new Me(this.x*e,this.y*t)}divide(e){return new Me(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new Me(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,s){return s.x=this.x-e,s.y=this.y-t,s}negate(){return new Me(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new Me(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=.001){return e&&te(this.x,e.x,t)&&te(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new Me(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new Me(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotate(e){return this.rotateToRef(e,new Me)}rotateToRef(e,t){const s=Math.cos(e),i=Math.sin(e);return t.x=s*this.x-i*this.y,t.y=i*this.x+s*this.y,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new Me;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?(e.x=this.x,e.y=this.y,e):this.scaleToRef(1/t,e)}clone(){return new Me(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new Me(0,0)}static One(){return new Me(1,1)}static Random(e=0,t=1){return new Me(se(e,t),se(e,t))}static RandomToRef(e=0,t=1,s){return s.copyFromFloats(se(e,t),se(e,t))}static get ZeroReadOnly(){return Me._ZeroReadOnly}static FromArray(e,t=0){return new Me(e[t],e[t+1])}static FromArrayToRef(e,t,s){return s.x=e[t],s.y=e[t+1],s}static FromFloatsToRef(e,t,s){return s.copyFromFloats(e,t),s}static CatmullRom(e,t,s,i,r){const n=r*r,a=r*n,o=.5*(2*t.x+(-e.x+s.x)*r+(2*e.x-5*t.x+4*s.x-i.x)*n+(-e.x+3*t.x-3*s.x+i.x)*a),h=.5*(2*t.y+(-e.y+s.y)*r+(2*e.y-5*t.y+4*s.y-i.y)*n+(-e.y+3*t.y-3*s.y+i.y)*a);return new Me(o,h)}static ClampToRef(e,t,s,i){return i.x=ne(e.x,t.x,s.x),i.y=ne(e.y,t.y,s.y),i}static Clamp(e,t,s){const i=ne(e.x,t.x,s.x),r=ne(e.y,t.y,s.y);return new Me(i,r)}static Hermite(e,t,s,i,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,u=e.x*o+s.x*h+t.x*l+i.x*c,d=e.y*o+s.y*h+t.y*l+i.y*c;return new Me(u,d)}static Hermite1stDerivative(e,t,s,i,r){return this.Hermite1stDerivativeToRef(e,t,s,i,r,new Me)}static Hermite1stDerivativeToRef(e,t,s,i,r,n){const a=r*r;return n.x=6*(a-r)*e.x+(3*a-4*r+1)*t.x+6*(-a+r)*s.x+(3*a-2*r)*i.x,n.y=6*(a-r)*e.y+(3*a-4*r+1)*t.y+6*(-a+r)*s.y+(3*a-2*r)*i.y,n}static Lerp(e,t,s){return Me.LerpToRef(e,t,s,new Me)}static LerpToRef(e,t,s,i){return i.x=e.x+(t.x-e.x)*s,i.y=e.y+(t.y-e.y)*s,i}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return Me.NormalizeToRef(e,new Me)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const s=e.x<t.x?e.x:t.x,i=e.y<t.y?e.y:t.y;return new Me(s,i)}static Maximize(e,t){const s=e.x>t.x?e.x:t.x,i=e.y>t.y?e.y:t.y;return new Me(s,i)}static Transform(e,t){return Me.TransformToRef(e,t,new Me)}static TransformToRef(e,t,s){const i=t.m,r=e.x*i[0]+e.y*i[4]+i[12],n=e.x*i[1]+e.y*i[5]+i[13];return s.x=r,s.y=n,s}static PointInTriangle(e,t,s,i){const r=.5*(-s.y*i.x+t.y*(-s.x+i.x)+t.x*(s.y-i.y)+s.x*i.y),n=r<0?-1:1,a=(t.y*i.x-t.x*i.y+(i.y-t.y)*e.x+(t.x-i.x)*e.y)*n,o=(t.x*s.y-t.y*s.x+(t.y-s.y)*e.x+(s.x-t.x)*e.y)*n;return a>0&&o>0&&a+o<2*r*n}static Distance(e,t){return Math.sqrt(Me.DistanceSquared(e,t))}static DistanceSquared(e,t){const s=e.x-t.x,i=e.y-t.y;return s*s+i*i}static Center(e,t){return Me.CenterToRef(e,t,new Me)}static CenterToRef(e,t,s){return s.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,s){const i=Me.DistanceSquared(t,s);if(0===i)return Me.Distance(e,t);const r=s.subtract(t),n=Math.max(0,Math.min(1,Me.Dot(e.subtract(t),r)/i)),a=t.add(r.multiplyByFloats(n,n));return Me.Distance(e,a)}}Me._V8PerformanceHack=new Me(.5,.5),Me._ZeroReadOnly=Me.Zero();class xe{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,s=0){this._isDirty=!0,this._x=e,this._y=t,this._z=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=ye(this._x);return e=397*e^ye(this._y),e=397*e^ye(this._z),e}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return xe.FromArrayToRef(e,t,this),this}toQuaternion(){return ve.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,s){return this._x+=e,this._y+=t,this._z+=s,this._isDirty=!0,this}add(e){return new xe(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._isDirty=!0,t}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new xe(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,s){return new xe(this._x-e,this._y-t,this._z-s)}subtractFromFloatsToRef(e,t,s,i){return i._x=this._x-e,i._y=this._y-t,i._z=this._z-s,i._isDirty=!0,i}negate(){return new xe(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e._x=-1*this._x,e._y=-1*this._y,e._z=-1*this._z,e._isDirty=!0,e}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new xe(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._isDirty=!0,t}getNormalToRef(e){const t=this.length();let s=Math.acos(this._y/t);const i=Math.atan2(this._z,this._x);s>Math.PI/2?s-=Math.PI/2:s+=Math.PI/2;const r=t*Math.sin(s)*Math.cos(i),n=t*Math.cos(s),a=t*Math.sin(s)*Math.sin(i);return e.set(r,n,a),e}applyRotationQuaternionToRef(e,t){const s=this._x,i=this._y,r=this._z,n=e._x,a=e._y,o=e._z,h=e._w,l=2*(a*r-o*i),c=2*(o*s-n*r),u=2*(n*i-a*s);return t._x=s+h*l+a*u-o*c,t._y=i+h*c+o*l-n*u,t._z=r+h*u+n*c-a*l,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new xe)}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._isDirty=!0,t}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new xe)}projectOnPlaneToRef(e,t,s){const i=e.normal,r=e.d,n=Pe.Vector3[0];this.subtractToRef(t,n),n.normalize();const a=xe.Dot(n,i);if(Math.abs(a)<1e-10)s.setAll(1/0);else{const e=-(xe.Dot(t,i)+r)/a,o=n.scaleInPlace(e);t.addToRef(o,s)}return s}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=.001){return e&&te(this._x,e._x,t)&&te(this._y,e._y,t)&&te(this._z,e._z,t)}equalsToFloats(e,t,s){return this._x===e&&this._y===t&&this._z===s}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t._x=this._x*e._x,t._y=this._y*e._y,t._z=this._z*e._z,t._isDirty=!0,t}multiplyByFloats(e,t,s){return new xe(this._x*e,this._y*t,this._z*s)}divide(e){return new xe(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t._x=this._x/e._x,t._y=this._y/e._y,t._z=this._z/e._z,t._isDirty=!0,t}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,s){return e<this._x&&(this.x=e),t<this._y&&(this.y=t),s<this._z&&(this.z=s),this}maximizeInPlaceFromFloats(e,t,s){return e>this._x&&(this.x=e),t>this._y&&(this.y=t),s>this._z&&(this.z=s),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),s=Math.abs(this._y);if(!te(t,s,e))return!0;const i=Math.abs(this._z);return!te(t,i,e)||!te(s,i,e)}get isNonUniform(){const e=Math.abs(this._x);if(e!==Math.abs(this._y))return!0;return e!==Math.abs(this._z)}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new xe(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fractToRef(e){return e._x=this._x-Math.floor(this._x),e._y=this._y-Math.floor(this._y),e._z=this._z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new xe(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z===0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if("xyz"===(e=e.toLowerCase()))return this;const t=Pe.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(Pe.Matrix[0]),xe.TransformCoordinatesToRef(this,Pe.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,s){return this.subtractToRef(t,Pe.Vector3[0]),Pe.Vector3[0].rotateByQuaternionToRef(e,Pe.Vector3[0]),t.addToRef(Pe.Vector3[0],s),s}cross(e){return xe.CrossToRef(this,e,new xe)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new xe)}normalizeToRef(e){const t=this.length();return 0===t||1===t?(e._x=this._x,e._y=this._y,e._z=this._z,e._isDirty=!0,e):this.scaleToRef(1/t,e)}clone(){return new xe(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,s){return this._x=e,this._y=t,this._z=s,this._isDirty=!0,this}set(e,t,s){return this.copyFromFloats(e,t,s)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,s,i){const r=xe.Dot(e,s);return(r-i)/(r-xe.Dot(t,s))}static GetAngleBetweenVectors(e,t,s){const i=e.normalizeToRef(Pe.Vector3[1]),r=t.normalizeToRef(Pe.Vector3[2]);let n=xe.Dot(i,r);n=ne(n,-1,1);const a=Math.acos(n),o=Pe.Vector3[3];return xe.CrossToRef(i,r,o),xe.Dot(o,s)>0?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,s){Pe.Vector3[0].copyFrom(e);const i=Pe.Vector3[0];Pe.Vector3[1].copyFrom(t);const r=Pe.Vector3[1];Pe.Vector3[2].copyFrom(s);const n=Pe.Vector3[2],a=Pe.Vector3[3],o=Pe.Vector3[4];i.normalize(),r.normalize(),n.normalize(),xe.CrossToRef(n,i,a),xe.CrossToRef(a,n,o);return ae(Math.atan2(xe.Dot(r,a),xe.Dot(r,o)))}static PitchYawRollToMoveBetweenPointsToRef(e,t,s){const i=Ce.Vector3[0];return t.subtractToRef(e,i),s._y=Math.atan2(i.x,i.z)||0,s._x=Math.atan2(Math.sqrt(i.x**2+i.z**2),i.y)||0,s._z=0,s._isDirty=!0,s}static PitchYawRollToMoveBetweenPoints(e,t){const s=xe.Zero();return xe.PitchYawRollToMoveBetweenPointsToRef(e,t,s)}static SlerpToRef(e,t,s,i){s=ne(s,0,1);const r=Pe.Vector3[0],n=Pe.Vector3[1];r.copyFrom(e);const a=r.length();r.normalizeFromLength(a),n.copyFrom(t);const o=n.length();n.normalizeFromLength(o);const h=xe.Dot(r,n);let l,c;if(h<.999){const e=Math.acos(h),t=1/Math.sin(e);l=Math.sin((1-s)*e)*t,c=Math.sin(s*e)*t}else l=1-s,c=s;return r.scaleInPlace(l),n.scaleInPlace(c),i.copyFrom(r).addInPlace(n),i.scaleInPlace(ie(a,o,s)),i}static SmoothToRef(e,t,s,i,r){return xe.SlerpToRef(e,t,0===i?1:s/i,r),r}static FromArray(e,t=0){return new xe(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return xe.FromArray(e,t)}static FromArrayToRef(e,t,s){return s._x=e[t],s._y=e[t+1],s._z=e[t+2],s._isDirty=!0,s}static FromFloatArrayToRef(e,t,s){return xe.FromArrayToRef(e,t,s)}static FromFloatsToRef(e,t,s,i){return i.copyFromFloats(e,t,s),i}static Zero(){return new xe(0,0,0)}static One(){return new xe(1,1,1)}static Up(){return new xe(0,1,0)}static get UpReadOnly(){return xe._UpReadOnly}static get DownReadOnly(){return xe._DownReadOnly}static get RightReadOnly(){return xe._RightReadOnly}static get LeftReadOnly(){return xe._LeftReadOnly}static get LeftHandedForwardReadOnly(){return xe._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return xe._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return xe._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return xe._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return xe._ZeroReadOnly}static get OneReadOnly(){return xe._OneReadOnly}static Down(){return new xe(0,-1,0)}static Forward(e=!1){return new xe(0,0,e?-1:1)}static Backward(e=!1){return new xe(0,0,e?1:-1)}static Right(){return new xe(1,0,0)}static Left(){return new xe(-1,0,0)}static Random(e=0,t=1){return new xe(se(e,t),se(e,t),se(e,t))}static RandomToRef(e=0,t=1,s){return s.copyFromFloats(se(e,t),se(e,t),se(e,t))}static TransformCoordinates(e,t){const s=xe.Zero();return xe.TransformCoordinatesToRef(e,t,s),s}static TransformCoordinatesToRef(e,t,s){return xe.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,s),s}static TransformCoordinatesFromFloatsToRef(e,t,s,i,r){const n=i.m,a=e*n[0]+t*n[4]+s*n[8]+n[12],o=e*n[1]+t*n[5]+s*n[9]+n[13],h=e*n[2]+t*n[6]+s*n[10]+n[14],l=1/(e*n[3]+t*n[7]+s*n[11]+n[15]);return r._x=a*l,r._y=o*l,r._z=h*l,r._isDirty=!0,r}static TransformNormal(e,t){const s=xe.Zero();return xe.TransformNormalToRef(e,t,s),s}static TransformNormalToRef(e,t,s){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,s),s}static TransformNormalFromFloatsToRef(e,t,s,i,r){const n=i.m;return r._x=e*n[0]+t*n[4]+s*n[8],r._y=e*n[1]+t*n[5]+s*n[9],r._z=e*n[2]+t*n[6]+s*n[10],r._isDirty=!0,r}static CatmullRom(e,t,s,i,r){const n=r*r,a=r*n,o=.5*(2*t._x+(-e._x+s._x)*r+(2*e._x-5*t._x+4*s._x-i._x)*n+(-e._x+3*t._x-3*s._x+i._x)*a),h=.5*(2*t._y+(-e._y+s._y)*r+(2*e._y-5*t._y+4*s._y-i._y)*n+(-e._y+3*t._y-3*s._y+i._y)*a),l=.5*(2*t._z+(-e._z+s._z)*r+(2*e._z-5*t._z+4*s._z-i._z)*n+(-e._z+3*t._z-3*s._z+i._z)*a);return new xe(o,h,l)}static Clamp(e,t,s){const i=new xe;return xe.ClampToRef(e,t,s,i),i}static ClampToRef(e,t,s,i){let r=e._x;r=r>s._x?s._x:r,r=r<t._x?t._x:r;let n=e._y;n=n>s._y?s._y:n,n=n<t._y?t._y:n;let a=e._z;return a=a>s._z?s._z:a,a=a<t._z?t._z:a,i.copyFromFloats(r,n,a),i}static CheckExtends(e,t,s){t.minimizeInPlace(e),s.maximizeInPlace(e)}static Hermite(e,t,s,i,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,u=e._x*o+s._x*h+t._x*l+i._x*c,d=e._y*o+s._y*h+t._y*l+i._y*c,_=e._z*o+s._z*h+t._z*l+i._z*c;return new xe(u,d,_)}static Hermite1stDerivative(e,t,s,i,r){const n=new xe;return this.Hermite1stDerivativeToRef(e,t,s,i,r,n),n}static Hermite1stDerivativeToRef(e,t,s,i,r,n){const a=r*r;return n._x=6*(a-r)*e._x+(3*a-4*r+1)*t._x+6*(-a+r)*s._x+(3*a-2*r)*i._x,n._y=6*(a-r)*e._y+(3*a-4*r+1)*t._y+6*(-a+r)*s._y+(3*a-2*r)*i._y,n._z=6*(a-r)*e._z+(3*a-4*r+1)*t._z+6*(-a+r)*s._z+(3*a-2*r)*i._z,n._isDirty=!0,n}static Lerp(e,t,s){const i=new xe(0,0,0);return xe.LerpToRef(e,t,s,i),i}static LerpToRef(e,t,s,i){return i._x=e._x+(t._x-e._x)*s,i._y=e._y+(t._y-e._y)*s,i._z=e._z+(t._z-e._z)*s,i._isDirty=!0,i}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z}static Cross(e,t){const s=new xe;return xe.CrossToRef(e,t,s),s}static CrossToRef(e,t,s){const i=e._y*t._z-e._z*t._y,r=e._z*t._x-e._x*t._z,n=e._x*t._y-e._y*t._x;return s.copyFromFloats(i,r,n),s}static Normalize(e){const t=xe.Zero();return xe.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Project(e,t,s,i){const r=new xe;return xe.ProjectToRef(e,t,s,i,r),r}static ProjectToRef(e,t,s,i,r){const n=i.width,a=i.height,o=i.x,h=i.y,l=Pe.Matrix[1],c=ee.LastCreatedEngine?.isNDCHalfZRange,u=c?1:.5,d=c?0:.5;Ie.FromValuesToRef(n/2,0,0,0,0,-a/2,0,0,0,0,u,0,o+n/2,a/2+h,d,1,l);const _=Pe.Matrix[0];return t.multiplyToRef(s,_),_.multiplyToRef(l,_),xe.TransformCoordinatesToRef(e,_,r),r}static Reflect(e,t){return this.ReflectToRef(e,t,new xe)}static ReflectToRef(e,t,s){const i=Ce.Vector3[0];return i.copyFrom(t).scaleInPlace(2*xe.Dot(e,t)),s.copyFrom(e).subtractInPlace(i)}static UnprojectFromTransform(e,t,s,i,r){return this.Unproject(e,t,s,i,r,Ie.IdentityReadOnly)}static Unproject(e,t,s,i,r,n){const a=new xe;return xe.UnprojectToRef(e,t,s,i,r,n,a),a}static UnprojectToRef(e,t,s,i,r,n,a){return xe.UnprojectFloatsToRef(e._x,e._y,e._z,t,s,i,r,n,a),a}static UnprojectFloatsToRef(e,t,s,i,r,n,a,o,h){const l=Pe.Matrix[0];n.multiplyToRef(a,l),l.multiplyToRef(o,l),l.invert();const c=Pe.Vector3[0];return c.x=e/i*2-1,c.y=-(t/r*2-1),ee.LastCreatedEngine?.isNDCHalfZRange?c.z=s:c.z=2*s-1,xe.TransformCoordinatesToRef(c,l,h),h}static Minimize(e,t){const s=new xe;return s.copyFrom(e),s.minimizeInPlace(t),s}static Maximize(e,t){const s=new xe;return s.copyFrom(e),s.maximizeInPlace(t),s}static Distance(e,t){return Math.sqrt(xe.DistanceSquared(e,t))}static DistanceSquared(e,t){const s=e._x-t._x,i=e._y-t._y,r=e._z-t._z;return s*s+i*i+r*r}static ProjectOnTriangleToRef(e,t,s,i,r){const n=Pe.Vector3[0],a=Pe.Vector3[1],o=Pe.Vector3[2],h=Pe.Vector3[3],l=Pe.Vector3[4];s.subtractToRef(t,n),i.subtractToRef(t,a),i.subtractToRef(s,o);const c=n.length(),u=a.length(),d=o.length();if(c<j||u<j||d<j)return r.copyFrom(t),xe.Distance(e,t);e.subtractToRef(t,l),xe.CrossToRef(n,a,h);const _=h.length();if(_<j)return r.copyFrom(t),xe.Distance(e,t);h.normalizeFromLength(_);let p=l.length();if(p<j)return r.copyFrom(t),0;l.normalizeFromLength(p);const f=xe.Dot(h,l),g=Pe.Vector3[5],m=Pe.Vector3[6];g.copyFrom(h).scaleInPlace(-p*f),m.copyFrom(e).addInPlace(g);const T=Pe.Vector3[4],E=Pe.Vector3[5],R=Pe.Vector3[7],b=Pe.Vector3[8];T.copyFrom(n).scaleInPlace(1/c),b.copyFrom(a).scaleInPlace(1/u),T.addInPlace(b).scaleInPlace(-1),E.copyFrom(n).scaleInPlace(-1/c),b.copyFrom(o).scaleInPlace(1/d),E.addInPlace(b).scaleInPlace(-1),R.copyFrom(o).scaleInPlace(-1/d),b.copyFrom(a).scaleInPlace(-1/u),R.addInPlace(b).scaleInPlace(-1);const A=Pe.Vector3[9];let y;A.copyFrom(m).subtractInPlace(t),xe.CrossToRef(T,A,b),y=xe.Dot(b,h);const M=y;A.copyFrom(m).subtractInPlace(s),xe.CrossToRef(E,A,b),y=xe.Dot(b,h);const x=y;A.copyFrom(m).subtractInPlace(i),xe.CrossToRef(R,A,b),y=xe.Dot(b,h);const S=y,v=Pe.Vector3[10];let I,P;M>0&&x<0?(v.copyFrom(n),I=t,P=s):x>0&&S<0?(v.copyFrom(o),I=s,P=i):(v.copyFrom(a).scaleInPlace(-1),I=i,P=t);const C=Pe.Vector3[9],O=Pe.Vector3[4];I.subtractToRef(m,b),P.subtractToRef(m,C),xe.CrossToRef(b,C,O);if(!(xe.Dot(O,h)<0))return r.copyFrom(m),Math.abs(p*f);const D=Pe.Vector3[5];xe.CrossToRef(v,O,D),D.normalize();const w=Pe.Vector3[9];w.copyFrom(I).subtractInPlace(m);const L=w.length();if(L<j)return r.copyFrom(I),xe.Distance(e,I);w.normalizeFromLength(L);const F=xe.Dot(D,w),N=Pe.Vector3[7];N.copyFrom(m).addInPlace(D.scaleInPlace(L*F)),b.copyFrom(N).subtractInPlace(I),p=v.length(),v.normalizeFromLength(p);let B=xe.Dot(b,v)/Math.max(p,j);return B=ne(B,0,1),N.copyFrom(I).addInPlace(v.scaleInPlace(B*p)),r.copyFrom(N),xe.Distance(e,N)}static Center(e,t){return xe.CenterToRef(e,t,xe.Zero())}static CenterToRef(e,t,s){return s.copyFromFloats((e._x+t._x)/2,(e._y+t._y)/2,(e._z+t._z)/2)}static RotationFromAxis(e,t,s){const i=new xe;return xe.RotationFromAxisToRef(e,t,s,i),i}static RotationFromAxisToRef(e,t,s,i){const r=Pe.Quaternion[0];return ve.RotationQuaternionFromAxisToRef(e,t,s,r),r.toEulerAnglesToRef(i),i}}xe._V8PerformanceHack=new xe(.5,.5,.5),xe._UpReadOnly=xe.Up(),xe._DownReadOnly=xe.Down(),xe._LeftHandedForwardReadOnly=xe.Forward(!1),xe._RightHandedForwardReadOnly=xe.Forward(!0),xe._LeftHandedBackwardReadOnly=xe.Backward(!1),xe._RightHandedBackwardReadOnly=xe.Backward(!0),xe._RightReadOnly=xe.Right(),xe._LeftReadOnly=xe.Left(),xe._ZeroReadOnly=xe.Zero(),xe._OneReadOnly=xe.One();class Se{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,s=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=s,this._w=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Vector4"}getHashCode(){let e=ye(this._x);return e=397*e^ye(this._y),e=397*e^ye(this._z),e=397*e^ye(this._w),e}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t){return void 0===t&&(t=0),e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return Se.FromArrayToRef(e,t,this),this}addInPlace(e){return this.x+=e._x,this.y+=e._y,this.z+=e._z,this.w+=e._w,this}addInPlaceFromFloats(e,t,s,i){return this.x+=e,this.y+=t,this.z+=s,this.w+=i,this}add(e){return new Se(this._x+e.x,this._y+e.y,this._z+e.z,this._w+e.w)}addToRef(e,t){return t.x=this._x+e.x,t.y=this._y+e.y,t.z=this._z+e.z,t.w=this._w+e.w,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subtract(e){return new Se(this._x-e.x,this._y-e.y,this._z-e.z,this._w-e.w)}subtractToRef(e,t){return t.x=this._x-e.x,t.y=this._y-e.y,t.z=this._z-e.z,t.w=this._w-e.w,t}subtractFromFloats(e,t,s,i){return new Se(this._x-e,this._y-t,this._z-s,this._w-i)}subtractFromFloatsToRef(e,t,s,i,r){return r.x=this._x-e,r.y=this._y-t,r.z=this._z-s,r.w=this._w-i,r}negate(){return new Se(-this._x,-this._y,-this._z,-this._w)}negateInPlace(){return this.x*=-1,this.y*=-1,this.z*=-1,this.w*=-1,this}negateToRef(e){return e.x=-this._x,e.y=-this._y,e.z=-this._z,e.w=-this._w,e}scaleInPlace(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}scale(e){return new Se(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t.x=this._x*e,t.y=this._y*e,t.z=this._z*e,t.w=this._w*e,t}scaleAndAddToRef(e,t){return t.x+=this._x*e,t.y+=this._y*e,t.z+=this._z*e,t.w+=this._w*e,t}equals(e){return e&&this._x===e.x&&this._y===e.y&&this._z===e.z&&this._w===e.w}equalsWithEpsilon(e,t=.001){return e&&te(this._x,e.x,t)&&te(this._y,e.y,t)&&te(this._z,e.z,t)&&te(this._w,e.w,t)}equalsToFloats(e,t,s,i){return this._x===e&&this._y===t&&this._z===s&&this._w===i}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiply(e){return new Se(this._x*e.x,this._y*e.y,this._z*e.z,this._w*e.w)}multiplyToRef(e,t){return t.x=this._x*e.x,t.y=this._y*e.y,t.z=this._z*e.z,t.w=this._w*e.w,t}multiplyByFloats(e,t,s,i){return new Se(this._x*e,this._y*t,this._z*s,this._w*i)}divide(e){return new Se(this._x/e.x,this._y/e.y,this._z/e.z,this._w/e.w)}divideToRef(e,t){return t.x=this._x/e.x,t.y=this._y/e.y,t.z=this._z/e.z,t.w=this._w/e.w,t}divideInPlace(e){return this.divideToRef(e,this)}minimizeInPlace(e){return e.x<this._x&&(this.x=e.x),e.y<this._y&&(this.y=e.y),e.z<this._z&&(this.z=e.z),e.w<this._w&&(this.w=e.w),this}maximizeInPlace(e){return e.x>this._x&&(this.x=e.x),e.y>this._y&&(this.y=e.y),e.z>this._z&&(this.z=e.z),e.w>this._w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,s,i){return this.x=Math.min(e,this._x),this.y=Math.min(t,this._y),this.z=Math.min(s,this._z),this.w=Math.min(i,this._w),this}maximizeInPlaceFromFloats(e,t,s,i){return this.x=Math.max(e,this._x),this.y=Math.max(t,this._y),this.z=Math.max(s,this._z),this.w=Math.max(i,this._w),this}floorToRef(e){return e.x=Math.floor(this._x),e.y=Math.floor(this._y),e.z=Math.floor(this._z),e.w=Math.floor(this._w),e}floor(){return new Se(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z),Math.floor(this._w))}fractToRef(e){return e.x=this._x-Math.floor(this._x),e.y=this._y-Math.floor(this._y),e.z=this._z-Math.floor(this._z),e.w=this._w-Math.floor(this._w),e}fract(){return new Se(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z),this._w-Math.floor(this._w))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new Se)}normalizeToRef(e){const t=this.length();return 0===t||1===t?(e.x=this._x,e.y=this._y,e.z=this._z,e.w=this._w,e):this.scaleToRef(1/t,e)}toVector3(){return new xe(this._x,this._y,this._z)}clone(){return new Se(this._x,this._y,this._z,this._w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,this}set(e,t,s,i){return this.copyFromFloats(e,t,s,i)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this._x*e.x+this._y*e.y+this._z*e.z+this._w*e.w}static FromArray(e,t){return t||(t=0),new Se(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,s){return s.x=e[t],s.y=e[t+1],s.z=e[t+2],s.w=e[t+3],s}static FromFloatArrayToRef(e,t,s){return Se.FromArrayToRef(e,t,s),s}static FromFloatsToRef(e,t,s,i,r){return r.x=e,r.y=t,r.z=s,r.w=i,r}static Zero(){return new Se(0,0,0,0)}static One(){return new Se(1,1,1,1)}static Random(e=0,t=1){return new Se(se(e,t),se(e,t),se(e,t),se(e,t))}static RandomToRef(e=0,t=1,s){return s.x=se(e,t),s.y=se(e,t),s.z=se(e,t),s.w=se(e,t),s}static Clamp(e,t,s){return Se.ClampToRef(e,t,s,new Se)}static ClampToRef(e,t,s,i){return i.x=ne(e.x,t.x,s.x),i.y=ne(e.y,t.y,s.y),i.z=ne(e.z,t.z,s.z),i.w=ne(e.w,t.w,s.w),i}static CheckExtends(e,t,s){t.minimizeInPlace(e),s.maximizeInPlace(e)}static get ZeroReadOnly(){return Se._ZeroReadOnly}static Normalize(e){return Se.NormalizeToRef(e,new Se)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const s=new Se;return s.copyFrom(e),s.minimizeInPlace(t),s}static Maximize(e,t){const s=new Se;return s.copyFrom(e),s.maximizeInPlace(t),s}static Distance(e,t){return Math.sqrt(Se.DistanceSquared(e,t))}static DistanceSquared(e,t){const s=e.x-t.x,i=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return s*s+i*i+r*r+n*n}static Center(e,t){return Se.CenterToRef(e,t,new Se)}static CenterToRef(e,t,s){return s.x=(e.x+t.x)/2,s.y=(e.y+t.y)/2,s.z=(e.z+t.z)/2,s.w=(e.w+t.w)/2,s}static TransformCoordinates(e,t){return Se.TransformCoordinatesToRef(e,t,new Se)}static TransformCoordinatesToRef(e,t,s){return Se.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,s),s}static TransformCoordinatesFromFloatsToRef(e,t,s,i,r){const n=i.m,a=e*n[0]+t*n[4]+s*n[8]+n[12],o=e*n[1]+t*n[5]+s*n[9]+n[13],h=e*n[2]+t*n[6]+s*n[10]+n[14],l=e*n[3]+t*n[7]+s*n[11]+n[15];return r.x=a,r.y=o,r.z=h,r.w=l,r}static TransformNormal(e,t){return Se.TransformNormalToRef(e,t,new Se)}static TransformNormalToRef(e,t,s){const i=t.m,r=e.x*i[0]+e.y*i[4]+e.z*i[8],n=e.x*i[1]+e.y*i[5]+e.z*i[9],a=e.x*i[2]+e.y*i[6]+e.z*i[10];return s.x=r,s.y=n,s.z=a,s.w=e.w,s}static TransformNormalFromFloatsToRef(e,t,s,i,r,n){const a=r.m;return n.x=e*a[0]+t*a[4]+s*a[8],n.y=e*a[1]+t*a[5]+s*a[9],n.z=e*a[2]+t*a[6]+s*a[10],n.w=i,n}static FromVector3(e,t=0){return new Se(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}}Se._V8PerformanceHack=new Se(.5,.5,.5,.5),Se._ZeroReadOnly=Se.Zero();class ve{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,s=0,i=1){this._isDirty=!0,this._x=e,this._y=t,this._z=s,this._w=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=ye(this._x);return e=397*e^ye(this._y),e=397*e^ye(this._z),e=397*e^ye(this._w),e}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return ve.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=.001){return e&&te(this._x,e._x,t)&&te(this._y,e._y,t)&&te(this._z,e._z,t)&&te(this._w,e._w,t)}isApprox(e,t=.001){return e&&(te(this._x,e._x,t)&&te(this._y,e._y,t)&&te(this._z,e._z,t)&&te(this._w,e._w,t)||te(this._x,-e._x,t)&&te(this._y,-e._y,t)&&te(this._z,-e._z,t)&&te(this._w,-e._w,t))}clone(){return new ve(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,s,i){return this._x=e,this._y=t,this._z=s,this._w=i,this._isDirty=!0,this}set(e,t,s,i){return this.copyFromFloats(e,t,s,i)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new ve(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,s,i){return this._x+=e,this._y+=t,this._z+=s,this._w+=i,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,s,i){return this.subtractFromFloatsToRef(e,t,s,i,new ve)}subtractFromFloatsToRef(e,t,s,i,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-s,r._w=this._w-i,r._isDirty=!0,r}subtract(e){return new ve(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new ve(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new ve(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const s=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,i=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,n=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(s,i,r,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,s,i){return this._x*=e,this._y*=t,this._z*=s,this._w*=i,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new ve)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,s,i){return this._x===e&&this._y===t&&this._z===s&&this._w===i}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new ve(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return 0==e||1==e||this.scaleInPlace(1/e),this}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new ve(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=xe.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,s=this._x,i=this._y,r=this._w,n=i*t-s*r,a=.4999999;if(n<-a)e._y=2*Math.atan2(i,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>a)e._y=2*Math.atan2(i,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const a=r*r,o=t*t,h=s*s,l=i*i;e._z=Math.atan2(2*(s*i+t*r),-o-h+l+a),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*s+i*r),o-h-l+a),e._isDirty=!0}return e}toAlphaBetaGammaToRef(e){const t=this._z,s=this._x,i=this._y,r=this._w,n=Math.sqrt(s*s+i*i),a=Math.sqrt(t*t+r*r),o=2*Math.atan2(n,a),h=2*Math.atan2(t,r),l=2*Math.atan2(i,s),c=(h+l)/2,u=(h-l)/2;return e.set(u,o,c),e}toRotationMatrix(e){return Ie.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return ve.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}toAxisAngle(){const e=xe.Zero();return{axis:e,angle:this.toAxisAngleToRef(e)}}toAxisAngleToRef(e){let t;const s=Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z),i=this._w;return s>0?(t=2*Math.atan2(s,i),e.set(this._x/s,this._y/s,this._z/s)):(t=0,e.set(1,0,0)),t}static FromRotationMatrix(e){const t=new ve;return ve.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const s=e.m,i=s[0],r=s[4],n=s[8],a=s[1],o=s[5],h=s[9],l=s[2],c=s[6],u=s[10],d=i+o+u;let _;return d>0?(_=.5/Math.sqrt(d+1),t._w=.25/_,t._x=(c-h)*_,t._y=(n-l)*_,t._z=(a-r)*_,t._isDirty=!0):i>o&&i>u?(_=2*Math.sqrt(1+i-o-u),t._w=(c-h)/_,t._x=.25*_,t._y=(r+a)/_,t._z=(n+l)/_,t._isDirty=!0):o>u?(_=2*Math.sqrt(1+o-i-u),t._w=(n-l)/_,t._x=(r+a)/_,t._y=.25*_,t._z=(h+c)/_,t._isDirty=!0):(_=2*Math.sqrt(1+u-i-o),t._w=(a-r)/_,t._x=(n+l)/_,t._y=(h+c)/_,t._z=.25*_,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,s=.1){const i=ve.Dot(e,t);return 1-i*i<=s}static SmoothToRef(e,t,s,i,r){let n=0===i?1:s/i;return n=ne(n,0,1),ve.SlerpToRef(e,t,n,r),r}static Zero(){return new ve(0,0,0,0)}static Inverse(e){return new ve(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new ve(0,0,0,1)}static IsIdentity(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w}static RotationAxis(e,t){return ve.RotationAxisToRef(e,t,new ve)}static RotationAxisToRef(e,t,s){s._w=Math.cos(t/2);const i=Math.sin(t/2)/e.length();return s._x=e._x*i,s._y=e._y*i,s._z=e._z*i,s._isDirty=!0,s}static FromArray(e,t){return t||(t=0),new ve(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,s){return s._x=e[t],s._y=e[t+1],s._z=e[t+2],s._w=e[t+3],s._isDirty=!0,s}static FromFloatsToRef(e,t,s,i,r){return r.copyFromFloats(e,t,s,i),r}static FromEulerAngles(e,t,s){const i=new ve;return ve.RotationYawPitchRollToRef(t,e,s,i),i}static FromEulerAnglesToRef(e,t,s,i){return ve.RotationYawPitchRollToRef(t,e,s,i),i}static FromEulerVector(e){const t=new ve;return ve.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return ve.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,s,i=.001){const r=xe.Dot(e,t)+1;return r<i?Math.abs(e.x)>Math.abs(e.z)?s.set(-e.y,e.x,0,0):s.set(0,-e.z,e.y,0):(xe.CrossToRef(e,t,Ce.Vector3[0]),s.set(Ce.Vector3[0].x,Ce.Vector3[0].y,Ce.Vector3[0].z,r)),s.normalize()}static RotationYawPitchRoll(e,t,s){const i=new ve;return ve.RotationYawPitchRollToRef(e,t,s,i),i}static RotationYawPitchRollToRef(e,t,s,i){const r=.5*s,n=.5*t,a=.5*e,o=Math.sin(r),h=Math.cos(r),l=Math.sin(n),c=Math.cos(n),u=Math.sin(a),d=Math.cos(a);return i._x=d*l*h+u*c*o,i._y=u*c*h-d*l*o,i._z=d*c*o-u*l*h,i._w=d*c*h+u*l*o,i._isDirty=!0,i}static RotationAlphaBetaGamma(e,t,s){const i=new ve;return ve.RotationAlphaBetaGammaToRef(e,t,s,i),i}static RotationAlphaBetaGammaToRef(e,t,s,i){const r=.5*(s+e),n=.5*(s-e),a=.5*t;return i._x=Math.cos(n)*Math.sin(a),i._y=Math.sin(n)*Math.sin(a),i._z=Math.sin(r)*Math.cos(a),i._w=Math.cos(r)*Math.cos(a),i._isDirty=!0,i}static RotationQuaternionFromAxis(e,t,s){const i=new ve(0,0,0,0);return ve.RotationQuaternionFromAxisToRef(e,t,s,i),i}static RotationQuaternionFromAxisToRef(e,t,s,i){const r=Pe.Matrix[0];return e=e.normalizeToRef(Pe.Vector3[0]),t=t.normalizeToRef(Pe.Vector3[1]),s=s.normalizeToRef(Pe.Vector3[2]),Ie.FromXYZAxesToRef(e,t,s,r),ve.FromRotationMatrixToRef(r,i),i}static FromLookDirectionLH(e,t){const s=new ve;return ve.FromLookDirectionLHToRef(e,t,s),s}static FromLookDirectionLHToRef(e,t,s){const i=Pe.Matrix[0];return Ie.LookDirectionLHToRef(e,t,i),ve.FromRotationMatrixToRef(i,s),s}static FromLookDirectionRH(e,t){const s=new ve;return ve.FromLookDirectionRHToRef(e,t,s),s}static FromLookDirectionRHToRef(e,t,s){const i=Pe.Matrix[0];return Ie.LookDirectionRHToRef(e,t,i),ve.FromRotationMatrixToRef(i,s)}static Slerp(e,t,s){const i=ve.Identity();return ve.SlerpToRef(e,t,s,i),i}static SlerpToRef(e,t,s,i){let r,n,a=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,o=!1;if(a<0&&(o=!0,a=-a),a>.999999)n=1-s,r=o?-s:s;else{const e=Math.acos(a),t=1/Math.sin(e);n=Math.sin((1-s)*e)*t,r=o?-Math.sin(s*e)*t:Math.sin(s*e)*t}return i._x=n*e._x+r*t._x,i._y=n*e._y+r*t._y,i._z=n*e._z+r*t._z,i._w=n*e._w+r*t._w,i._isDirty=!0,i}static Hermite(e,t,s,i,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,u=e._x*o+s._x*h+t._x*l+i._x*c,d=e._y*o+s._y*h+t._y*l+i._y*c,_=e._z*o+s._z*h+t._z*l+i._z*c,p=e._w*o+s._w*h+t._w*l+i._w*c;return new ve(u,d,_,p)}static Hermite1stDerivative(e,t,s,i,r){const n=new ve;return this.Hermite1stDerivativeToRef(e,t,s,i,r,n),n}static Hermite1stDerivativeToRef(e,t,s,i,r,n){const a=r*r;return n._x=6*(a-r)*e._x+(3*a-4*r+1)*t._x+6*(-a+r)*s._x+(3*a-2*r)*i._x,n._y=6*(a-r)*e._y+(3*a-4*r+1)*t._y+6*(-a+r)*s._y+(3*a-2*r)*i._y,n._z=6*(a-r)*e._z+(3*a-4*r+1)*t._z+6*(-a+r)*s._z+(3*a-2*r)*i._z,n._w=6*(a-r)*e._w+(3*a-4*r+1)*t._w+6*(-a+r)*s._w+(3*a-2*r)*i._w,n._isDirty=!0,n}static Normalize(e){const t=ve.Zero();return ve.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,s){const i=new ve;return ve.ClampToRef(e,t,s,i),i}static ClampToRef(e,t,s,i){return i.copyFromFloats(ne(e.x,t.x,s.x),ne(e.y,t.y,s.y),ne(e.z,t.z,s.z),ne(e.w,t.w,s.w))}static Random(e=0,t=1){return new ve(se(e,t),se(e,t),se(e,t),se(e,t))}static RandomToRef(e=0,t=1,s){return s.copyFromFloats(se(e,t),se(e,t),se(e,t),se(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(ve.DistanceSquared(e,t))}static DistanceSquared(e,t){const s=e.x-t.x,i=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return s*s+i*i+r*r+n*n}static Center(e,t){return ve.CenterToRef(e,t,ve.Zero())}static CenterToRef(e,t,s){return s.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}ve._V8PerformanceHack=new ve(.5,.5,.5,.5);class Ie{static get Use64Bits(){return J.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=pe._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,s=!1,i=!0){this._isIdentity=e,this._isIdentity3x2=e||s,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&i}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,J.MatrixTrackPrecisionChange&&J.MatrixTrackedMatrices.push(this),this._m=new J.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]||0!==this._m[1]||0!==this._m[2]||0!==this._m[3]||0!==this._m[4]||0!==this._m[6]||0!==this._m[7]||0!==this._m[8]||0!==this._m[9]||0!==this._m[10]||0!==this._m[11]||0!==this._m[12]||0!==this._m[13]||0!==this._m[14]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;const e=this._m,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],a=e[5],o=e[6],h=e[7],l=e[8],c=e[9],u=e[10],d=e[11],_=e[12],p=e[13],f=e[14],g=e[15],m=u*g-f*d,T=c*g-p*d,E=c*f-p*u,R=l*g-_*d,b=l*f-u*_,A=l*p-_*c;return t*+(a*m-o*T+h*E)+s*-(n*m-o*R+h*b)+i*+(n*T-a*R+h*A)+r*-(n*E-a*b+o*A)}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}\n${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}\n${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}\n${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const s=this._m;for(let i=0;i<16;i++)e[t+i]=s[i];return this}asArray(){return this._m}fromArray(e,t=0){return Ie.FromArrayToRef(e,t,this)}copyFromFloats(...e){return Ie.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let s=0;s<16;s++)t[s]=e[s];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let s=0;s<16;s++)t[s]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return Ie.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){const t=new Ie;return this.addToRef(e,t),t}addToRef(e,t){const s=this._m,i=t._m,r=e.m;for(let e=0;e<16;e++)i[e]=s[e]+r[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,s=e.m;return t[0]+=s[0],t[1]+=s[1],t[2]+=s[2],t[3]+=s[3],t[4]+=s[4],t[5]+=s[5],t[6]+=s[6],t[7]+=s[7],t[8]+=s[8],t[9]+=s[9],t[10]+=s[10],t[11]+=s[11],t[12]+=s[12],t[13]+=s[13],t[14]+=s[14],t[15]+=s[15],this.markAsUpdated(),this}addInPlace(e){const t=this._m,s=e.m;for(let e=0;e<16;e++)t[e]+=s[e];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let s=0;s<16;s++)t[s]+=e[s];return this.markAsUpdated(),this}subtract(e){const t=this._m,s=e.m;for(let e=0;e<16;e++)t[e]-=s[e];return this.markAsUpdated(),this}subtractToRef(e,t){const s=this._m,i=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=s[e]-i[e];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,s=e.m;for(let e=0;e<16;e++)t[e]-=s[e];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new Ie)}subtractFromFloatsToRef(...e){const t=e.pop(),s=this._m,i=t._m,r=e;for(let e=0;e<16;e++)i[e]=s[e]-r[e];return t.markAsUpdated(),t}invertToRef(e){return!0===this._isIdentity?(Ie.IdentityToRef(e),e):(Ee(this,e.asArray())?e.markAsUpdated():e.copyFrom(this),e)}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,s){return this._m[12]=e,this._m[13]=t,this._m[14]=s,this.markAsUpdated(),this}addTranslationFromFloats(e,t,s){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=s,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new xe(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){const e=this.m;return Ie.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]),this}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){return function(e,t,s=0){const i=e.asArray();t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],t[s+4]=i[4],t[s+5]=i[5],t[s+6]=i[6],t[s+7]=i[7],t[s+8]=i[8],t[s+9]=i[9],t[s+10]=i[10],t[s+11]=i[11],t[s+12]=i[12],t[s+13]=i[13],t[s+14]=i[14],t[s+15]=i[15]}(this,e,t),this}multiply(e){const t=new Ie;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,s=e.m;for(let e=0;e<16;e++)t[e]*=s[e];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let s=0;s<16;s++)t[s]*=e[s];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),s=this._m,i=t._m,r=e;for(let e=0;e<16;e++)i[e]=s[e]*r[e];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,s){return ge(this,e,t,s),this}divide(e){return this.divideToRef(e,new Ie)}divideToRef(e,t){const s=this._m,i=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=s[e]/i[e];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,s=e.m;for(let e=0;e<16;e++)t[e]/=s[e];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,s=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],s[e]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let s=0;s<16;s++)t[s]=Math.min(t[s],e[s]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,s=e.m;for(let e=0;e<16;e++)t[e]=Math.max(t[e],s[e]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let s=0;s<16;s++)t[s]=Math.max(t[s],e[s]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new Ie)}negateInPlace(){const e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){const t=this._m,s=e._m;for(let e=0;e<16;e++)s[e]=-t[e];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const s=this.m,i=t.m;return s[0]===i[0]&&s[1]===i[1]&&s[2]===i[2]&&s[3]===i[3]&&s[4]===i[4]&&s[5]===i[5]&&s[6]===i[6]&&s[7]===i[7]&&s[8]===i[8]&&s[9]===i[9]&&s[10]===i[10]&&s[11]===i[11]&&s[12]===i[12]&&s[13]===i[13]&&s[14]===i[14]&&s[15]===i[15]}equalsWithEpsilon(e,t=0){const s=this._m,i=e.m;for(let e=0;e<16;e++)if(!te(s[e],i[e],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let s=0;s<16;s++)if(t[s]!=e[s])return!1;return!0}floor(){return this.floorToRef(new Ie)}floorToRef(e){const t=this._m,s=e._m;for(let e=0;e<16;e++)s[e]=Math.floor(t[e]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new Ie)}fractToRef(e){const t=this._m,s=e._m;for(let e=0;e<16;e++)s[e]=t[e]-Math.floor(t[e]);return e.markAsUpdated(),e}clone(){const e=new Ie;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=ye(this._m[0]);for(let t=1;t<16;t++)e=397*e^ye(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new ve,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,s,i,r=!0){if(this._isIdentity)return s&&s.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const n=this._m;if(s&&s.copyFromFloats(n[12],n[13],n[14]),(e=e||Pe.Vector3[0]).x=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),e.y=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),e.z=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]),i){const t=(r?i.absoluteScaling.x:i.scaling.x)<0?-1:1,s=(r?i.absoluteScaling.y:i.scaling.y)<0?-1:1,n=(r?i.absoluteScaling.z:i.scaling.z)<0?-1:1;e.x*=t,e.y*=s,e.z*=n}else this.determinant()<=0&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const s=1/e._x,i=1/e._y,r=1/e._z;Ie.FromValuesToRef(n[0]*s,n[1]*s,n[2]*s,0,n[4]*i,n[5]*i,n[6]*i,0,n[8]*r,n[9]*r,n[10]*r,0,0,0,0,1,Pe.Matrix[0]),ve.FromRotationMatrixToRef(Pe.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new Se(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){const s=4*e;t.x=this._m[s+0],t.y=this._m[s+1],t.z=this._m[s+2],t.w=this._m[s+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){const e=new Ie;return Ie.TransposeToRef(this,e),e}transposeToRef(e){return Ie.TransposeToRef(this,e),e}setRowFromFloats(e,t,s,i,r){if(e<0||e>3)return this;const n=4*e;return this._m[n+0]=t,this._m[n+1]=s,this._m[n+2]=i,this._m[n+3]=r,this.markAsUpdated(),this}scale(e){const t=new Ie;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let s=0;s<16;s++)t._m[s]=this._m[s]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let s=0;s<16;s++)t._m[s]+=this._m[s]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let s=0;s<16;s++)t[s]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=Pe.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const s=e._m;return Ie.FromValuesToRef(s[0],s[1],s[2],0,s[4],s[5],s[6],0,s[8],s[9],s[10],0,0,0,0,1,e),e}getRotationMatrix(){const e=new Ie;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=Pe.Vector3[0];if(!this.decompose(t))return Ie.IdentityToRef(e),e;const s=this._m,i=1/t._x,r=1/t._y,n=1/t._z;return Ie.FromValuesToRef(s[0]*i,s[1]*i,s[2]*i,0,s[4]*r,s[5]*r,s[6]*r,0,s[8]*n,s[9]*n,s[10]*n,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}_convertProjectionToHalfZRangeInPlace(){return this.multiplyToRef(Oe,this),this}static FromArray(e,t=0){const s=new Ie;return Ie.FromArrayToRef(e,t,s),s}static FromArrayToRef(e,t,s){for(let i=0;i<16;i++)s._m[i]=e[i+t];return s.markAsUpdated(),s}static FromFloat32ArrayToRefScaled(e,t,s,i){return i._m[0]=e[0+t]*s,i._m[1]=e[1+t]*s,i._m[2]=e[2+t]*s,i._m[3]=e[3+t]*s,i._m[4]=e[4+t]*s,i._m[5]=e[5+t]*s,i._m[6]=e[6+t]*s,i._m[7]=e[7+t]*s,i._m[8]=e[8+t]*s,i._m[9]=e[9+t]*s,i._m[10]=e[10+t]*s,i._m[11]=e[11+t]*s,i._m[12]=e[12+t]*s,i._m[13]=e[13+t]*s,i._m[14]=e[14+t]*s,i._m[15]=e[15+t]*s,i.markAsUpdated(),i}static get IdentityReadOnly(){return Ie._IdentityReadOnly}static FromValuesToRef(e,t,s,i,r,n,a,o,h,l,c,u,d,_,p,f,g){const m=g._m;m[0]=e,m[1]=t,m[2]=s,m[3]=i,m[4]=r,m[5]=n,m[6]=a,m[7]=o,m[8]=h,m[9]=l,m[10]=c,m[11]=u,m[12]=d,m[13]=_,m[14]=p,m[15]=f,g.markAsUpdated()}static FromValues(e,t,s,i,r,n,a,o,h,l,c,u,d,_,p,f){const g=new Ie,m=g._m;return m[0]=e,m[1]=t,m[2]=s,m[3]=i,m[4]=r,m[5]=n,m[6]=a,m[7]=o,m[8]=h,m[9]=l,m[10]=c,m[11]=u,m[12]=d,m[13]=_,m[14]=p,m[15]=f,g.markAsUpdated(),g}static Compose(e,t,s){const i=new Ie;return Ie.ComposeToRef(e,t,s,i),i}static ComposeToRef(e,t,s,i){const r=i._m,n=t._x,a=t._y,o=t._z,h=t._w,l=n+n,c=a+a,u=o+o,d=n*l,_=n*c,p=n*u,f=a*c,g=a*u,m=o*u,T=h*l,E=h*c,R=h*u,b=e._x,A=e._y,y=e._z;return r[0]=(1-(f+m))*b,r[1]=(_+R)*b,r[2]=(p-E)*b,r[3]=0,r[4]=(_-R)*A,r[5]=(1-(d+m))*A,r[6]=(g+T)*A,r[7]=0,r[8]=(p+E)*y,r[9]=(g-T)*y,r[10]=(1-(d+f))*y,r[11]=0,r[12]=s._x,r[13]=s._y,r[14]=s._z,r[15]=1,i.markAsUpdated(),i}static Identity(){const e=Ie.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return Ie.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){const e=Ie.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){const t=new Ie;return Ie.RotationXToRef(e,t),t}static Invert(e){const t=new Ie;return e.invertToRef(t),t}static RotationXToRef(e,t){const s=Math.sin(e),i=Math.cos(e);return Ie.FromValuesToRef(1,0,0,0,0,i,s,0,0,-s,i,0,0,0,0,1,t),t._updateIdentityStatus(1===i&&0===s),t}static RotationY(e){const t=new Ie;return Ie.RotationYToRef(e,t),t}static RotationYToRef(e,t){const s=Math.sin(e),i=Math.cos(e);return Ie.FromValuesToRef(i,0,-s,0,0,1,0,0,s,0,i,0,0,0,0,1,t),t._updateIdentityStatus(1===i&&0===s),t}static RotationZ(e){const t=new Ie;return Ie.RotationZToRef(e,t),t}static RotationZToRef(e,t){const s=Math.sin(e),i=Math.cos(e);return Ie.FromValuesToRef(i,s,0,0,-s,i,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===i&&0===s),t}static RotationAxis(e,t){const s=new Ie;return Ie.RotationAxisToRef(e,t,s),s}static RotationAxisToRef(e,t,s){const i=Math.sin(-t),r=Math.cos(-t),n=1-r;e=e.normalizeToRef(Pe.Vector3[0]);const a=s._m;return a[0]=e._x*e._x*n+r,a[1]=e._x*e._y*n-e._z*i,a[2]=e._x*e._z*n+e._y*i,a[3]=0,a[4]=e._y*e._x*n+e._z*i,a[5]=e._y*e._y*n+r,a[6]=e._y*e._z*n-e._x*i,a[7]=0,a[8]=e._z*e._x*n-e._y*i,a[9]=e._z*e._y*n+e._x*i,a[10]=e._z*e._z*n+r,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,s.markAsUpdated(),s}static RotationAlignToRef(e,t,s,i=!1){const r=xe.Dot(t,e),n=s._m;if(r<-.999)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=i?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=i?-1:1,n[11]=0;else{const s=xe.Cross(t,e),i=1/(1+r);n[0]=s._x*s._x*i+r,n[1]=s._y*s._x*i-s._z,n[2]=s._z*s._x*i+s._y,n[3]=0,n[4]=s._x*s._y*i+s._z,n[5]=s._y*s._y*i+r,n[6]=s._z*s._y*i-s._x,n[7]=0,n[8]=s._x*s._z*i-s._y,n[9]=s._y*s._z*i+s._x,n[10]=s._z*s._z*i+r,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,s.markAsUpdated(),s}static RotationYawPitchRoll(e,t,s){const i=new Ie;return Ie.RotationYawPitchRollToRef(e,t,s,i),i}static RotationYawPitchRollToRef(e,t,s,i){return ve.RotationYawPitchRollToRef(e,t,s,Pe.Quaternion[0]),Pe.Quaternion[0].toRotationMatrix(i),i}static Scaling(e,t,s){const i=new Ie;return Ie.ScalingToRef(e,t,s,i),i}static ScalingToRef(e,t,s,i){return Ie.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1,i),i._updateIdentityStatus(1===e&&1===t&&1===s),i}static Translation(e,t,s){const i=new Ie;return Ie.TranslationToRef(e,t,s,i),i}static TranslationToRef(e,t,s,i){return Ie.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,s,1,i),i._updateIdentityStatus(0===e&&0===t&&0===s),i}static Lerp(e,t,s){const i=new Ie;return Ie.LerpToRef(e,t,s,i),i}static LerpToRef(e,t,s,i){const r=i._m,n=e.m,a=t.m;for(let e=0;e<16;e++)r[e]=n[e]*(1-s)+a[e]*s;return i.markAsUpdated(),i}static DecomposeLerp(e,t,s){const i=new Ie;return Ie.DecomposeLerpToRef(e,t,s,i),i}static DecomposeLerpToRef(e,t,s,i){const r=Pe.Vector3[0],n=Pe.Quaternion[0],a=Pe.Vector3[1];e.decompose(r,n,a);const o=Pe.Vector3[2],h=Pe.Quaternion[1],l=Pe.Vector3[3];t.decompose(o,h,l);const c=Pe.Vector3[4];xe.LerpToRef(r,o,s,c);const u=Pe.Quaternion[2];ve.SlerpToRef(n,h,s,u);const d=Pe.Vector3[5];return xe.LerpToRef(a,l,s,d),Ie.ComposeToRef(c,u,d,i),i}static LookAtLH(e,t,s){const i=new Ie;return Ie.LookAtLHToRef(e,t,s,i),i}static LookAtLHToRef(e,t,s,i){const r=Pe.Vector3[0],n=Pe.Vector3[1],a=Pe.Vector3[2];t.subtractToRef(e,a),a.normalize(),xe.CrossToRef(s,a,r);const o=r.lengthSquared();0===o?r.x=1:r.normalizeFromLength(Math.sqrt(o)),xe.CrossToRef(a,r,n),n.normalize();const h=-xe.Dot(r,e),l=-xe.Dot(n,e),c=-xe.Dot(a,e);return Ie.FromValuesToRef(r._x,n._x,a._x,0,r._y,n._y,a._y,0,r._z,n._z,a._z,0,h,l,c,1,i),i}static LookAtRH(e,t,s){const i=new Ie;return Ie.LookAtRHToRef(e,t,s,i),i}static LookAtRHToRef(e,t,s,i){const r=Pe.Vector3[0],n=Pe.Vector3[1],a=Pe.Vector3[2];e.subtractToRef(t,a),a.normalize(),xe.CrossToRef(s,a,r);const o=r.lengthSquared();0===o?r.x=1:r.normalizeFromLength(Math.sqrt(o)),xe.CrossToRef(a,r,n),n.normalize();const h=-xe.Dot(r,e),l=-xe.Dot(n,e),c=-xe.Dot(a,e);return Ie.FromValuesToRef(r._x,n._x,a._x,0,r._y,n._y,a._y,0,r._z,n._z,a._z,0,h,l,c,1,i),i}static LookDirectionLH(e,t){const s=new Ie;return Ie.LookDirectionLHToRef(e,t,s),s}static LookDirectionLHToRef(e,t,s){const i=Pe.Vector3[0];i.copyFrom(e),i.scaleInPlace(-1);const r=Pe.Vector3[1];return xe.CrossToRef(t,i,r),Ie.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,s),s}static LookDirectionRH(e,t){const s=new Ie;return Ie.LookDirectionRHToRef(e,t,s),s}static LookDirectionRHToRef(e,t,s){const i=Pe.Vector3[2];return xe.CrossToRef(t,e,i),Ie.FromValuesToRef(i._x,i._y,i._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,s),s}static OrthoLH(e,t,s,i,r){const n=new Ie;return Ie.OrthoLHToRef(e,t,s,i,n,r),n}static OrthoLHToRef(e,t,s,i,r,n){const a=2/e,o=2/t,h=2/(i-s),l=-(i+s)/(i-s);return Ie.FromValuesToRef(a,0,0,0,0,o,0,0,0,0,h,0,0,0,l,1,r),n&&r.multiplyToRef(Oe,r),r._updateIdentityStatus(1===a&&1===o&&1===h&&0===l),r}static OrthoOffCenterLH(e,t,s,i,r,n,a){const o=new Ie;return Ie.OrthoOffCenterLHToRef(e,t,s,i,r,n,o,a),o}static OrthoOffCenterLHToRef(e,t,s,i,r,n,a,o){const h=2/(t-e),l=2/(i-s),c=2/(n-r),u=-(n+r)/(n-r),d=(e+t)/(e-t),_=(i+s)/(s-i);return Ie.FromValuesToRef(h,0,0,0,0,l,0,0,0,0,c,0,d,_,u,1,a),o&&a.multiplyToRef(Oe,a),a.markAsUpdated(),a}static ObliqueOffCenterLHToRef(e,t,s,i,r,n,a,o,h,l,c){const u=-a*Math.cos(o),d=-a*Math.sin(o);return Ie.TranslationToRef(0,0,-h,Pe.Matrix[1]),Ie.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,Pe.Matrix[0]),Pe.Matrix[1].multiplyToRef(Pe.Matrix[0],Pe.Matrix[0]),Ie.TranslationToRef(0,0,h,Pe.Matrix[1]),Pe.Matrix[0].multiplyToRef(Pe.Matrix[1],Pe.Matrix[0]),Ie.OrthoOffCenterLHToRef(e,t,s,i,r,n,l,c),Pe.Matrix[0].multiplyToRef(l,l),l}static OrthoOffCenterRH(e,t,s,i,r,n,a){const o=new Ie;return Ie.OrthoOffCenterRHToRef(e,t,s,i,r,n,o,a),o}static OrthoOffCenterRHToRef(e,t,s,i,r,n,a,o){return Ie.OrthoOffCenterLHToRef(e,t,s,i,r,n,a,o),a._m[10]*=-1,a}static ObliqueOffCenterRHToRef(e,t,s,i,r,n,a,o,h,l,c){const u=a*Math.cos(o),d=a*Math.sin(o);return Ie.TranslationToRef(0,0,h,Pe.Matrix[1]),Ie.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,Pe.Matrix[0]),Pe.Matrix[1].multiplyToRef(Pe.Matrix[0],Pe.Matrix[0]),Ie.TranslationToRef(0,0,-h,Pe.Matrix[1]),Pe.Matrix[0].multiplyToRef(Pe.Matrix[1],Pe.Matrix[0]),Ie.OrthoOffCenterRHToRef(e,t,s,i,r,n,l,c),Pe.Matrix[0].multiplyToRef(l,l),l}static PerspectiveLH(e,t,s,i,r,n=0){const a=new Ie,o=2*s/e,h=2*s/t,l=(i+s)/(i-s),c=-2*i*s/(i-s),u=Math.tan(n);return Ie.FromValuesToRef(o,0,0,0,0,h,0,u,0,0,l,1,0,0,c,0,a),r&&a.multiplyToRef(Oe,a),a._updateIdentityStatus(!1),a}static PerspectiveFovLH(e,t,s,i,r,n=0,a=!1){const o=new Ie;return Ie.PerspectiveFovLHToRef(e,t,s,i,o,!0,r,n,a),o}static PerspectiveFovLHToRef(e,t,s,i,r,n=!0,a,o=0,h=!1){const l=s,c=i,u=1/Math.tan(.5*e),d=n?u/t:u,_=n?u:u*t,p=h&&0===l?-1:0!==c?(c+l)/(c-l):1,f=h&&0===l?2*c:0!==c?-2*c*l/(c-l):-2*l,g=Math.tan(o);return Ie.FromValuesToRef(d,0,0,0,0,_,0,g,0,0,p,1,0,0,f,0,r),a&&r.multiplyToRef(Oe,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,s,i,r,n=!0,a,o=0){const h=1/Math.tan(.5*e),l=n?h/t:h,c=n?h:h*t,u=Math.tan(o);return Ie.FromValuesToRef(l,0,0,0,0,c,0,u,0,0,-s,1,0,0,1,0,r),a&&r.multiplyToRef(Oe,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,s,i,r,n=0,a=!1){const o=new Ie;return Ie.PerspectiveFovRHToRef(e,t,s,i,o,!0,r,n,a),o}static PerspectiveFovRHToRef(e,t,s,i,r,n=!0,a,o=0,h=!1){const l=s,c=i,u=1/Math.tan(.5*e),d=n?u/t:u,_=n?u:u*t,p=h&&0===l?1:0!==c?-(c+l)/(c-l):-1,f=h&&0===l?2*c:0!==c?-2*c*l/(c-l):-2*l,g=Math.tan(o);return Ie.FromValuesToRef(d,0,0,0,0,_,0,g,0,0,p,-1,0,0,f,0,r),a&&r.multiplyToRef(Oe,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,s,i,r,n=!0,a,o=0){const h=1/Math.tan(.5*e),l=n?h/t:h,c=n?h:h*t,u=Math.tan(o);return Ie.FromValuesToRef(l,0,0,0,0,c,0,u,0,0,-s,-1,0,0,-1,0,r),a&&r.multiplyToRef(Oe,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,s,i,r,n){const a=e.width,o=e.height,h=e.x,l=e.y,c=Ie.FromValues(a/2,0,0,0,0,-o/2,0,0,0,0,n-r,0,h+a/2,o/2+l,r,1),u=new Ie;return t.multiplyToRef(s,u),u.multiplyToRef(i,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){const t=e.m,s=[t[0],t[1],t[4],t[5]];return J.MatrixUse64Bits?s:new Float32Array(s)}static GetAsMatrix3x3(e){const t=e.m,s=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return J.MatrixUse64Bits?s:new Float32Array(s)}static Transpose(e){const t=new Ie;return Ie.TransposeToRef(e,t),t}static TransposeToRef(e,t){const s=e.m,i=s[0],r=s[4],n=s[8],a=s[12],o=s[1],h=s[5],l=s[9],c=s[13],u=s[2],d=s[6],_=s[10],p=s[14],f=s[3],g=s[7],m=s[11],T=s[15],E=t._m;return E[0]=i,E[1]=r,E[2]=n,E[3]=a,E[4]=o,E[5]=h,E[6]=l,E[7]=c,E[8]=u,E[9]=d,E[10]=_,E[11]=p,E[12]=f,E[13]=g,E[14]=m,E[15]=T,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new Ie;return Ie.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const s=e.normal.x,i=e.normal.y,r=e.normal.z,n=-2*s,a=-2*i,o=-2*r;return Ie.FromValuesToRef(n*s+1,a*s,o*s,0,n*i,a*i+1,o*i,0,n*r,a*r,o*r+1,0,n*e.d,a*e.d,o*e.d,1,t),t}static FromXYZAxesToRef(e,t,s,i){return Ie.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static FromQuaternionToRef(e,t){const s=e._x*e._x,i=e._y*e._y,r=e._z*e._z,n=e._x*e._y,a=e._z*e._w,o=e._z*e._x,h=e._y*e._w,l=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(i+r),t._m[1]=2*(n+a),t._m[2]=2*(o-h),t._m[3]=0,t._m[4]=2*(n-a),t._m[5]=1-2*(r+s),t._m[6]=2*(l+c),t._m[7]=0,t._m[8]=2*(o+h),t._m[9]=2*(l-c),t._m[10]=1-2*(i+s),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}Ie._IdentityReadOnly=Ie.Identity();class Pe{}Pe.Vector3=$(11,xe.Zero),Pe.Matrix=$(2,Ie.Identity),Pe.Quaternion=$(3,ve.Zero);class Ce{}Ce.Vector2=$(3,Me.Zero),Ce.Vector3=$(13,xe.Zero),Ce.Vector4=$(3,Se.Zero),Ce.Quaternion=$(3,ve.Zero),Ce.Matrix=$(8,Ie.Identity);const Oe=Ie.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);let De=!1;const we={};function Le(e,t=!1){if(!t||!we[e])return we[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}const Fe={};function Ne(e,t,s=!1){const i=function(){if(s){const s=`${e}.${t}`;Fe[s]||(Fe[s]=!0,console.warn(`[Babylon.js] ${s}() requires a side-effect import. See: https://doc.babylonjs.com/setup/treeshaking`))}};return i.__isSideEffectStub=!0,i}function Be(e){return!!e&&!e.__isSideEffectStub}function Ue(e,t){return{get(){},set(e){Object.defineProperty(this,t,{value:e,writable:!0,configurable:!0,enumerable:!0})},configurable:!0,enumerable:!0}}class ke{static Eval(e,t){return e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,e=>(e=e.slice(1,e.length-1),ke._HandleParenthesisContent(e,t))):ke._HandleParenthesisContent(e,t),"true"===e||"false"!==e&&ke.Eval(e,t)}static _HandleParenthesisContent(e,t){let s;t=t||(e=>"true"===e);const i=e.split("||");for(const e in i)if(Object.prototype.hasOwnProperty.call(i,e)){let r=ke._SimplifyNegation(i[e].trim());const n=r.split("&&");if(n.length>1)for(let e=0;e<n.length;++e){const i=ke._SimplifyNegation(n[e].trim());if(s="true"!==i&&"false"!==i?"!"===i[0]?!t(i.substring(1)):t(i):"true"===i,!s){r="false";break}}if(s||"true"===r){s=!0;break}s="true"!==r&&"false"!==r?"!"===r[0]?!t(r.substring(1)):t(r):"true"===r}return s?"true":"false"}static _SimplifyNegation(e){return e=e.replace(/^[\s!]+/,e=>(e=e.replace(/[\s]/g,()=>"")).length%2?"!":""),"!true"===(e=e.trim())?e="false":"!false"===e&&(e="true"),e}}class Ge{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>Ge.HasTags(e),e.addTags=t=>Ge.AddTagsTo(e,t),e.removeTags=t=>Ge.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Ge.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const t=[];for(const s in e._tags)Object.prototype.hasOwnProperty.call(e._tags,s)&&!0===e._tags[s]&&t.push(s);return t.join(" ")}return e._tags}static AddTagsTo(e,t){if(!t)return;if("string"!=typeof t)return;const s=t.split(" ");for(const t of s)Ge._AddTagTo(e,t)}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Ge.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!Ge.HasTags(e))return;const s=t.split(" ");for(const t in s)Ge._RemoveTagFrom(e,s[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?Ge.HasTags(e):ke.Eval(t,t=>Ge.HasTags(e)&&e._tags[t]))}}function Ve(e){return Math.pow(e,2.2)}function He(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function ze(e){return Math.pow(e,K)}function We(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}class Xe{constructor(e=0,t=0,s=0){this.r=e,this.g=t,this.b=s}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return Xe.FromArrayToRef(e,t,this),this}toColor4(e=1){return new Ke(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return.3*this.r+.59*this.g+.11*this.b}multiply(e){return new Xe(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,s){return new Xe(this.r*e,this.g*t,this.b*s)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,s){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(s,this.b),this}maximizeInPlaceFromFloats(e,t,s){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(s,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,s){return this.equalsToFloats(e,t,s)}equalsToFloats(e,t,s){return this.r===e&&this.g===t&&this.b===s}equalsWithEpsilon(e,t=.001){return te(this.r,e.r,t)&&te(this.g,e.g,t)&&te(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new Xe(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,s){return s.r=ne(this.r,e,t),s.g=ne(this.g,e,t),s.b=ne(this.b,e,t),s}add(e){return new Xe(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,s){return this.r+=e,this.g+=t,this.b+=s,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new Xe(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,s){return new Xe(this.r-e,this.g-t,this.b-s)}subtractFromFloatsToRef(e,t,s,i){return i.r=this.r-e,i.g=this.g-t,i.b=this.b-s,i}clone(){return new Xe(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,s){return this.r=e,this.g=t,this.b=s,this}set(e,t,s){return this.copyFromFloats(e,t,s)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){const e=Math.round(255*this.r),t=Math.round(255*this.g),s=Math.round(255*this.b);return"#"+oe(e)+oe(t)+oe(s)}fromHexString(e){return"#"!==e.substring(0,1)||7!==e.length||(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255),this}toHSV(){return this.toHSVToRef(new Xe)}toHSVToRef(e){const t=this.r,s=this.g,i=this.b,r=Math.max(t,s,i),n=Math.min(t,s,i);let a=0,o=0;const h=r,l=r-n;return 0!==r&&(o=l/r),r!=n&&(r==t?(a=(s-i)/l,s<i&&(a+=6)):r==s?a=(i-t)/l+2:r==i&&(a=(t-s)/l+4),a*=60),e.r=a,e.g=o,e.b=h,e}toLinearSpace(e=!1){const t=new Xe;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=He(this.r),e.g=He(this.g),e.b=He(this.b)):(e.r=Ve(this.r),e.g=Ve(this.g),e.b=Ve(this.b)),this}toGammaSpace(e=!1){const t=new Xe;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=We(this.r),e.g=We(this.g),e.b=We(this.b)):(e.r=ze(this.r),e.g=ze(this.g),e.b=ze(this.b)),this}static HSVtoRGBToRef(e,t,s,i){const r=s*t,n=e/60,a=r*(1-Math.abs(n%2-1));let o=0,h=0,l=0;n>=0&&n<=1?(o=r,h=a):n>=1&&n<=2?(o=a,h=r):n>=2&&n<=3?(h=r,l=a):n>=3&&n<=4?(h=a,l=r):n>=4&&n<=5?(o=a,l=r):n>=5&&n<=6&&(o=r,l=a);const c=s-r;return i.r=o+c,i.g=h+c,i.b=l+c,i}static FromHSV(e,t,s){const i=new Xe(0,0,0);return Xe.HSVtoRGBToRef(e,t,s,i),i}static FromHexString(e){return new Xe(0,0,0).fromHexString(e)}static FromArray(e,t=0){return new Xe(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,s){s.r=e[t],s.g=e[t+1],s.b=e[t+2]}static FromInts(e,t,s){return new Xe(e/255,t/255,s/255)}static Lerp(e,t,s){const i=new Xe(0,0,0);return Xe.LerpToRef(e,t,s,i),i}static LerpToRef(e,t,s,i){i.r=e.r+(t.r-e.r)*s,i.g=e.g+(t.g-e.g)*s,i.b=e.b+(t.b-e.b)*s}static Hermite(e,t,s,i,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,u=e.r*o+s.r*h+t.r*l+i.r*c,d=e.g*o+s.g*h+t.g*l+i.g*c,_=e.b*o+s.b*h+t.b*l+i.b*c;return new Xe(u,d,_)}static Hermite1stDerivative(e,t,s,i,r){const n=Xe.Black();return this.Hermite1stDerivativeToRef(e,t,s,i,r,n),n}static Hermite1stDerivativeToRef(e,t,s,i,r,n){const a=r*r;n.r=6*(a-r)*e.r+(3*a-4*r+1)*t.r+6*(-a+r)*s.r+(3*a-2*r)*i.r,n.g=6*(a-r)*e.g+(3*a-4*r+1)*t.g+6*(-a+r)*s.g+(3*a-2*r)*i.g,n.b=6*(a-r)*e.b+(3*a-4*r+1)*t.b+6*(-a+r)*s.b+(3*a-2*r)*i.b}static Red(){return new Xe(1,0,0)}static Green(){return new Xe(0,1,0)}static Blue(){return new Xe(0,0,1)}static Black(){return new Xe(0,0,0)}static get BlackReadOnly(){return Xe._BlackReadOnly}static White(){return new Xe(1,1,1)}static Purple(){return new Xe(.5,0,.5)}static Magenta(){return new Xe(1,0,1)}static Yellow(){return new Xe(1,1,0)}static Gray(){return new Xe(.5,.5,.5)}static Teal(){return new Xe(0,1,1)}static Random(){return new Xe(Math.random(),Math.random(),Math.random())}}Xe._V8PerformanceHack=new Xe(.5,.5,.5),Xe._BlackReadOnly=Xe.Black();class Ke{constructor(e=0,t=0,s=0,i=1){this.r=e,this.g=t,this.b=s,this.a=i}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new Ke(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,s,i){return this.r+=e,this.g+=t,this.b+=s,this.a+=i,this}subtract(e){return new Ke(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,s,i){return new Ke(this.r-e,this.g-t,this.b-s,this.a-i)}subtractFromFloatsToRef(e,t,s,i,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-s,r.a=this.a-i,r}scale(e){return new Ke(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,s){return s.r=ne(this.r,e,t),s.g=ne(this.g,e,t),s.b=ne(this.b,e,t),s.a=ne(this.a,e,t),s}multiply(e){return new Ke(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,s,i){return new Ke(this.r*e,this.g*t,this.b*s,this.a*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,s,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(s,this.b),this.a=Math.min(i,this.a),this}maximizeInPlaceFromFloats(e,t,s,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(s,this.b),this.a=Math.max(i,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=.001){return te(this.r,e.r,t)&&te(this.g,e.g,t)&&te(this.b,e.b,t)&&te(this.a,e.a,t)}equalsToFloats(e,t,s,i){return this.r===e&&this.g===t&&this.b===s&&this.a===i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e=397*e^255*this.a,e}clone(){return(new Ke).copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,s,i){return this.r=e,this.g=t,this.b=s,this.a=i,this}set(e,t,s,i){return this.copyFromFloats(e,t,s,i)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(255*this.r),s=Math.round(255*this.g),i=Math.round(255*this.b);if(e)return"#"+oe(t)+oe(s)+oe(i);const r=Math.round(255*this.a);return"#"+oe(t)+oe(s)+oe(i)+oe(r)}fromHexString(e){return"#"!==e.substring(0,1)||9!==e.length&&7!==e.length||(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255,9===e.length&&(this.a=parseInt(e.substring(7,9),16)/255)),this}toLinearSpace(e=!1){const t=new Ke;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=He(this.r),e.g=He(this.g),e.b=He(this.b)):(e.r=Ve(this.r),e.g=Ve(this.g),e.b=Ve(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new Ke;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=We(this.r),e.g=We(this.g),e.b=We(this.b)):(e.r=ze(this.r),e.g=ze(this.g),e.b=ze(this.b)),e.a=this.a,this}static FromHexString(e){return"#"!==e.substring(0,1)||9!==e.length&&7!==e.length?new Ke(0,0,0,0):new Ke(0,0,0,1).fromHexString(e)}static Lerp(e,t,s){return Ke.LerpToRef(e,t,s,new Ke)}static LerpToRef(e,t,s,i){return i.r=e.r+(t.r-e.r)*s,i.g=e.g+(t.g-e.g)*s,i.b=e.b+(t.b-e.b)*s,i.a=e.a+(t.a-e.a)*s,i}static Hermite(e,t,s,i,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,u=e.r*o+s.r*h+t.r*l+i.r*c,d=e.g*o+s.g*h+t.g*l+i.g*c,_=e.b*o+s.b*h+t.b*l+i.b*c,p=e.a*o+s.a*h+t.a*l+i.a*c;return new Ke(u,d,_,p)}static Hermite1stDerivative(e,t,s,i,r){const n=new Ke;return this.Hermite1stDerivativeToRef(e,t,s,i,r,n),n}static Hermite1stDerivativeToRef(e,t,s,i,r,n){const a=r*r;n.r=6*(a-r)*e.r+(3*a-4*r+1)*t.r+6*(-a+r)*s.r+(3*a-2*r)*i.r,n.g=6*(a-r)*e.g+(3*a-4*r+1)*t.g+6*(-a+r)*s.g+(3*a-2*r)*i.g,n.b=6*(a-r)*e.b+(3*a-4*r+1)*t.b+6*(-a+r)*s.b+(3*a-2*r)*i.b,n.a=6*(a-r)*e.a+(3*a-4*r+1)*t.a+6*(-a+r)*s.a+(3*a-2*r)*i.a}static FromColor3(e,t=1){return new Ke(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Ke(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,s){s.r=e[t],s.g=e[t+1],s.b=e[t+2],s.a=e[t+3]}static FromInts(e,t,s,i){return new Ke(e/255,t/255,s/255,i/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let s=0;s<e.length;s+=3){const i=s/3*4;t[i]=e[s],t[i+1]=e[s+1],t[i+2]=e[s+2],t[i+3]=1}return t}return e}}Ke._V8PerformanceHack=new Ke(.5,.5,.5,.5);class Ye{}Ye.Color3=q(3,Xe.Black),Ye.Color4=q(3,()=>new Ke(0,0,0,0));let je=!1;const qe=function(e,t,s,i={}){const r=e();Ge&&Ge.HasTags(t)&&Ge.AddTagsTo(r,Ge.GetTags(t,!0));const n=O(r),a={};for(const e in n){const o=n[e],h=t[e],l=o.type;if(null!=h&&("uniqueId"!==e||$e.AllowLoadingUniqueId))switch(l){case 0:case 6:case 9:case 11:"function"==typeof h.slice?r[e]=h.slice():r[e]=h;break;case 1:i.cloneTexturesOnlyOnce&&a[h.uniqueId]?r[e]=a[h.uniqueId]:(r[e]=s||h.isRenderTarget?h:h.clone(),a[h.uniqueId]=r[e]);break;case 2:case 3:case 4:case 5:case 7:case 8:case 10:case 12:case 13:r[e]=s?h:h.clone()}}return r};class $e{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let s=0;s<e.animations.length;s++){const i=e.animations[s];t.animations.push(i.serialize())}}}static Serialize(e,t){t||(t={}),Ge&&(t.tags=Ge.GetTags(e));const s=O(e);for(const i in s){const r=s[i],n=r.sourceName||i,a=r.type,o=e[i];if(null!=o&&("uniqueId"!==i||$e.AllowLoadingUniqueId))switch(a){case 0:Array.isArray(o)?t[n]=o.slice():t[n]=o;break;case 1:case 3:case 7:case 9:t[n]=o.serialize();break;case 2:case 4:case 5:case 8:case 10:case 12:case 13:t[n]=o.asArray();break;case 6:case 11:t[n]=o.id}}return t}static ParseProperties(e,t,s,i){i||(i="");const r=O(t);for(const n in r){const a=r[n],o=e[a.sourceName||n],h=a.type;if(null!=o&&("uniqueId"!==n||$e.AllowLoadingUniqueId)){const e=t;switch(h){case 0:e[n]=o;break;case 1:s&&(e[n]=$e._TextureParser(o,s,i));break;case 2:e[n]=Xe.FromArray(o);break;case 3:e[n]=$e._FresnelParametersParser(o);break;case 4:e[n]=Me.FromArray(o);break;case 5:e[n]=xe.FromArray(o);break;case 6:s&&(e[n]=s.getLastMeshById(o));break;case 7:e[n]=$e._ColorCurvesParser(o);break;case 8:e[n]=Ke.FromArray(o);break;case 9:e[n]=$e._ImageProcessingConfigurationParser(o);break;case 10:e[n]=ve.FromArray(o);break;case 11:s&&(e[n]=s.getCameraById(o));break;case 12:e[n]=Ie.FromArray(o);break;case 13:e[n]=Se.FromArray(o)}}}}static Parse(e,t,s,i=null){const r=e();return Ge&&Ge.AddTagsTo(r,t.tags),$e.ParseProperties(t,r,s,i),r}static Clone(e,t,s={}){return qe(e,t,!1,s)}static Instanciate(e,t){return qe(e,t,!0)}}$e.AllowLoadingUniqueId=!1,$e._ImageProcessingConfigurationParser=e=>{throw Le("ImageProcessingConfiguration")},$e._FresnelParametersParser=e=>{throw Le("FresnelParameters")},$e._ColorCurvesParser=e=>{throw Le("ColorCurves")},$e._TextureParser=(e,t,s)=>{throw Le("Texture")};class Ze{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new c,this._onEffectiveEnabledStateChangedObservable=null,this._onClonedObservable=new c,this._inheritVisibility=!1,this._isVisible=!0}}let Qe=(()=>{var e;let t,s,i,r,n,a=[],o=[],h=[],l=[],u=[],d=[],_=[],p=[],f=[],g=[];return e=class{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,s,i){const r=this._NodeConstructors[e];return r?r(t,s,i):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;const t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){const t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}get inheritVisibility(){return this._nodeDataStorage._inheritVisibility}set inheritVisibility(e){this._nodeDataStorage._inheritVisibility=e}get isVisible(){return!(this.inheritVisibility&&this._parentNode&&!this._parentNode.isVisible)&&this._nodeDataStorage._isVisible}set isVisible(e){this._nodeDataStorage._isVisible=e}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){-1===this._nodeDataStorage._sceneRootNodesIndex&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(-1!==this._nodeDataStorage._sceneRootNodesIndex){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onEffectiveEnabledStateChangedObservable(){return this._nodeDataStorage._onEffectiveEnabledStateChangedObservable??=new c}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,s=!0){this._isDirty=!1,this._nodeDataStorage=new Ze,this.name=A(this,a,void 0),this.id=(A(this,o),A(this,h,void 0)),this.uniqueId=(A(this,l),A(this,u,void 0)),this.state=(A(this,d),A(this,_,"")),this.metadata=(A(this,p),A(this,f,null)),this._internalMetadata=A(this,g),this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new c,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=Ie.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new c,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||ee.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),s&&this._addToSceneRootNodes()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return-1!==this._behaviors.indexOf(e)||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(()=>{this._behaviors.includes(e)&&e.attach(this)}):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors.splice(t,1),e.detach()),this}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={}}updateCache(e){!e&&this.isSynchronized()||this._updateCache()}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return!this._parentNode||!this._parentNode._isDirty&&this._parentUpdateId===this._parentNode._childUpdateId&&this._parentNode.isSynchronized()}isSynchronized(){return!(this._parentNode&&!this.isSynchronizedWithParent())&&this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return!1===e?this._nodeDataStorage._isEnabled:!!this._nodeDataStorage._isEnabled&&this._nodeDataStorage._isParentEnabled}_hasEffectiveEnabledStateObservers(){const e=this._nodeDataStorage._onEffectiveEnabledStateChangedObservable;return!!e&&e.hasObservers()}_syncParentEnabledState(){const e=this._hasEffectiveEnabledStateObservers(),t=e?this.isEnabled():null;if(this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),this._children)for(const e of this._children)e._syncParentEnabledState();if(e){const e=this.isEnabled();e!==t&&this._nodeDataStorage._onEffectiveEnabledStateChangedObservable.notifyObservers(e)}}setEnabled(e){if(this._nodeDataStorage._isEnabled===e)return;const t=this._hasEffectiveEnabledStateObservers(),s=t?this.isEnabled():null;if(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e),t){const e=this.isEnabled();e!==s&&this._nodeDataStorage._onEffectiveEnabledStateChangedObservable.notifyObservers(e)}}isDescendantOf(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))}_getDescendants(e,t=!1,s){if(this._children)for(let i=0;i<this._children.length;i++){const r=this._children[i];s&&!s(r)||e.push(r),t||r._getDescendants(e,!1,s)}}getDescendants(e,t){const s=[];return this._getDescendants(s,e,t),s}getChildMeshes(e,t){const s=[];return this._getDescendants(s,e,e=>(!t||t(e))&&void 0!==e.cullingStrategy),s}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;t<this.animations.length;t++){const s=this.animations[t];if(s.name===e)return s}return null}createAnimationRange(t,s,i){if(!this._ranges[t]){this._ranges[t]=e._AnimationRangeFactory(t,s,i);for(let e=0,r=this.animations.length;e<r;e++)this.animations[e]&&this.animations[e].createRange(t,s,i)}}deleteAnimationRange(e,t=!0){for(let s=0,i=this.animations.length;s<i;s++)this.animations[s]&&this.animations[s].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}clone(t,s,i){const r=$e.Clone(()=>new e(t,this.getScene()),this);if(s&&(r.parent=s),!i){const e=this.getDescendants(!0);for(let s=0;s<e.length;s++){const i=e[s];i.clone(t+"."+i.name,r)}}return r}getAnimationRanges(){const e=[];let t;for(t in this._ranges)e.push(this._ranges[t]);return e}beginAnimation(e,t,s,i){const r=this.getAnimationRange(e);return r?this._scene.beginAnimation(this,r.from,r.to,t,s,i):null}serializeAnimationRanges(){const e=[];for(const t in this._ranges){const s=this._ranges[t];if(!s)continue;const i={};i.name=t,i.from=s.from,i.to=s.to,e.push(i)}return e}computeWorldMatrix(e){return this._worldMatrix||(this._worldMatrix=Ie.Identity()),this._worldMatrix}dispose(e,t=!1){if(this._nodeDataStorage._isDisposed=!0,!e){const s=this.getDescendants(!0);for(const i of s)i.dispose(e,t)}this.parent?this.parent=null:this._removeFromSceneRootNodes(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onEnabledStateChangedObservable.clear(),this._nodeDataStorage._onEffectiveEnabledStateChangedObservable?.clear(),this.onClonedObservable.clear();for(const e of this._behaviors)e.detach();this._behaviors.length=0,this.metadata=null}static ParseAnimationRanges(e,t,s){if(t.ranges)for(let s=0;s<t.ranges.length;s++){const i=t.ranges[s];e.createAnimationRange(i.name,i.from,i.to)}}getHierarchyBoundingVectors(e=!0,t=null){let s,i;this.getScene().incrementRenderId(),this.computeWorldMatrix(!0);const r=this;if(r.getBoundingInfo&&r.subMeshes){const e=r.getBoundingInfo();s=e.boundingBox.minimumWorld.clone(),i=e.boundingBox.maximumWorld.clone()}else s=new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new xe(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(e){const e=this.getDescendants(!1);for(const r of e){const e=r;if(e.computeWorldMatrix(!0),t&&!t(e))continue;if(!e.getBoundingInfo||0===e.getTotalVertices())continue;const n=e.getBoundingInfo().boundingBox,a=n.minimumWorld,o=n.maximumWorld;xe.CheckExtends(a,s,i),xe.CheckExtends(o,s,i)}}return{min:s,max:i}}},(()=>{const c="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[L()],s=[L()],i=[L()],r=[L()],n=[L()],b(null,null,t,{kind:"field",name:"name",static:!1,private:!1,access:{has:e=>"name"in e,get:e=>e.name,set:(e,t)=>{e.name=t}},metadata:c},a,o),b(null,null,s,{kind:"field",name:"id",static:!1,private:!1,access:{has:e=>"id"in e,get:e=>e.id,set:(e,t)=>{e.id=t}},metadata:c},h,l),b(null,null,i,{kind:"field",name:"uniqueId",static:!1,private:!1,access:{has:e=>"uniqueId"in e,get:e=>e.uniqueId,set:(e,t)=>{e.uniqueId=t}},metadata:c},u,d),b(null,null,r,{kind:"field",name:"state",static:!1,private:!1,access:{has:e=>"state"in e,get:e=>e.state,set:(e,t)=>{e.state=t}},metadata:c},_,p),b(null,null,n,{kind:"field",name:"metadata",static:!1,private:!1,access:{has:e=>"metadata"in e,get:e=>e.metadata,set:(e,t)=>{e.metadata=t}},metadata:c},f,g),c&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:c})})(),e._AnimationRangeFactory=(e,t,s)=>{throw Le("AnimationRange")},e._NodeConstructors={},e})();function Je(){return"undefined"!=typeof window}function et(){return"undefined"!=typeof navigator}function tt(){return"undefined"!=typeof document}function st(e){let t="",s=e.firstChild;for(;s;)3===s.nodeType&&(t+=s.textContent),s=s.nextSibling;return t}const it=(e,t,s)=>e?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():s&&"object"==typeof e?{...e}:null:e.clone(t):null;class rt{static DeepCopy(e,t,s,i,r=!1){const n=function(e){const t=[];do{const s=Object.getOwnPropertyNames(e);for(const e of s)-1===t.indexOf(e)&&t.push(e)}while(e=Object.getPrototypeOf(e));return t}(e);for(const o of n){if("_"===o[0]&&(!i||-1===i.indexOf(o)))continue;if(o.endsWith("Observable"))continue;if(s&&-1!==s.indexOf(o))continue;const n=e[o],h=typeof n;if("function"!==h)try{if("object"===h)if(n instanceof Uint8Array)t[o]=Uint8Array.from(n);else if(n instanceof Array){if(t[o]=[],n.length>0)if("object"==typeof n[0])for(let e=0;e<n.length;e++){const s=it(n[e],t,r);-1===t[o].indexOf(s)&&t[o].push(s)}else t[o]=n.slice(0)}else t[o]=it(n,t,r);else t[o]=n}catch(e){a.Warn(e.message)}}}}class nt{static get Now(){return Je()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class at{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(at.CustomRequestHeaders).length>0||at.CustomRequestModifiers.length>0}static _CleanUrl(e){return e=(e=e.replace("file:http:","http:")).replace("file:https:","https:")}static _ShouldSkipRequestModifications(e){return at.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}static _CollectCustomizations(e,t={}){const s={...t};if(at._ShouldSkipRequestModifications(e))return{url:e,headers:s};for(const e in at.CustomRequestHeaders){const t=at.CustomRequestHeaders[e];t&&(s[e]=t)}const i={setRequestHeader:(e,t)=>{s[e]=t}};for(const t of at.CustomRequestModifiers){if(at._ShouldSkipRequestModifications(e))break;const s=t(i,e);"string"==typeof s&&(e=s)}return{url:e,headers:s}}static async FetchAsync(e,t={}){const s=t.method??"GET";if("undefined"!=typeof fetch){const{url:i,headers:r}=at._CollectCustomizations(at._CleanUrl(e),t.headers??{});return await fetch(i,{method:s,headers:r,body:t.body??void 0})}return await new Promise((i,r)=>{const n=new at;n.responseType="arraybuffer",n.addEventListener("readystatechange",()=>{if(4===n.readyState)if(n.status>=200&&n.status<300){const e="undefined"!=typeof Headers?new Headers:void 0,t=n.getResponseHeader("Content-Type");t&&e&&e.set("Content-Type",t),"undefined"!=typeof Response?i(new Response(n.response,{status:n.status,statusText:n.statusText,headers:e})):i({ok:!0,status:n.status,statusText:n.statusText,headers:{get:e=>n.getResponseHeader(e)},arrayBuffer:async()=>await Promise.resolve(n.response)})}else r(new Error(`HTTP ${n.status} loading '${n.requestURL}': ${n.statusText}`))}),n.open(s,e,t.headers),n.send(t.body??null)})}get requestURL(){return this._requestURL}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,s){this._xhr.addEventListener(e,t,s)}removeEventListener(e,t,s){this._xhr.removeEventListener(e,t,s)}abort(){this._xhr.abort()}send(e){this._xhr.send(e)}open(e,t,s){const{url:i,headers:r}=at._CollectCustomizations(t,s);this._requestURL=at._CleanUrl(i),this._xhr.open(e,this._requestURL,!0);for(const e in r)this._xhr.setRequestHeader(e,r[e])}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}at.CustomRequestHeaders={},at.CustomRequestModifiers=new Array,at.SkipRequestModificationForBabylonCDN=!0;class ot{}ot.FilesToLoad={};const ht=e=>{if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let s=0;s<e.byteLength;s++)t+=String.fromCharCode(e[s]);return t};const lt=e=>{const t=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);return"function"==typeof t.toBase64?t.toBase64():function(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let s,i,r,n,a,o,h,l="",c=0;for(;c<e.length;)s=e[c++],i=c<e.length?e[c++]:Number.NaN,r=c<e.length?e[c++]:Number.NaN,n=s>>2,a=(3&s)<<4|i>>4,o=(15&i)<<2|r>>6,h=63&r,isNaN(i)?o=h=64:isNaN(r)&&(h=64),l+=t.charAt(n)+t.charAt(a)+t.charAt(o)+t.charAt(h);return l}(t)},ct=e=>atob(e),ut=e=>"function"==typeof Uint8Array.fromBase64?Uint8Array.fromBase64(e).buffer:function(e){const t=ct(e),s=t.length,i=new Uint8Array(new ArrayBuffer(s));for(let e=0;e<s;e++)i[e]=t.charCodeAt(e);return i.buffer}(e);class dt{}dt.AUTOSAMPLERSUFFIX="Sampler",dt.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS",dt.ALPHA_DISABLE=0,dt.ALPHA_ADD=1,dt.ALPHA_COMBINE=2,dt.ALPHA_SUBTRACT=3,dt.ALPHA_MULTIPLY=4,dt.ALPHA_MAXIMIZED=5,dt.ALPHA_ONEONE=6,dt.ALPHA_PREMULTIPLIED=7,dt.ALPHA_PREMULTIPLIED_PORTERDUFF=8,dt.ALPHA_INTERPOLATE=9,dt.ALPHA_SCREENMODE=10,dt.ALPHA_ONEONE_ONEONE=11,dt.ALPHA_ALPHATOCOLOR=12,dt.ALPHA_REVERSEONEMINUS=13,dt.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,dt.ALPHA_ONEONE_ONEZERO=15,dt.ALPHA_EXCLUSION=16,dt.ALPHA_LAYER_ACCUMULATE=17,dt.ALPHA_MIN=18,dt.ALPHA_MAX=19,dt.ALPHA_DUAL_SRC0_ADD_SRC1xDST=20,dt.ALPHA_REPLACE_COLOR=21,dt.ALPHA_EQUATION_ADD=0,dt.ALPHA_EQUATION_SUBSTRACT=1,dt.ALPHA_EQUATION_REVERSE_SUBTRACT=2,dt.ALPHA_EQUATION_MAX=3,dt.ALPHA_EQUATION_MIN=4,dt.ALPHA_EQUATION_DARKEN=5,dt.DELAYLOADSTATE_NONE=0,dt.DELAYLOADSTATE_LOADED=1,dt.DELAYLOADSTATE_LOADING=2,dt.DELAYLOADSTATE_NOTLOADED=4,dt.NEVER=512,dt.ALWAYS=519,dt.LESS=513,dt.EQUAL=514,dt.LEQUAL=515,dt.GREATER=516,dt.GEQUAL=518,dt.NOTEQUAL=517,dt.KEEP=7680,dt.ZERO=0,dt.REPLACE=7681,dt.INCR=7682,dt.DECR=7683,dt.INVERT=5386,dt.INCR_WRAP=34055,dt.DECR_WRAP=34056,dt.TEXTURE_CLAMP_ADDRESSMODE=0,dt.TEXTURE_WRAP_ADDRESSMODE=1,dt.TEXTURE_MIRROR_ADDRESSMODE=2,dt.TEXTURE_REPETITION_NONE=0,dt.TEXTURE_REPETITION_NOISE_BLEND=1,dt.TEXTURE_REPETITION_HEX_TILING=2,dt.TEXTURE_REPETITION_TILE_RANDOMIZATION=3,dt.TEXTURE_REPETITION_VORONOI_BOMBING=4,dt.TEXTURE_CREATIONFLAG_STORAGE=1,dt.TEXTUREFORMAT_ALPHA=0,dt.TEXTUREFORMAT_LUMINANCE=1,dt.TEXTUREFORMAT_LUMINANCE_ALPHA=2,dt.TEXTUREFORMAT_RGB=4,dt.TEXTUREFORMAT_RGBA=5,dt.TEXTUREFORMAT_RED=6,dt.TEXTUREFORMAT_R=6,dt.TEXTUREFORMAT_R16_UNORM=33322,dt.TEXTUREFORMAT_RG16_UNORM=33324,dt.TEXTUREFORMAT_RGB16_UNORM=32852,dt.TEXTUREFORMAT_RGBA16_UNORM=32859,dt.TEXTUREFORMAT_R16_SNORM=36760,dt.TEXTUREFORMAT_RG16_SNORM=36761,dt.TEXTUREFORMAT_RGB16_SNORM=36762,dt.TEXTUREFORMAT_RGBA16_SNORM=36763,dt.TEXTUREFORMAT_RG=7,dt.TEXTUREFORMAT_RED_INTEGER=8,dt.TEXTUREFORMAT_R_INTEGER=8,dt.TEXTUREFORMAT_RG_INTEGER=9,dt.TEXTUREFORMAT_RGB_INTEGER=10,dt.TEXTUREFORMAT_RGBA_INTEGER=11,dt.TEXTUREFORMAT_BGRA=12,dt.TEXTUREFORMAT_DEPTH24_STENCIL8=13,dt.TEXTUREFORMAT_DEPTH32_FLOAT=14,dt.TEXTUREFORMAT_DEPTH16=15,dt.TEXTUREFORMAT_DEPTH24=16,dt.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,dt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,dt.TEXTUREFORMAT_STENCIL8=19,dt.TEXTUREFORMAT_UNDEFINED=4294967295,dt.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,dt.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,dt.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,dt.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,dt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,dt.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,dt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,dt.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,dt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,dt.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,dt.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,dt.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_5x4=37809,dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_5x5=37810,dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_6x5=37811,dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_6x6=37812,dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x5=37813,dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x6=37814,dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x8=37815,dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x5=37816,dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x6=37817,dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x8=37818,dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x10=37819,dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_12x10=37820,dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_12x12=37821,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR=37841,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR=37842,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR=37843,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR=37844,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR=37845,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR=37846,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR=37847,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR=37848,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR=37849,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR=37850,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR=37851,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR=37852,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR=37853,dt.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,dt.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,dt.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,dt.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,dt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,dt.TEXTURETYPE_UNSIGNED_BYTE=0,dt.TEXTURETYPE_UNSIGNED_INT=0,dt.TEXTURETYPE_FLOAT=1,dt.TEXTURETYPE_HALF_FLOAT=2,dt.TEXTURETYPE_BYTE=3,dt.TEXTURETYPE_SHORT=4,dt.TEXTURETYPE_UNSIGNED_SHORT=5,dt.TEXTURETYPE_INT=6,dt.TEXTURETYPE_UNSIGNED_INTEGER=7,dt.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,dt.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,dt.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,dt.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,dt.TEXTURETYPE_UNSIGNED_INT_24_8=12,dt.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,dt.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,dt.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,dt.TEXTURETYPE_UNDEFINED=16,dt.TEXTURE_2D=3553,dt.TEXTURE_2D_ARRAY=35866,dt.TEXTURE_CUBE_MAP=34067,dt.TEXTURE_CUBE_MAP_ARRAY=3735928559,dt.TEXTURE_3D=32879,dt.TEXTURE_NEAREST_SAMPLINGMODE=1,dt.TEXTURE_NEAREST_NEAREST=1,dt.TEXTURE_BILINEAR_SAMPLINGMODE=2,dt.TEXTURE_LINEAR_LINEAR=2,dt.TEXTURE_TRILINEAR_SAMPLINGMODE=3,dt.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,dt.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,dt.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,dt.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,dt.TEXTURE_NEAREST_LINEAR=7,dt.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,dt.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,dt.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,dt.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,dt.TEXTURE_LINEAR_NEAREST=12,dt.TEXTURE_EXPLICIT_MODE=0,dt.TEXTURE_SPHERICAL_MODE=1,dt.TEXTURE_PLANAR_MODE=2,dt.TEXTURE_CUBIC_MODE=3,dt.TEXTURE_PROJECTION_MODE=4,dt.TEXTURE_SKYBOX_MODE=5,dt.TEXTURE_INVCUBIC_MODE=6,dt.TEXTURE_EQUIRECTANGULAR_MODE=7,dt.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,dt.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,dt.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,dt.TEXTURE_FILTERING_QUALITY_HIGH=64,dt.TEXTURE_FILTERING_QUALITY_MEDIUM=16,dt.TEXTURE_FILTERING_QUALITY_LOW=8,dt.SCALEMODE_FLOOR=1,dt.SCALEMODE_NEAREST=2,dt.SCALEMODE_CEILING=3,dt.MATERIAL_TextureDirtyFlag=1,dt.MATERIAL_LightDirtyFlag=2,dt.MATERIAL_FresnelDirtyFlag=4,dt.MATERIAL_AttributesDirtyFlag=8,dt.MATERIAL_MiscDirtyFlag=16,dt.MATERIAL_PrePassDirtyFlag=32,dt.MATERIAL_ImageProcessingDirtyFlag=64,dt.MATERIAL_AllDirtyFlag=127,dt.MATERIAL_TriangleFillMode=0,dt.MATERIAL_WireFrameFillMode=1,dt.MATERIAL_PointFillMode=2,dt.MATERIAL_PointListDrawMode=3,dt.MATERIAL_LineListDrawMode=4,dt.MATERIAL_LineLoopDrawMode=5,dt.MATERIAL_LineStripDrawMode=6,dt.MATERIAL_TriangleStripDrawMode=7,dt.MATERIAL_TriangleFanDrawMode=8,dt.MATERIAL_ClockWiseSideOrientation=0,dt.MATERIAL_CounterClockWiseSideOrientation=1,dt.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR=0,dt.MATERIAL_DIFFUSE_MODEL_BURLEY=1,dt.MATERIAL_DIFFUSE_MODEL_LAMBERT=2,dt.MATERIAL_DIFFUSE_MODEL_LEGACY=3,dt.MATERIAL_DIELECTRIC_SPECULAR_MODEL_GLTF=0,dt.MATERIAL_DIELECTRIC_SPECULAR_MODEL_OPENPBR=1,dt.MATERIAL_CONDUCTOR_SPECULAR_MODEL_GLTF=0,dt.MATERIAL_CONDUCTOR_SPECULAR_MODEL_OPENPBR=1,dt.ACTION_NothingTrigger=0,dt.ACTION_OnPickTrigger=1,dt.ACTION_OnLeftPickTrigger=2,dt.ACTION_OnRightPickTrigger=3,dt.ACTION_OnCenterPickTrigger=4,dt.ACTION_OnPickDownTrigger=5,dt.ACTION_OnDoublePickTrigger=6,dt.ACTION_OnPickUpTrigger=7,dt.ACTION_OnPickOutTrigger=16,dt.ACTION_OnLongPressTrigger=8,dt.ACTION_OnPointerOverTrigger=9,dt.ACTION_OnPointerOutTrigger=10,dt.ACTION_OnEveryFrameTrigger=11,dt.ACTION_OnIntersectionEnterTrigger=12,dt.ACTION_OnIntersectionExitTrigger=13,dt.ACTION_OnKeyDownTrigger=14,dt.ACTION_OnKeyUpTrigger=15,dt.PARTICLES_BILLBOARDMODE_Y=2,dt.PARTICLES_BILLBOARDMODE_ALL=7,dt.PARTICLES_BILLBOARDMODE_STRETCHED=8,dt.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,dt.MESHES_CULLINGSTRATEGY_STANDARD=0,dt.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,dt.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,dt.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,dt.SCENELOADER_NO_LOGGING=0,dt.SCENELOADER_MINIMAL_LOGGING=1,dt.SCENELOADER_SUMMARY_LOGGING=2,dt.SCENELOADER_DETAILED_LOGGING=3,dt.PREPASS_IRRADIANCE_LEGACY_TEXTURE_TYPE=0,dt.PREPASS_POSITION_TEXTURE_TYPE=1,dt.PREPASS_VELOCITY_TEXTURE_TYPE=2,dt.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,dt.PREPASS_COLOR_TEXTURE_TYPE=4,dt.PREPASS_DEPTH_TEXTURE_TYPE=5,dt.PREPASS_NORMAL_TEXTURE_TYPE=6,dt.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,dt.PREPASS_WORLD_NORMAL_TEXTURE_TYPE=8,dt.PREPASS_LOCAL_POSITION_TEXTURE_TYPE=9,dt.PREPASS_SCREENSPACE_DEPTH_TEXTURE_TYPE=10,dt.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE=11,dt.PREPASS_ALBEDO_TEXTURE_TYPE=12,dt.PREPASS_NORMALIZED_VIEW_DEPTH_TEXTURE_TYPE=13,dt.PREPASS_IRRADIANCE_TEXTURE_TYPE=14,dt.BUFFER_CREATIONFLAG_READ=1,dt.BUFFER_CREATIONFLAG_WRITE=2,dt.BUFFER_CREATIONFLAG_READWRITE=3,dt.BUFFER_CREATIONFLAG_UNIFORM=4,dt.BUFFER_CREATIONFLAG_VERTEX=8,dt.BUFFER_CREATIONFLAG_INDEX=16,dt.BUFFER_CREATIONFLAG_STORAGE=32,dt.BUFFER_CREATIONFLAG_INDIRECT=64,dt.RENDERPASS_MAIN=0,dt.INPUT_ALT_KEY=18,dt.INPUT_CTRL_KEY=17,dt.INPUT_META_KEY1=91,dt.INPUT_META_KEY2=92,dt.INPUT_META_KEY3=93,dt.INPUT_SHIFT_KEY=16,dt.SNAPSHOTRENDERING_STANDARD=0,dt.SNAPSHOTRENDERING_FAST=1,dt.PERSPECTIVE_CAMERA=0,dt.ORTHOGRAPHIC_CAMERA=1,dt.FOVMODE_VERTICAL_FIXED=0,dt.FOVMODE_HORIZONTAL_FIXED=1,dt.RIG_MODE_NONE=0,dt.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,dt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,dt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,dt.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,dt.RIG_MODE_STEREOSCOPIC_INTERLACED=14,dt.RIG_MODE_VR=20,dt.RIG_MODE_CUSTOM=22,dt.MAX_SUPPORTED_UV_SETS=6,dt.GL_ALPHA_EQUATION_ADD=32774,dt.GL_ALPHA_EQUATION_MIN=32775,dt.GL_ALPHA_EQUATION_MAX=32776,dt.GL_ALPHA_EQUATION_SUBTRACT=32778,dt.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,dt.GL_ALPHA_FUNCTION_SRC=768,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,dt.GL_ALPHA_FUNCTION_SRC_ALPHA=770,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,dt.GL_ALPHA_FUNCTION_DST_ALPHA=772,dt.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,dt.GL_ALPHA_FUNCTION_DST_COLOR=774,dt.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,dt.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,dt.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,dt.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,dt.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,dt.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,dt.GL_ALPHA_FUNCTION_SRC1_COLOR=35065,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_COLOR=35066,dt.GL_ALPHA_FUNCTION_SRC1_ALPHA=34185,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_ALPHA=35067,dt.SnippetUrl="https://snippet.babylonjs.com",dt.FOGMODE_NONE=0,dt.FOGMODE_EXP=1,dt.FOGMODE_EXP2=2,dt.FOGMODE_LINEAR=3,dt.BYTE=5120,dt.UNSIGNED_BYTE=5121,dt.SHORT=5122,dt.UNSIGNED_SHORT=5123,dt.INT=5124,dt.UNSIGNED_INT=5125,dt.FLOAT=5126,dt.HALF_FLOAT=5131,dt.PositionKind="position",dt.NormalKind="normal",dt.TangentKind="tangent",dt.UVKind="uv",dt.UV2Kind="uv2",dt.UV3Kind="uv3",dt.UV4Kind="uv4",dt.UV5Kind="uv5",dt.UV6Kind="uv6",dt.ColorKind="color",dt.ColorInstanceKind="instanceColor",dt.MatricesIndicesKind="matricesIndices",dt.MatricesWeightsKind="matricesWeights",dt.MatricesIndicesExtraKind="matricesIndicesExtra",dt.MatricesWeightsExtraKind="matricesWeightsExtra",dt.ANIMATIONTYPE_FLOAT=0,dt.ANIMATIONTYPE_VECTOR3=1,dt.ANIMATIONTYPE_QUATERNION=2,dt.ANIMATIONTYPE_MATRIX=3,dt.ANIMATIONTYPE_COLOR3=4,dt.ANIMATIONTYPE_COLOR4=7,dt.ANIMATIONTYPE_VECTOR2=5,dt.ANIMATIONTYPE_SIZE=6,dt.ShadowMinZ=0,dt.ShadowMaxZ=1e4,dt.OUTLINELAYER_SAMPLING_TRIDIRECTIONAL=0,dt.OUTLINELAYER_SAMPLING_OCTADIRECTIONAL=1;const _t={};function pt(e,t,s=""){return s+(t?t+"\n":"")+e}function ft(e,t,s,i,r,n,a){const o=a||_t.loadFile;if(!o)throw Le("FileTools");return o(e,t,s,i,r,n)}function gt(e,t,s,i){if(e)return t?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,s?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(i?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return t&&(e+="#define IS_NDC_HALF_ZRANGE"),s&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),i&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}function mt(e,t,s=!1,i){switch(e){case dt.TEXTURETYPE_BYTE:{const e=new Int8Array(t);return i&&e.set(new Int8Array(i)),e}case dt.TEXTURETYPE_UNSIGNED_BYTE:{const e=new Uint8Array(t);return i&&e.set(new Uint8Array(i)),e}case dt.TEXTURETYPE_SHORT:{const e="number"!=typeof t?new Int16Array(t):new Int16Array(s?t/2:t);return i&&e.set(new Int16Array(i)),e}case dt.TEXTURETYPE_UNSIGNED_SHORT:case dt.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:case dt.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:case dt.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:case dt.TEXTURETYPE_HALF_FLOAT:{const e="number"!=typeof t?new Uint16Array(t):new Uint16Array(s?t/2:t);return i&&e.set(new Uint16Array(i)),e}case dt.TEXTURETYPE_INT:{const e="number"!=typeof t?new Int32Array(t):new Int32Array(s?t/4:t);return i&&e.set(new Int32Array(i)),e}case dt.TEXTURETYPE_UNSIGNED_INTEGER:case dt.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:case dt.TEXTURETYPE_UNSIGNED_INT_24_8:case dt.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:case dt.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:case dt.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:{const e="number"!=typeof t?new Uint32Array(t):new Uint32Array(s?t/4:t);return i&&e.set(new Uint32Array(i)),e}case dt.TEXTURETYPE_FLOAT:{const e="number"!=typeof t?new Float32Array(t):new Float32Array(s?t/4:t);return i&&e.set(new Float32Array(i)),e}}const r=new Uint8Array(t);return i&&r.set(new Uint8Array(i)),r}class Tt{constructor(){this.children=[]}isValid(e){return!0}process(e,t,s){let i="";if(this.line){let s=this.line;const r=t.processor;if(r){r.lineProcessor&&(s=r.lineProcessor(s,t.isFragment,t.processingContext));const i=t.processor?.attributeKeywordName??"attribute",n=t.isFragment&&t.processor?.varyingFragmentKeywordName?t.processor?.varyingFragmentKeywordName:!t.isFragment&&t.processor?.varyingVertexKeywordName?t.processor?.varyingVertexKeywordName:"varying";if(!t.isFragment&&r.attributeProcessor&&this.line.startsWith(i))s=r.attributeProcessor(this.line,e,t.processingContext);else if(r.varyingProcessor&&(r.varyingCheck?.(this.line,t.isFragment)||!r.varyingCheck&&this.line.startsWith(n)))s=r.varyingProcessor(this.line,t.isFragment,e,t.processingContext);else if(r.uniformProcessor&&r.uniformRegexp&&r.uniformRegexp.test(this.line))t.lookForClosingBracketForUniformBuffer||(s=r.uniformProcessor(this.line,t.isFragment,e,t.processingContext));else if(r.uniformBufferProcessor&&r.uniformBufferRegexp&&r.uniformBufferRegexp.test(this.line))t.lookForClosingBracketForUniformBuffer||(s=r.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0);else if(r.textureProcessor&&r.textureRegexp&&r.textureRegexp.test(this.line))s=r.textureProcessor(this.line,t.isFragment,e,t.processingContext);else if((r.uniformProcessor||r.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer){/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?r.uniformProcessor&&(s=r.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):r.uniformBufferProcessor&&(s=r.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)}t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,r.endOfUniformBufferProcessor&&(s=r.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}i+=s+"\n"}for(const r of this.children)i+=r.process(e,t,s);return this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true",s[this.additionalDefineKey]=e[this.additionalDefineKey]),i}}class Et{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex<this._lines.length-1}set lines(e){this._lines.length=0;for(const t of e){if(!t||"\r"===t)continue;if("#"===t[0]){this._lines.push(t);continue}const e=t.trim();if(!e)continue;if(e.startsWith("//")){this._lines.push(t);continue}const s=e.indexOf(";");if(-1===s)this._lines.push(e);else if(s===e.length-1)e.length>1&&this._lines.push(e);else{const e=t.split(";");for(let t=0;t<e.length;t++){let s=e[t];s&&(s=s.trim(),s&&this._lines.push(s+(t!==e.length-1?";":"")))}}}}}class Rt extends Tt{process(e,t,s){for(let i=0;i<this.children.length;i++){const r=this.children[i];if(r.isValid(e))return r.process(e,t,s)}return""}}class bt extends Tt{isValid(e){return this.testExpression.isTrue(e)}}class At{isTrue(e){return!0}static postfixToInfix(e){const t=[];for(const s of e)if(void 0===At._OperatorPriority[s])t.push(s);else{const e=t[t.length-1],i=t[t.length-2];t.length-=2,t.push(`(${i}${s}${e})`)}return t[t.length-1]}static infixToPostfix(e){const t=At._InfixToPostfixCache.get(e);if(t)return t.accessTime=Date.now(),t.result;if(!(e.includes("&&")||e.includes("||")||e.includes(")")||e.includes("(")))return[e];const s=[];let i=-1;const r=()=>{l=l.trim(),""!==l&&(s.push(l),l="")},n=e=>{i<At._Stack.length-1&&(At._Stack[++i]=e)},a=()=>At._Stack[i],o=()=>-1===i?"!!INVALID EXPRESSION!!":At._Stack[i--];let h=0,l="";for(;h<e.length;){const t=e.charAt(h),c=h<e.length-1?e.substring(h,2+h):"";if("("===t)l="",n(t);else if(")"===t){for(r();-1!==i&&"("!==a();)s.push(o());o()}else if(At._OperatorPriority[c]>1){for(r();-1!==i&&At._OperatorPriority[a()]>=At._OperatorPriority[c];)s.push(o());n(c),h++}else l+=t;h++}for(r();-1!==i;)"("===a()?o():s.push(o());return At._InfixToPostfixCache.size>=At.InfixToPostfixCacheLimitSize&&At.ClearCache(),At._InfixToPostfixCache.set(e,{result:s,accessTime:Date.now()}),s}static ClearCache(){const e=Array.from(At._InfixToPostfixCache.entries()).sort((e,t)=>e[1].accessTime-t[1].accessTime);for(let t=0;t<At.InfixToPostfixCacheCleanupSize;t++)At._InfixToPostfixCache.delete(e[t][0])}}At.InfixToPostfixCacheLimitSize=5e4,At.InfixToPostfixCacheCleanupSize=25e3,At._InfixToPostfixCache=new Map,At._OperatorPriority={")":0,"(":1,"||":2,"&&":3},At._Stack=["","","","","","","","","","","","","","","","","","","",""];class yt extends At{constructor(e,t=!1){super(),this.define=e,this.not=t}isTrue(e){let t=void 0!==e[this.define];return this.not&&(t=!t),t}}class Mt extends At{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}}class xt extends At{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}}class St extends At{constructor(e,t,s){super(),this.define=e,this.operand=t,this.testValue=s}toString(){return`${this.define} ${this.operand} ${this.testValue}`}isTrue(e){let t=!1;const s=parseInt(null!=e[this.define]?e[this.define]:this.define),i=parseInt(null!=e[this.testValue]?e[this.testValue]:this.testValue);if(isNaN(s)||isNaN(i))return!1;switch(this.operand){case">":t=s>i;break;case"<":t=s<i;break;case"<=":t=s<=i;break;case">=":t=s>=i;break;case"==":t=s===i;break;case"!=":t=s!==i}return t}}const vt=/defined\s*?\((.+?)\)/g,It=/defined\s*?\[(.+?)\]/g,Pt=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,Ct=/__decl__/,Ot=/light\{X\}.(\w*)/g,Dt=/\{X\}/g,wt=[],Lt=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function Ft(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}function Nt(e,t,s,i){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),Ht(e,t,e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e,t.defines));const r=function(e,t,s){let i=function(e,t){if(t.processor?.noPrecision)return e;const s=t.shouldUseHighPrecisionShader;-1===e.indexOf("precision highp float")?e=s?"precision highp float;\n"+e:"precision mediump float;\n"+e:s||(e=e.replace("precision highp float","precision mediump float"));return e}(e,t);if(!t.processor)return i;if(0===t.processor.shaderLanguage&&-1!==i.indexOf("#version 3")&&(i=i.replace("#version 300 es",""),!t.processor.parseGLES3))return i;const r=t.defines,n=function(e,t){const s=e.defines,i={};for(const e of s){const t=e.replace("#define","").replace(";","").trim().split(" ");i[t[0]]=t.length>1?t[1]:""}0===e.processor?.shaderLanguage&&(i.GL_ES="true");return i.__VERSION__=e.version,i[e.platformName]="true",gt(i,t?.isNDCHalfZRange,t?.useReverseDepthBuffer,t?.useExactSrgbConversions),i}(t,s);t.processor.preProcessor&&(i=t.processor.preProcessor(i,r,n,t.isFragment,t.processingContext));const a={};i=function(e,t,s,i){const r=new Tt,n=new Et;return n.lineIndex=-1,n.lines=e.split("\n"),Vt(n,r),r.process(t,s,i)}(i,n,t,a),t.processor.postProcessor&&(i=t.processor.postProcessor(i,r,t.isFragment,t.processingContext,s?{drawBuffersExtensionDisabled:!s.getCaps().drawBuffersExtension}:{},n,a));s?._features.needShaderCodeInlining&&(i=s.inlineShaderCode(i));return i}(e,t,i);s(r,e)})}function Bt(e,t,s){return s.processor&&s.processor.finalizeShaders?s.processor.finalizeShaders(e,t,s.processingContext):{vertexCode:e,fragmentCode:t}}function Ut(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new yt(t[1].trim(),"!"===e[0]);const s=["==","!=",">=","<=","<",">"];let i="",r=0;for(i of s)if(r=e.indexOf(i),r>-1)break;if(-1===r)return new yt(e);const n=e.substring(0,r).trim(),a=e.substring(r+i.length).trim();return new St(n,i,a)}function kt(e,t){const s=new bt,i=e.substring(0,t);let r=e.substring(t);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),s.testExpression="#ifdef"===i?new yt(r):"#ifndef"===i?new yt(r,!0):function(e){e=e.replace(vt,"defined[$1]");const t=At.infixToPostfix(e),s=[];for(const e of t)if("||"!==e&&"&&"!==e)s.push(e);else if(s.length>=2){let t=s[s.length-1],i=s[s.length-2];s.length-=2;const r="&&"==e?new xt:new Mt;"string"==typeof t&&(t=t.replace(It,"defined($1)")),"string"==typeof i&&(i=i.replace(It,"defined($1)")),r.leftOperand="string"==typeof i?Ut(i):i,r.rightOperand="string"==typeof t?Ut(t):t,s.push(r)}let i=s[s.length-1];return"string"==typeof i&&(i=i.replace(It,"defined($1)")),"string"==typeof i?Ut(i):i}(r),s}function Gt(e,t,s,i){let r;for(;Vt(e,s);){r=e.currentLine;const i=r.substring(0,5).toLowerCase();if("#else"===i){const s=new Tt;return t.children.push(s),void Vt(e,s)}if("#elif"===i){const e=kt(r,5);t.children.push(e),s=e}}}function Vt(e,t,s){for(;e.canRead;){e.lineIndex++;const s=e.currentLine;if(s.indexOf("#")>=0){const i=Lt.exec(s);if(i&&i.length){switch(i[0]){case"#ifdef":{const i=new Rt;t.children.push(i);const r=kt(s,6);i.children.push(r),Gt(e,i,r);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const i=new Rt;t.children.push(i);const r=kt(s,7);i.children.push(r),Gt(e,i,r);break}case"#if":{const i=new Rt,r=kt(s,3);t.children.push(i),i.children.push(r),Gt(e,i,r);break}}continue}}const i=new Tt;if(i.line=s,t.children.push(i),"#"===s[0]&&"d"===s[1]){const e=s.replace(";","").split(" ");i.additionalDefineKey=e[1],3===e.length&&(i.additionalDefineValue=e[2])}}return!1}function Ht(e,t,s){let i;for(wt.length=0;null!==(i=Pt.exec(e));)wt.push(i);let r=[e],n=!1;for(const e of wt){let i=e[1];if(-1!==i.indexOf("__decl__")&&(i=i.replace(Ct,""),t.supportsUniformBuffers&&(i=i.replace("Vertex","Ubo").replace("Fragment","Ubo")),i+="Declaration"),!t.includesShadersStore[i]){const e=t.shadersRepository+"ShadersInclude/"+i+".fx";return void zt.loadFile(e,e=>{t.includesShadersStore[i]=e,Ht(r.join(""),t,s)})}{let s=t.includesShadersStore[i];if(e[2]){const t=e[3].split(",");for(let e=0;e<t.length;e+=2){const i=new RegExp(t[e],"g"),r=t[e+1];s=s.replace(i,r)}}if(e[4]){const i=e[5];if(-1!==i.indexOf("..")){const e=i.split(".."),r=parseInt(e[0]);let n=parseInt(e[1]),a=s.slice(0);s="",isNaN(n)&&(n=t.indexParameters[e[1]]);for(let e=r;e<n;e++)t.supportsUniformBuffers||(a=a.replace(Ot,(e,t)=>t+"{X}")),s+=a.replace(Dt,e.toString())+"\n"}else t.supportsUniformBuffers||(s=s.replace(Ot,(e,t)=>t+"{X}")),s=s.replace(Dt,i)}const a=[];for(const t of r){const i=t.split(e[0]);for(let e=0;e<i.length-1;e++)a.push(i[e]),a.push(s);a.push(i[i.length-1])}r=a,n=n||s.indexOf("#include<")>=0||s.indexOf("#include <")>=0}}wt.length=0;const a=r.join("");n?Ht(a.toString(),t,s):s(a)}const zt={loadFile:(e,t,s,i,r,n)=>{throw Le("FileTools")}};let Wt=[];class Xt{static SetImmediate(e){0===Wt.length&&setTimeout(()=>{const e=Wt;Wt=[];for(const t of e)t()},1),Wt.push(e)}}function Kt(e,t,s){try{if(e())return t(),!0}catch(e){return s?.(e),!0}return!1}const Yt=(e,t,s,i=16,r=3e4,n=!0,a)=>{if(n&&Kt(e,t,s))return null;const o=setInterval(()=>{Kt(e,t,s)?clearInterval(o):(r-=i)<0&&(clearInterval(o),s?.(new Error("Operation timed out after maximum retries. "+(a||"")),!0))},i);return()=>clearInterval(o)};let jt=null;function qt(){if(jt)return jt;const e=new ArrayBuffer(4),t=new Float32Array(e),s=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-24?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[256|e]=64512,r[e]=13,r[256|e]=13)}const n=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,s=0;for(;!(8388608&t);)t<<=1,s-=8388608;t&=-8388609,s+=947912704,n[e]=t|s}for(let e=1024;e<2048;++e)n[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)a[e]=e<<23;a[31]=1199570944,a[32]=2147483648;for(let e=33;e<63;++e)a[e]=2147483648+(e-32<<23);a[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return jt={floatView:t,uint32View:s,baseTable:i,shiftTable:r,mantissaTable:n,exponentTable:a,offsetTable:o},jt}const $t=65504;function Zt(e){const t=qt();t.floatView[0]=e;const s=t.uint32View[0],i=s>>23&511;return t.baseTable[i]+((8388607&s)>>t.shiftTable[i])}function Qt(e){const t=qt();return t.uint32View[0]=t.mantissaTable[t.offsetTable[e>>10]+(1023&e)]+t.exponentTable[e>>10],t.floatView[0]}function Jt(e,t,s,i){switch(t){case dt.BYTE:{let t=e.getInt8(s);return i&&(t=Math.max(t/127,-1)),t}case dt.UNSIGNED_BYTE:{let t=e.getUint8(s);return i&&(t/=255),t}case dt.SHORT:{let t=e.getInt16(s,!0);return i&&(t=Math.max(t/32767,-1)),t}case dt.UNSIGNED_SHORT:{let t=e.getUint16(s,!0);return i&&(t/=65535),t}case dt.HALF_FLOAT:return Qt(e.getUint16(s,!0));case dt.INT:return e.getInt32(s,!0);case dt.UNSIGNED_INT:return e.getUint32(s,!0);case dt.FLOAT:return e.getFloat32(s,!0);default:throw new Error(`Invalid component type ${t}`)}}function es(e,t,s,i,r){switch(t){case dt.BYTE:i&&(r=Math.round(127*r)),e.setInt8(s,r);break;case dt.UNSIGNED_BYTE:i&&(r=Math.round(255*r)),e.setUint8(s,r);break;case dt.SHORT:i&&(r=Math.round(32767*r)),e.setInt16(s,r,!0);break;case dt.UNSIGNED_SHORT:i&&(r=Math.round(65535*r)),e.setUint16(s,r,!0);break;case dt.HALF_FLOAT:e.setUint16(s,Zt(r),!0);break;case dt.INT:e.setInt32(s,r,!0);break;case dt.UNSIGNED_INT:e.setUint32(s,r,!0);break;case dt.FLOAT:e.setFloat32(s,r,!0);break;default:throw new Error(`Invalid component type ${t}`)}}function ts(e){switch(e){case dt.BYTE:case dt.UNSIGNED_BYTE:return 1;case dt.SHORT:case dt.UNSIGNED_SHORT:case dt.HALF_FLOAT:return 2;case dt.INT:case dt.UNSIGNED_INT:case dt.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}function ss(e){switch(e){case dt.BYTE:return Int8Array;case dt.UNSIGNED_BYTE:return Uint8Array;case dt.SHORT:return Int16Array;case dt.UNSIGNED_SHORT:case dt.HALF_FLOAT:return Uint16Array;case dt.INT:return Int32Array;case dt.UNSIGNED_INT:return Uint32Array;case dt.FLOAT:return Float32Array;default:throw new Error(`Invalid component type '${e}'`)}}function is(e,t,s,i,r,n,a,o){const h=new Array(i),l=new Array(i);if(e instanceof Array){let r=t/4;const a=s/4;for(let t=0;t<n;t+=i){for(let t=0;t<i;t++)h[t]=l[t]=e[r+t];o(l,t);for(let t=0;t<i;t++)h[t]!==l[t]&&(e[r+t]=l[t]);r+=a}}else{const c=ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),u=ts(r);for(let e=0;e<n;e+=i){for(let e=0,s=t;e<i;e++,s+=u)h[e]=l[e]=Jt(c,r,s,a);o(l,e);for(let e=0,s=t;e<i;e++,s+=u)h[e]!==l[e]&&es(c,r,s,a,l[e]);t+=s}}}function rs(e,t,s,i,r,n,o,h){const l=t*ts(s),c=o*t;if(s!==dt.FLOAT||r!==l){const a=new Float32Array(c);return is(e,i,r,t,s,c,n,(e,s)=>{for(let i=0;i<t;i++)a[s+i]=e[i]}),a}if(!(e instanceof Array||e instanceof Float32Array)||0!==i||e.length!==c){if(e instanceof Array){const t=i/4;return e.slice(t,t+c)}if(ArrayBuffer.isView(e)){const t=e.byteOffset+i;return 3&t&&(a.Warn("Float array must be aligned to 4-bytes border"),h=!0),h?new Float32Array(e.buffer.slice(t,t+c*Float32Array.BYTES_PER_ELEMENT)):new Float32Array(e.buffer,t,c)}return new Float32Array(e,i,c)}return h?e.slice():e}function ns(e,t,s,i,r,n,o){const h=ts(s),l=ss(s),c=n*t;if(Array.isArray(e)){if(3&i||3&r)throw new Error("byteOffset and byteStride must be a multiple of 4 for number[] data.");const a=i/4,o=r/4;if(a+(n-1)*o+t>e.length)throw new Error("Last accessed index is out of bounds.");if(o<t)throw new Error("Data stride cannot be smaller than the component size.");if(o!==t){const n=new l(c);return is(e,i,r,t,s,c,!1,(e,s)=>{for(let i=0;i<t;i++)n[s+i]=e[i]}),n}return new l(e.slice(a,a+c))}let u,d=i;ArrayBuffer.isView(e)?(u=e.buffer,d+=e.byteOffset):u=e;if(d+(n-1)*r+t*h>u.byteLength)throw new Error("Last accessed byte is out of bounds.");const _=t*h;if(r<_)throw new Error("Byte stride cannot be smaller than the component's byte size.");if(r!==_){const e=new l(c),s=new Uint8Array(u,d),i=new Uint8Array(e.buffer),a=t*h;for(let e=0,t=0,o=0;e<n;e++,t+=r,o+=a)i.set(s.subarray(t,t+a),o);return e}return 1!==h&&d&h-1&&(a.Warn("Array must be aligned to border of element size. Data will be copied."),o=!0),o?new l(u.slice(d,d+c*h)):new l(u,d,c)}function as(e){const t=e.buffer;if(t instanceof ArrayBuffer)return e;const s=new ArrayBuffer(e.byteLength);return new Uint8Array(s).set(new Uint8Array(t,e.byteOffset,e.byteLength)),s}const os=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class hs extends s{constructor(s,i){super(s,t.LoadFileError),this.name="LoadFileError",e._setPrototypeOf(this,hs.prototype),i instanceof at?this.request=i:this.file=i}}class ls extends s{constructor(s,i){super(s,t.RequestFileError),this.request=i,this.name="RequestFileError",e._setPrototypeOf(this,ls.prototype)}}class cs extends s{constructor(s,i){super(s,t.ReadFileError),this.file=i,this.name="ReadFileError",e._setPrototypeOf(this,cs.prototype)}}const us={DefaultRetryStrategy:class{static ExponentialBackoff(e=3,t=500){return(s,i,r)=>0!==i.status||r>=e||-1!==s.indexOf("file:")?-1:Math.pow(2,r)*t}}.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e,CleanUrl:e=>e=e.replace(/#/gm,"%23")},ds=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&us.CorsBehavior)if("string"==typeof us.CorsBehavior||us.CorsBehavior instanceof String)t.crossOrigin=us.CorsBehavior;else{const s=us.CorsBehavior(e);s&&(t.crossOrigin=s)}},_s=(e,t,s,i,r="",n,a=ee.LastCreatedEngine)=>{if("undefined"==typeof HTMLImageElement&&!a?._features.forceBitmapOverHTMLImageElement)return s("LoadImage is only supported in web or BabylonNative environments."),null;let o,h=!1;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))if("undefined"!=typeof Blob&&"undefined"!=typeof URL){let t;t=e instanceof ArrayBuffer?e:as(e),o=URL.createObjectURL(new Blob([t],{type:r})),h=!0}else o=`data:${r};base64,`+lt(e);else e instanceof Blob?(o=URL.createObjectURL(e),h=!0):(o=us.CleanUrl(e),o=us.PreprocessUrl(o));const l=t=>{if(s){const i=o||e.toString();s(`Error while trying to load image: ${0===i.indexOf("http")||i.length<=128?i:i.slice(0,128)+"..."}`,t)}};if(a?._features.forceBitmapOverHTMLImageElement)return fs(o,i=>{a.createImageBitmap(new Blob([i],{type:r}),{premultiplyAlpha:"none",colorSpaceConversion:"none",...n}).then(e=>{t(e),h&&URL.revokeObjectURL(o)}).catch(t=>{s&&s("Error while trying to load image: "+e,t)})},void 0,i||void 0,!0,(e,t)=>{l(t)}),null;const c=new Image;ds(o,c);const u=[],d=()=>{for(const e of u)e.target.removeEventListener(e.name,e.handler);u.length=0};u.push({target:c,name:"load",handler:()=>{d(),t(c),h&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:c,name:"error",handler:e=>{d(),l(e),h&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==c.src||"report"===e.disposition)return;d();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);ee.UseFallbackTexture=!1,l(t),h&&c.src&&URL.revokeObjectURL(c.src),c.src=""}}),(()=>{for(const e of u)e.target.addEventListener(e.name,e.handler)})();const _="blob:"===o.substring(0,5),p="data:"===o.substring(0,5),f=()=>{_||p||!at.IsCustomRequestAvailable?c.src=o:fs(o,(e,t,s)=>{const i=new Blob([e],{type:!r&&s?s:r}),n=URL.createObjectURL(i);h=!0,c.src=n},void 0,i||void 0,!0,(e,t)=>{l(t)})},g=()=>{i&&i.loadImage(o,c)};if(!_&&!p&&i&&i.enableTexturesOffline)i.open(g,f);else{if(-1!==o.indexOf("file:")){const e=decodeURIComponent(o.substring(5).toLowerCase());if(ot.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(ot.FilesToLoad[e])}catch(s){t=URL.createObjectURL(ot.FilesToLoad[e])}c.src=t,h=!0}catch(e){c.src=""}return c}}f()}return c},ps=(e,t,s,i,r)=>{const n=new FileReader,a={onCompleteObservable:new c,abort:()=>n.abort()};return n.onloadend=()=>a.onCompleteObservable.notifyObservers(a),r&&(n.onerror=()=>{r(new cs(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},s&&(n.onprogress=s),i?n.readAsArrayBuffer(e):n.readAsText(e),a},fs=(e,t,s,i,r,n,o)=>{if(e.name)return ps(e,t,s,r,n?e=>{n(void 0,e)}:void 0);const h=e;if(-1!==h.indexOf("file:")){let e=decodeURIComponent(h.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const i=ot.FilesToLoad[e];if(i)return ps(i,t,s,r,n?e=>n(void 0,new hs(e.message,e.file)):void 0)}const{match:l,type:u}=Rs(h);if(l){const e={onCompleteObservable:new c,abort:()=>()=>{}};try{const e=r?bs(h):As(h);t(e,void 0,u)}catch(e){n?n(void 0,e):a.Error(e.message||"Failed to parse the Data URL")}return Xt.SetImmediate(()=>{e.onCompleteObservable.notifyObservers(e)}),e}return gs(h,(e,s)=>{t(e,s?.responseURL,s?.getResponseHeader("content-type"))},s,i,r,n?e=>{n(e.request,new hs(e.message,e.request))}:void 0,o)},gs=(e,t,s,i,r,n,o)=>{null!==i&&(i??=ee.LastCreatedScene?.offlineProvider),e=us.CleanUrl(e),e=us.PreprocessUrl(e);const h=us.BaseUrl+e;let l=!1;const u={onCompleteObservable:new c,abort:()=>l=!0},d=()=>{let e,i=new at,c=null;const d=()=>{i&&(s&&i.removeEventListener("progress",s),e&&i.removeEventListener("readystatechange",e),i.removeEventListener("loadend",_))};let _=()=>{d(),u.onCompleteObservable.notifyObservers(u),u.onCompleteObservable.clear(),s=void 0,e=null,_=null,n=void 0,o=void 0,t=void 0};u.abort=()=>{l=!0,_&&_(),i&&i.readyState!==(XMLHttpRequest.DONE||4)&&i.abort(),null!==c&&(clearTimeout(c),c=null),i=null};const p=e=>{const t=e.message||"Unknown error";n&&i?n(new ls(t,i)):a.Error(t)},f=a=>{if(i){if(i.open("GET",h),o)try{o(i)}catch(e){return void p(e)}r&&(i.responseType="arraybuffer"),s&&i.addEventListener("progress",s),_&&i.addEventListener("loadend",_),e=()=>{if(!l&&i&&i.readyState===(XMLHttpRequest.DONE||4)){if(e&&i.removeEventListener("readystatechange",e),i.status>=200&&i.status<300||0===i.status&&(!Je()||Ts())){const e=r?i.response:i.responseText;if(null!==e){try{t&&t(e,i)}catch(e){p(e)}return}}const s=us.DefaultRetryStrategy;if(s){const e=s(h,i,a);if(-1!==e)return d(),i=new at,void(c=setTimeout(()=>f(a+1),e))}const o=new ls("Error status: "+i.status+" "+i.statusText+" - Unable to load "+h,i);n&&n(o)}},i.addEventListener("readystatechange",e),i.send()}};f(0)};if(i&&i.enableSceneOffline&&!e.startsWith("blob:")){const a=e=>{e&&e.status>400?n&&n(e):d()},o=()=>{i&&i.loadFile(us.BaseUrl+e,e=>{!l&&t&&t(e),u.onCompleteObservable.notifyObservers(u)},s?e=>{!l&&s&&s(e)}:void 0,a,r)};i.open(o,a)}else d();return u},ms=e=>{const{match:t,type:s}=Rs(e);if(t)return s||void 0;const i=e.lastIndexOf(".");switch(e.substring(i+1).toLowerCase()){case"glb":return"model/gltf-binary";case"bin":return"application/octet-stream";case"gltf":return"model/gltf+json";case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"ktx":return"image/ktx";case"ktx2":return"image/ktx2";case"avif":return"image/avif";default:return}},Ts=()=>"undefined"!=typeof location&&"file:"===location.protocol,Es=e=>os.test(e),Rs=e=>{const t=os.exec(e);if(null===t||0===t.length)return{match:!1,type:""};return{match:!0,type:t[0].replace("data:","").replace(";base64,","")}};function bs(e){return ut(e.split(",")[1])}const As=e=>ct(e.split(",")[1]);let ys;let Ms=!1;function xs(){Ms||(Ms=!0,((e,t,s,i,r,n,a,o,h,l)=>{ys={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:s.DefaultRetryStrategy,BaseUrl:s.BaseUrl,CorsBehavior:s.CorsBehavior,PreprocessUrl:s.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:r,LoadFile:n,LoadImage:a,ReadFile:o,RequestFile:h,SetCorsBehavior:l},Object.defineProperty(ys,"DefaultRetryStrategy",{get:function(){return s.DefaultRetryStrategy},set:function(e){s.DefaultRetryStrategy=e}}),Object.defineProperty(ys,"BaseUrl",{get:function(){return s.BaseUrl},set:function(e){s.BaseUrl=e}}),Object.defineProperty(ys,"PreprocessUrl",{get:function(){return s.PreprocessUrl},set:function(e){s.PreprocessUrl=e}}),Object.defineProperty(ys,"CorsBehavior",{get:function(){return s.CorsBehavior},set:function(e){s.CorsBehavior=e}})})(bs,As,us,Es,Ts,fs,_s,ps,gs,ds),_t.loadFile=fs,_t.loadImage=_s,zt.loadFile=fs)}class Ss{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=Ae(e);if(t)return t;a.Warn(e+" not found, you may have missed an import.");const s=e.split(".");let i="undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:this;for(let e=0,t=s.length;e<t;e++)i=i[s[e]];return"function"!=typeof i?null:i}}function vs(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function Is(e){let t=1;do{t*=2}while(t<e);return t===e}function Ps(e,t,s){return e*(1-s)+t*s}function Cs(e){const t=Os(e),s=Ds(e);return t-e>e-s?s:t}function Os(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}function Ds(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}function ws(e,t,s=dt.SCALEMODE_NEAREST){let i;switch(s){case dt.SCALEMODE_FLOOR:i=Ds(e);break;case dt.SCALEMODE_NEAREST:i=Cs(e);break;case dt.SCALEMODE_CEILING:default:i=Os(e)}return Math.min(i,t)}var Ls;Ss.RegisteredExternalClasses={};class Fs{static get BaseUrl(){return us.BaseUrl}static set BaseUrl(e){us.BaseUrl=e}static get CleanUrl(){return us.CleanUrl}static set CleanUrl(e){us.CleanUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||-1!==e.indexOf("://")&&(-1!==e.indexOf(".")&&(-1!==e.indexOf("/")&&(!(e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://")<e.indexOf(".")||(0===e.indexOf("data:")||0===e.indexOf("blob:"))))))}static set ScriptBaseUrl(e){us.ScriptBaseUrl=e}static get ScriptBaseUrl(){return us.ScriptBaseUrl}static set CDNBaseUrl(e){Ls.ScriptBaseUrl=e,Ls.AssetBaseUrl=e}static set ScriptPreprocessUrl(e){us.ScriptPreprocessUrl=e}static get ScriptPreprocessUrl(){return us.ScriptPreprocessUrl}static get DefaultRetryStrategy(){return us.DefaultRetryStrategy}static set DefaultRetryStrategy(e){us.DefaultRetryStrategy=e}static get CorsBehavior(){return us.CorsBehavior}static set CorsBehavior(e){us.CorsBehavior=e}static get UseFallbackTexture(){return ee.UseFallbackTexture}static set UseFallbackTexture(e){ee.UseFallbackTexture=e}static get RegisteredExternalClasses(){return Ss.RegisteredExternalClasses}static set RegisteredExternalClasses(e){Ss.RegisteredExternalClasses=e}static get fallbackTexture(){return ee.FallbackTexture}static set fallbackTexture(e){ee.FallbackTexture=e}static FetchToRef(e,t,s,i,r,n){const a=4*((Math.abs(e)*s%s|0)+(Math.abs(t)*i%i|0)*s);n.r=r[a]/255,n.g=r[a+1]/255,n.b=r[a+2]/255,n.a=r[a+3]/255}static Mix(e,t,s){return 0}static Instantiate(e){return Ss.Instantiate(e)}static SetImmediate(e){Xt.SetImmediate(e)}static IsExponentOfTwo(e){return!0}static FloatRound(e){return Math.fround(e)}static GetFilename(e){const t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)}static GetFolderPath(e,t=!1){const s=e.lastIndexOf("/");return s<0?t?e:"":e.substring(0,s+1)}static ToDegrees(e){return 180*e/Math.PI}static ToRadians(e){return e*Math.PI/180}static SmoothAngleChange(e,t,s=.9){const i=this.ToRadians(e),r=this.ToRadians(t);return this.ToDegrees(Math.atan2((1-s)*Math.sin(r)+s*Math.sin(i),(1-s)*Math.cos(r)+s*Math.cos(i)))}static MakeArray(e,t){return!0===t||void 0!==e&&null!=e?Array.isArray(e)?e:[e]:null}static GetPointerPrefix(e){return Je()&&!window.PointerEvent?"mouse":"pointer"}static SetCorsBehavior(e,t){ds(e,t)}static SetReferrerPolicyBehavior(e,t){t.referrerPolicy=e}static get PreprocessUrl(){return us.PreprocessUrl}static set PreprocessUrl(e){us.PreprocessUrl=e}static LoadImage(e,t,s,i,r,n){return _s(e,t,s,i,r,n)}static LoadFile(e,t,s,i,r,n){return fs(e,t,s,i,r,n)}static async LoadFileAsync(e,t=!0){return await new Promise((s,i)=>{fs(e,e=>{s(e)},void 0,void 0,t,(e,t)=>{i(t)})})}static GetAssetUrl(e){if(!e)return"";if(Ls.AssetBaseUrl&&e.startsWith(Ls._DefaultAssetsUrl)){const t=Ls.AssetBaseUrl.endsWith("/")?Ls.AssetBaseUrl.slice(0,-1):Ls.AssetBaseUrl;return e.replace(Ls._DefaultAssetsUrl,t)}return e}static GetBabylonScriptURL(e,t){if(!e)return"";if(e.startsWith(Ls._DefaultCdnUrl))if(Ls.ScriptBaseUrl){const t=Ls.ScriptBaseUrl.endsWith("/")?Ls.ScriptBaseUrl.slice(0,-1):Ls.ScriptBaseUrl;e=e.replace(Ls._DefaultCdnUrl,t)}else if(Ls._CdnVersion){const t=`${Ls._DefaultCdnUrl}/v${Ls._CdnVersion}`;e.startsWith(t)||(e=e.replace(Ls._DefaultCdnUrl,t))}return e=Ls.ScriptPreprocessUrl(e),t&&!Ls.IsAbsoluteUrl(e)&&(e=Ls.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,s,i){e=Ls.GetBabylonScriptURL(e),Ls.LoadScript(e,t,s)}static async LoadBabylonScriptAsync(e){return e=Ls.GetBabylonScriptURL(e),await Ls.LoadScriptAsync(e)}static _LoadScriptNative(e,t,s,i,r=!1){if(_native){if(r){const e="Loading a script as an ES module is not supported in Babylon Native";return void s?.(e,new Error(e))}Ls.LoadFile(e,e=>{try{Function(e).apply(null),t&&t()}catch(e){s&&s("LoadScript Error",e)}},void 0,void 0,!1,(e,t)=>{s&&s("LoadScript Error",t)})}}static _LoadScriptWeb(e,t,s,i,r=!1){if("function"==typeof importScripts){try{importScripts(e),t&&t()}catch(t){s?.(`Unable to load script '${e}' in worker`,t)}return}if(!Je())return void s?.(`Cannot load script '${e}' outside of a window or a worker`);const n=document.getElementsByTagName("head")[0],a=document.createElement("script");r?(a.setAttribute("type","module"),a.innerText=e):(a.setAttribute("type","text/javascript"),a.setAttribute("src",e)),i&&(a.id=i),a.onload=()=>{t&&t()},a.onerror=t=>{s&&s(`Unable to load script '${e}'`,t)},n.appendChild(a)}static async LoadScriptAsync(e,t){return await new Promise((s,i)=>{this.LoadScript(e,()=>{s()},(e,t)=>{i(t||new Error(e))},t)})}static ReadFileAsDataURL(e,t,s){const i=new FileReader,r={onCompleteObservable:new c,abort:()=>i.abort()};return i.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},i.onload=e=>{t(e.target.result)},i.onprogress=s,i.readAsDataURL(e),r}static ReadFile(e,t,s,i,r){return ps(e,t,s,i,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,s,i){rt.DeepCopy(e,t,s,i)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let s=0;s<t.length;s++){const i=t[s];e.addEventListener(i.name,i.handler,!1);try{window.parent&&window.parent.addEventListener(i.name,i.handler,!1)}catch(e){}}}static UnregisterTopRootEvents(e,t){for(let s=0;s<t.length;s++){const i=t[s];e.removeEventListener(i.name,i.handler);try{e.parent&&e.parent.removeEventListener(i.name,i.handler)}catch(e){}}}static async DumpFramebuffer(e,t,s,i,r="image/png",n,a){throw Le("DumpTools")}static DumpData(e,t,s,i,r="image/png",n,a=!1,o=!1,h){throw Le("DumpTools")}static async DumpDataAsync(e,t,s,i="image/png",r,n=!1,a=!1,o){throw Le("DumpTools")}static _IsOffScreenCanvas(e){return void 0!==e.convertToBlob}static ToBlob(e,t,s="image/png",i){Ls._IsOffScreenCanvas(e)||e.toBlob||(e.toBlob=function(e,t,s){setTimeout(()=>{const i=atob(this.toDataURL(t,s).split(",")[1]),r=i.length,n=new Uint8Array(r);for(let e=0;e<r;e++)n[e]=i.charCodeAt(e);e(new Blob([n]))})}),Ls._IsOffScreenCanvas(e)?e.convertToBlob({type:s,quality:i}).then(e=>t(e)):e.toBlob(function(e){t(e)},s,i)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const e=new Date;t="screenshot_"+((e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2))+".png"}Ls.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),s=window.open("");if(!s)return;const i=s.document.createElement("img");i.onload=function(){URL.revokeObjectURL(t)},i.src=t,s.document.body.appendChild(i)}}static EncodeScreenshotCanvasData(e,t,s="image/png",i,r){if("string"!=typeof i&&t){if(t){if(Ls._IsOffScreenCanvas(e))return void e.convertToBlob({type:s,quality:r}).then(e=>{const s=new FileReader;s.readAsDataURL(e),s.onloadend=()=>{const e=s.result;t(e)}});const i=e.toDataURL(s,r);t(i)}}else this.ToBlob(e,function(e){e&&Ls.DownloadBlob(e,i),t&&t("")},s,r)}static Download(e,t){if("undefined"==typeof URL)return;const s=window.URL.createObjectURL(e),i=document.createElement("a");document.body.appendChild(i),i.style.display="none",i.href=s,i.download=t,i.addEventListener("click",()=>{i.parentElement&&i.parentElement.removeChild(i)}),i.click(),window.URL.revokeObjectURL(s)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,s,i,r="image/png",n=!1,a){throw Le("ScreenshotTools")}static async CreateScreenshotAsync(e,t,s,i="image/png",r){throw Le("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,s,i,r="image/png",n=1,a=!1,o,h=!1,l=!1,c=!0,u,d){throw Le("ScreenshotTools")}static async CreateScreenshotUsingRenderTargetAsync(e,t,s,i="image/png",r=1,n=!1,a,o=!1,h=!1,l=!0,c,u){throw Le("ScreenshotTools")}static RandomId(){return vs()}static IsBase64(e){return Es(e)}static DecodeBase64(e){return bs(e)}static get errorsCount(){return a.errorsCount}static Log(e){a.Log(e)}static Warn(e){a.Warn(e)}static Error(e){a.Error(e)}static get LogCache(){return a.LogCache}static ClearLogCache(){a.ClearLogCache()}static set LogLevels(e){a.LogLevels=e}static set PerformanceLogLevel(e){(e&Ls.PerformanceUserMarkLogLevel)!==Ls.PerformanceUserMarkLogLevel?(e&Ls.PerformanceConsoleLogLevel)!==Ls.PerformanceConsoleLogLevel?(Ls.StartPerformanceCounter=Ls._StartPerformanceCounterDisabled,Ls.EndPerformanceCounter=Ls._EndPerformanceCounterDisabled,_native?.disablePerformanceLogging?.()):_native?.enablePerformanceLogging?(_native.enablePerformanceLogging(2),Ls.StartPerformanceCounter=Ls._StartMarkNative,Ls.EndPerformanceCounter=Ls._EndMarkNative):(Ls.StartPerformanceCounter=Ls._StartPerformanceConsole,Ls.EndPerformanceCounter=Ls._EndPerformanceConsole):_native?.enablePerformanceLogging?(_native.enablePerformanceLogging(1),Ls.StartPerformanceCounter=Ls._StartMarkNative,Ls.EndPerformanceCounter=Ls._EndMarkNative):(Ls.StartPerformanceCounter=Ls._StartUserMark,Ls.EndPerformanceCounter=Ls._EndUserMark)}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Ls._Performance){if(!Je())return;Ls._Performance=window.performance}t&&Ls._Performance.mark&&Ls._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&Ls._Performance.mark&&(Ls._Performance.mark(e+"-End"),Ls._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Ls._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Ls._EndUserMark(e,t),console.timeEnd(e))}static _StartMarkNative(e,t=!0){if(t&&_native?.startPerformanceCounter)if(Ls._NativePerformanceCounterHandles.has(e))Ls.Warn(`Performance counter with name ${e} is already started.`);else{const t=_native.startPerformanceCounter(e);Ls._NativePerformanceCounterHandles.set(e,t)}}static _EndMarkNative(e,t=!0){if(t&&_native?.endPerformanceCounter){const t=Ls._NativePerformanceCounterHandles.get(e);t?(_native.endPerformanceCounter(t),Ls._NativePerformanceCounterHandles.delete(e)):Ls.Warn(`Performance counter with name ${e} was not started.`)}}static get Now(){return nt.Now}static GetClassName(e,t=!1){let s=null;if(!t&&e.getClassName)s=e.getClassName();else{if(e instanceof Object){s=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__}s||(s=typeof e)}return s}static First(e,t){for(const s of e)if(t(s))return s;return null}static getFullClassName(e,t=!1){let s=null,i=null;if(!t&&e.getClassName)s=e.getClassName();else{if(e instanceof Object){const r=t?e:Object.getPrototypeOf(e);s=r.constructor.__bjsclassName__,i=r.constructor.__bjsmoduleName__}s||(s=typeof e)}return s?(null!=i?i+".":"")+s:null}static async DelayAsync(e){await new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return!!et()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}Ls=Fs,Fs.AssetBaseUrl="",Fs.UseCustomRequestHeaders=!1,Fs.CustomRequestHeaders=at.CustomRequestHeaders,Fs.GetDOMTextContent=st,Fs._DefaultCdnUrl="https://cdn.babylonjs.com",Fs._CdnVersion="9.22.2",Fs._DefaultAssetsUrl="https://assets.babylonjs.com/core",Fs.LoadScript="undefined"==typeof _native?Ls._LoadScriptWeb:Ls._LoadScriptNative,Fs.GetAbsoluteUrl="object"==typeof document?e=>{const t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},Fs.NoneLogLevel=a.NoneLogLevel,Fs.MessageLogLevel=a.MessageLogLevel,Fs.WarningLogLevel=a.WarningLogLevel,Fs.ErrorLogLevel=a.ErrorLogLevel,Fs.AllLogLevel=a.AllLogLevel,Fs.IsWindowObjectExist=Je,Fs.PerformanceNoneLogLevel=0,Fs.PerformanceUserMarkLogLevel=1,Fs.PerformanceConsoleLogLevel=2,Fs._NativePerformanceCounterHandles=new Map,Fs.StartPerformanceCounter=Ls._StartPerformanceCounterDisabled,Fs.EndPerformanceCounter=Ls._EndPerformanceCounterDisabled;class Ns{constructor(e,t,s,i=0){this.iterations=e,this.index=i-1,this._done=!1,this._fn=t,this._successCallback=s}executeNext(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())}breakLoop(){this._done=!0,this._successCallback()}static Run(e,t,s,i=0){const r=new Ns(e,t,s,i);return r.executeNext(),r}static SyncAsyncForLoop(e,t,s,i,r,n=0){return Ns.Run(Math.ceil(e/t),i=>{r&&r()?i.breakLoop():setTimeout(()=>{for(let n=0;n<t;++n){const a=i.index*t+n;if(a>=e)break;if(s(a),r&&r()){i.breakLoop();break}}i.executeNext()},n)},i)}}let Bs=!1;function Us(){Bs||(Bs=!0,Fs.Mix=Ps,Fs.IsExponentOfTwo=Is,ee.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z")}function ks(e,t,s){try{const i=e.next();i.done?t(i):i.value?i.value.then(()=>{i.value=void 0,t(i)},s):t(i)}catch(e){s(e)}}function Gs(e=25){let t;return(s,i,r)=>{const n=performance.now();void 0===t||n-t>e?(t=n,setTimeout(()=>{ks(s,i,r)},0)):ks(s,i,r)}}function Vs(e,t,s,i,r){const n=()=>{let r;const a=e=>{e.done?s(e.value):void 0===r?r=!0:n()};do{r=void 0,t(e,a,i),void 0===r&&(r=!1)}while(r)};n()}function Hs(e,t){let s;return Vs(e,ks,e=>s=e,e=>{throw e}),s}async function zs(e,t,s){return await new Promise((s,i)=>{Vs(e,t,s,i)})}class Ws{constructor(e){this.length=0,this.data=new Array(e),this._id=Ws._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;t<this.length;t++)e(this.data[t])}sort(e){this.data.sort(e)}reset(){this.length=0}dispose(){this.reset(),this.data&&(this.data.length=0)}concat(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}}indexOf(e){const t=this.data.indexOf(e);return t>=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}Ws._GlobalId=0;class Xs extends Ws{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return(!e.__smartArrayFlags||e.__smartArrayFlags[this._id]!==this._duplicateId)&&(this.push(e),!0)}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t<e.length;t++){const s=(e.data||e)[t];this.pushNoDuplicate(s)}}}}class Ks{constructor(e,t,s,i){this.x=e,this.y=t,this.width=s,this.height=i}toGlobal(e,t){return new Ks(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,s){return s.x=this.x*e,s.y=this.y*t,s.width=this.width*e,s.height=this.height*t,this}clone(){return new Ks(this.x,this.y,this.width,this.height)}}class Ys{constructor(e,t,s,i){this.normal=new xe(e,t,s),this.d=i}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Ys(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^this.d,e}normalize(){const e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z);let t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=Ys._TmpMatrix;e.invertToRef(t);const s=t.m,i=this.normal.x,r=this.normal.y,n=this.normal.z,a=this.d,o=i*s[0]+r*s[1]+n*s[2]+a*s[3],h=i*s[4]+r*s[5]+n*s[6]+a*s[7],l=i*s[8]+r*s[9]+n*s[10]+a*s[11],c=i*s[12]+r*s[13]+n*s[14]+a*s[15];return new Ys(o,h,l,c)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,s){const i=t.x-e.x,r=t.y-e.y,n=t.z-e.z,a=s.x-e.x,o=s.y-e.y,h=s.z-e.z,l=r*h-n*o,c=n*a-i*h,u=i*o-r*a,d=Math.sqrt(l*l+c*c+u*u);let _;return _=0!==d?1/d:0,this.normal.x=l*_,this.normal.y=c*_,this.normal.z=u*_,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return xe.Dot(this.normal,e)<=t}signedDistanceTo(e){return xe.Dot(e,this.normal)+this.d}static FromArray(e){return new Ys(e[0],e[1],e[2],e[3])}static FromPoints(e,t,s){const i=new Ys(0,0,0,0);return i.copyFromPoints(e,t,s),i}static FromPositionAndNormal(e,t){const s=new Ys(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,s)}static FromPositionAndNormalToRef(e,t,s){return s.normal.copyFrom(t),s.normal.normalize(),s.d=-e.dot(s.normal),s}static SignedDistanceToPlaneFromPositionAndNormal(e,t,s){const i=-(t.x*e.x+t.y*e.y+t.z*e.z);return xe.Dot(s,t)+i}}Ys._TmpMatrix=Ie.Identity();class js{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new Ys(0,0,0,0));return js.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const s=e.m;t.normal.x=s[3]+s[2],t.normal.y=s[7]+s[6],t.normal.z=s[11]+s[10],t.d=s[15]+s[14],t.normalize()}static GetFarPlaneToRef(e,t){const s=e.m;t.normal.x=s[3]-s[2],t.normal.y=s[7]-s[6],t.normal.z=s[11]-s[10],t.d=s[15]-s[14],t.normalize()}static GetLeftPlaneToRef(e,t){const s=e.m;t.normal.x=s[3]+s[0],t.normal.y=s[7]+s[4],t.normal.z=s[11]+s[8],t.d=s[15]+s[12],t.normalize()}static GetRightPlaneToRef(e,t){const s=e.m;t.normal.x=s[3]-s[0],t.normal.y=s[7]-s[4],t.normal.z=s[11]-s[8],t.d=s[15]-s[12],t.normalize()}static GetTopPlaneToRef(e,t){const s=e.m;t.normal.x=s[3]-s[1],t.normal.y=s[7]-s[5],t.normal.z=s[11]-s[9],t.d=s[15]-s[13],t.normalize()}static GetBottomPlaneToRef(e,t){const s=e.m;t.normal.x=s[3]+s[1],t.normal.y=s[7]+s[5],t.normal.z=s[11]+s[9],t.d=s[15]+s[13],t.normalize()}static GetPlanesToRef(e,t){js.GetNearPlaneToRef(e,t[0]),js.GetFarPlaneToRef(e,t[1]),js.GetLeftPlaneToRef(e,t[2]),js.GetRightPlaneToRef(e,t[3]),js.GetTopPlaneToRef(e,t[4]),js.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let s=0;s<6;s++)if(t[s].dotCoordinate(e)<0)return!1;return!0}}class qs{static GetShadersRepository(e=0){return 0===e?qs.ShadersRepository:qs.ShadersRepositoryWGSL}static GetShadersStore(e=0){return 0===e?qs.ShadersStore:qs.ShadersStoreWGSL}static GetIncludesShadersStore(e=0){return 0===e?qs.IncludesShadersStore:qs.IncludesShadersStoreWGSL}}qs.ShadersRepository="src/Shaders/",qs.ShadersStore={},qs.IncludesShadersStore={},qs.ShadersRepositoryWGSL="src/ShadersWGSL/",qs.ShadersStoreWGSL={},qs.IncludesShadersStoreWGSL={};class $s{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,s,i,r,n,a,o){const h=this.engine;if(h.supportsUniformBuffers)for(const s in t)e.bindUniformBlock(s,t[s]);let l;for(this.engine.getUniforms(this,s).forEach((e,t)=>{i[s[t]]=e}),this._uniforms=i,l=0;l<r.length;l++){null==e.getUniform(r[l])&&(r.splice(l,1),l--)}r.forEach((e,t)=>{n[e]=t});for(const e of h.getAttributes(this,a))o.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const s=this._valueCache[e],i=t.updateFlag;return(void 0===s||s!==i)&&(this._valueCache[e]=i,!0)}_cacheFloat2(e,t,s){let i=this._valueCache[e];if(!i||2!==i.length)return i=[t,s],this._valueCache[e]=i,!0;let r=!1;return i[0]!==t&&(i[0]=t,r=!0),i[1]!==s&&(i[1]=s,r=!0),r}_cacheFloat3(e,t,s,i){let r=this._valueCache[e];if(!r||3!==r.length)return r=[t,s,i],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==s&&(r[1]=s,n=!0),r[2]!==i&&(r[2]=i,n=!0),n}_cacheFloat4(e,t,s,i,r){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,s,i,r],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==s&&(n[1]=s,a=!0),n[2]!==i&&(n[2]=i,a=!0),n[3]!==r&&(n[3]=r,a=!0),a}setInt(e,t){const s=this._valueCache[e];void 0!==s&&s===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,s){this._cacheFloat2(e,t,s)&&(this.engine.setInt2(this._uniforms[e],t,s)||(this._valueCache[e]=null))}setInt3(e,t,s,i){this._cacheFloat3(e,t,s,i)&&(this.engine.setInt3(this._uniforms[e],t,s,i)||(this._valueCache[e]=null))}setInt4(e,t,s,i,r){this._cacheFloat4(e,t,s,i,r)&&(this.engine.setInt4(this._uniforms[e],t,s,i,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const s=this._valueCache[e];void 0!==s&&s===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,s){this._cacheFloat2(e,t,s)&&(this.engine.setUInt2(this._uniforms[e],t,s)||(this._valueCache[e]=null))}setUInt3(e,t,s,i){this._cacheFloat3(e,t,s,i)&&(this.engine.setUInt3(this._uniforms[e],t,s,i)||(this._valueCache[e]=null))}setUInt4(e,t,s,i,r){this._cacheFloat4(e,t,s,i,r)&&(this.engine.setUInt4(this._uniforms[e],t,s,i,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const s=this._valueCache[e];void 0!==s&&s===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,s){this._cacheFloat2(e,t,s)&&(this.engine.setFloat2(this._uniforms[e],t,s)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,s,i){this._cacheFloat3(e,t,s,i)&&(this.engine.setFloat3(this._uniforms[e],t,s,i)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,s,i,r){this._cacheFloat4(e,t,s,i,r)&&(this.engine.setFloat4(this._uniforms[e],t,s,i,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,s){this._cacheFloat4(e,t.r,t.g,t.b,s)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,s)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}const Zs=new WeakMap,Qs={_webGLVersion:2,cachedPipelines:{}};function Js(e){let t=Zs.get(e);if(!t){if(!e)return Qs;t={_webGLVersion:e.TEXTURE_BINDING_3D?2:1,_context:e,parallelShaderCompile:e.getExtension("KHR_parallel_shader_compile")||void 0,cachedPipelines:{}},Zs.set(e,t)}return t}function ei(e){Zs.delete(e)}function ti(e,t,s,i,r,n){const a=Js(i);n||(n=a._createShaderProgramInjection??ii);return n(e,ai(t,"vertex",i,a._contextWasLost),ai(s,"fragment",i,a._contextWasLost),i,r,a.validateShaderPrograms)}function si(e,t,s,i,r,n=null,a){const o=Js(r);a||(a=o._createShaderProgramInjection??ii);const h=o._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"";return a(e,ni(t,"vertex",i,h,r,o._contextWasLost),ni(s,"fragment",i,h,r,o._contextWasLost),r,n,o.validateShaderPrograms)}function ii(e,t,s,i,r=null,n){const a=i.createProgram();if(e.program=a,!a)throw new Error("Unable to create program");return i.attachShader(a,t),i.attachShader(a,s),i.linkProgram(a),e.context=i,e.vertexShader=t,e.fragmentShader=s,e.isParallelCompiled||ri(e,i,n),a}function ri(e,t,s){const i=e.context,r=e.vertexShader,n=e.fragmentShader,a=e.program;if(!i.getProgramParameter(a,i.LINK_STATUS)){if(!t.getShaderParameter(r,t.COMPILE_STATUS)){const s=t.getShaderInfoLog(r);if(s)throw e.vertexCompilationError=s,new Error("VERTEX SHADER "+s)}if(!t.getShaderParameter(n,t.COMPILE_STATUS)){const s=t.getShaderInfoLog(n);if(s)throw e.fragmentCompilationError=s,new Error("FRAGMENT SHADER "+s)}const s=i.getProgramInfoLog(a);if(s)throw e.programLinkError=s,new Error(s)}if(s){i.validateProgram(a);if(!i.getProgramParameter(a,i.VALIDATE_STATUS)){const t=i.getProgramInfoLog(a);if(t)throw e.programValidationError=t,new Error(t)}}i.deleteShader(r),i.deleteShader(n),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}function ni(e,t,s,i,r,n){return ai(pt(e,s,i),t,r,n)}function ai(e,t,s,i){const r=s.createShader("vertex"===t?s.VERTEX_SHADER:s.FRAGMENT_SHADER);if(!r){let e,r=s.NO_ERROR;for(;(e=s.getError())!==s.NO_ERROR;)r=e;throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${r}, gl isContextLost=${s.isContextLost()}, _contextWasLost=${i}`)}return s.shaderSource(r,e),s.compileShader(r),r}function oi(e){const t=e._name,s=e.context;if(t&&s){const e=Js(s),i=e.cachedPipelines[t];i?.dispose(),delete e.cachedPipelines[t]}}function hi(e,t,s,i,r,n){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){return void i(st(e))}if("source:"===e.substring(0,7))return void i(e.substring(7));if("base64:"===e.substring(0,7)){return void i(window.atob(e.substring(7)))}const a=qs.GetShadersStore(r);if(a[e+t+"Shader"])return void i(a[e+t+"Shader"]);if(s&&a[e+s+"Shader"])return void i(a[e+s+"Shader"]);let o;if(o="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:qs.GetShadersRepository(r)+e,!(n=n||ft))throw new Error("loadFileInjection is not defined");n(o+"."+t.toLowerCase()+".fx",i)}class li{static get ShadersRepository(){return qs.ShadersRepository}static set ShadersRepository(e){qs.ShadersRepository=e}get isDisposed(){return this._isDisposed}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new c),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,s,i=null,r,n=null,a=null,o=null,h=null,l,u="",d=0,_){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new c,this.onErrorObservable=new c,this._onBindObservable=null,this._isDisposed=!1,this._refCount=1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._disableParallelShaderCompilation=!1,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this._onReleaseEffectsObserver=null,this.name=e,this._key=u;const p=this._key.replace(/\r/g,"").replace(/\n/g,"|");let f;if(t.attributes){const e=t;if(this._engine=s,this._attributesNames=e.attributes,this._uniformsNames=e.uniformsNames.concat(e.samplers),this._samplerList=e.samplers.slice(),this.defines=e.defines,this.onError=e.onError,this.onCompiled=e.onCompiled,this._fallbacks=e.fallbacks,this._indexParameters=e.indexParameters,this._transformFeedbackVaryings=e.transformFeedbackVaryings||null,this._multiTarget=!!e.multiTarget,this._shaderLanguage=e.shaderLanguage??0,this._disableParallelShaderCompilation=!!e.disableParallelShaderCompilation,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t<e.uniformBuffersNames.length;t++)this._uniformBuffersNames[e.uniformBuffersNames[t]]=t}this._processFinalCode=e.processFinalCode??null,this._processCodeAfterIncludes=e.processCodeAfterIncludes??void 0,_=e.extraInitializationsAsync,f=e.existingPipelineContext}else this._engine=r,this.defines=null==n?"":n,this._uniformsNames=s.concat(i),this._samplerList=i?i.slice():[],this._attributesNames=t,this._uniformBuffersNamesList=[],this._shaderLanguage=d,this.onError=h,this.onCompiled=o,this._indexParameters=l,this._fallbacks=a;var g;"WEBGL2"===this._engine.shaderPlatformName&&(g=p,f=Js(this._engine._gl).cachedPipelines[g]??f),this._attributeLocationByName={},this.uniqueId=li._UniqueIdSeed++,f?(this._pipelineContext=f,this._pipelineContext.setEngine(this._engine),this._onRenderingStateCompiled(this._pipelineContext),this._pipelineContext.program&&(this._pipelineContext.program.__SPECTOR_rebuildProgram=this._rebuildProgram.bind(this))):this._processShaderCodeAsync(null,!1,null,_).catch(e=>{const t=e?.message??String(e),s=new Error(`Effect async shader preparation failed for "${String(this.name)}": ${t}`);e&&"string"==typeof e.stack&&(s.stack=`${s.message}\nCaused by: ${e.stack}`),this._processCompilationErrors(s)}),this._onReleaseEffectsObserver=this._engine.onReleaseEffectsObservable.addOnce(()=>{this._onReleaseEffectsObserver=null,this.isDisposed||this.dispose(!0)})}async _processShaderCodeAsync(e=null,t=!1,s=null,i){i&&await i(),this._processingContext=s||this._engine._getShaderProcessingContext(this._shaderLanguage,!1);!function(e,t,s,i,r,n,a){let o,h;const l=Je()?n?.getHostDocument():null;o="string"==typeof t?t:"string"==typeof t.vertexSource?"source:"+t.vertexSource:"string"==typeof t.vertexElement?l?.getElementById(t.vertexElement)||t.vertexElement:t.vertex||t,h="string"==typeof t?t:"string"==typeof t.fragmentSource?"source:"+t.fragmentSource:"string"==typeof t.fragmentElement?l?.getElementById(t.fragmentElement)||t.fragmentElement:t.fragment||t;const c=[void 0,void 0],u=()=>{if(c[0]&&c[1]){const[o,h]=c;Ft(e),Nt(o,e,(o,l)=>{a&&(a._vertexSourceCodeBeforeMigration=l),s&&(o=s("vertex",o)),e.isFragment=!0,Nt(h,e,(n,h)=>{a&&(a._fragmentSourceCodeBeforeMigration=h),s&&(n=s("fragment",n));const l=Bt(o,n,e);e=null;const c=function(e,t,s,i){return s?{vertexSourceCode:(1===i?"//":"")+"#define SHADER_NAME vertex:"+(s.vertexElement||s.vertex||s.spectorName||s)+"\n"+e,fragmentSourceCode:(1===i?"//":"")+"#define SHADER_NAME fragment:"+(s.fragmentElement||s.fragment||s.spectorName||s)+"\n"+t}:{vertexSourceCode:e,fragmentSourceCode:t}}(l.vertexCode,l.fragmentCode,t,r);i?.(c.vertexSourceCode,c.fragmentSourceCode)},n)},n)}};hi(o,"Vertex","",e=>{a&&(a._rawVertexSourceCode=e),c[0]=e,u()},r),hi(h,"Fragment","Pixel",e=>{a&&(a._rawFragmentSourceCode=e),c[1]=e,u()},r)}({defines:this.defines.split("\n"),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:e??this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:qs.GetShadersRepository(this._shaderLanguage),includesShadersStore:qs.GetIncludesShadersStore(this._shaderLanguage),version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes},this.name,this._processFinalCode,(e,s)=>{this._vertexSourceCode=e,this._fragmentSourceCode=s,this._prepareEffect(t)},this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._engine.isDisposed||(!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady)}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}async whenCompiledAsync(){return await new Promise(e=>{this.executeWhenCompiled(e)})}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add(t=>{e(t)}),this._pipelineContext&&!this._pipelineContext.isAsync||this._checkIsReady(null))}_checkIsReady(e){Yt(()=>this._isReadyInternal()||this._isDisposed,()=>{},t=>{this._processCompilationErrors(t,e)},16,12e4,!0,` - Effect: ${"string"==typeof this.name?this.name:this.key}`)}get vertexSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._pipelineContext?._getVertexShaderCode()??this._vertexSourceCode}get fragmentSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._pipelineContext?._getFragmentShaderCode()??this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}getPipelineGenerationOptions(){return{platformName:this._engine.shaderPlatformName,shaderLanguage:this._shaderLanguage,shaderNameOrContent:this.name,key:this._key,defines:this.defines.split("\n"),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!(!this._vertexSourceCodeOverride||!this._fragmentSourceCodeOverride)}}}_rebuildProgram(e,t,s,i){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{i&&i(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;t<e.length;t++)e[t].markAllMaterialsAsDirty(dt.MATERIAL_AllDirtyFlag);this._pipelineContext._handlesSpectorRebuildCallback?.(s)},this._fallbacks=null,this._prepareEffect()}_onRenderingStateCompiled(e){if(this._pipelineContext=e,this._pipelineContext.setEngine(this._engine),this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,this._attributesNames,this._attributes),this._attributesNames)for(let e=0;e<this._attributesNames.length;e++){const t=this._attributesNames[e];this._attributeLocationByName[t]=this._attributes[e]}this._engine.bindSamplers(this),this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh(),li.AutomaticallyClearCodeCache&&this.clearCodeCache()}_prepareEffect(e=!1){const t=this._pipelineContext;this._isReady=!1;try{const s=!(!this._vertexSourceCodeOverride||!this._fragmentSourceCodeOverride),i=s?null:this.defines,r=s?this._vertexSourceCodeOverride:this._vertexSourceCode,n=s?this._fragmentSourceCodeOverride:this._fragmentSourceCode,o=this._engine;this._pipelineContext=((e,t,s,i)=>{try{const r=e.context?Js(e.context):null;r&&(r.disableParallelShaderCompile=e.disableParallelCompilation);const n=e.existingPipelineContext||t(e.shaderProcessingContext);return n._name=e.name,e.name&&r&&(r.cachedPipelines[e.name]=n),s(n,e.vertex,e.fragment,!!e.createAsRaw,"","",e.rebuildRebind,e.defines,e.transformFeedbackVaryings,"",()=>{i(n,()=>{e.onRenderingStateCompiled?.(n)})}),n}catch(e){throw a.Error("Error compiling effect"),e}})({existingPipelineContext:e?t:null,vertex:r,fragment:n,context:"WEBGL2"===o.shaderPlatformName||"WEBGL1"===o.shaderPlatformName?o._gl:void 0,rebuildRebind:(e,t,s,i)=>this._rebuildProgram(e,t,s,i),defines:i,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:s,disableParallelCompilation:this._disableParallelShaderCompilation,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:s=>{t&&!e&&this._engine._deletePipelineContext(t),s&&this._onRenderingStateCompiled(s)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContextAsync.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t,s){const i=s?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let r=null;if(t&&e){const n=t.match(i);if(n&&2===n.length){const t=parseInt(n[1]),i=e.split("\n",-1);i.length>=t&&(r=`Offending line [${t}] in ${s?"fragment":"vertex"} code: ${i[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){this._compilationError="string"==typeof e?.stack?e.stack:e?.message??String(e);const s=this._attributesNames,i=this._fallbacks;if(a.Error("Unable to compile effect:"),a.Error(`Uniforms: ${this._uniformsNames.join(" ")}`),a.Error(`Attributes: ${s.join(" ")}`),a.Error("Defines:\n"+this.defines),li.LogShaderCodeOnCompilationError){let e,t=null,s=null;this._pipelineContext?._getVertexShaderCode()&&([e,t]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),e&&(a.Error("Vertex code:"),a.Error(e))),this._pipelineContext?._getFragmentShaderCode()&&([e,s]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),e&&(a.Error("Fragment code:"),a.Error(e))),t&&a.Error(t),s&&a.Error(s)}a.Error("Error: "+this._compilationError);const r=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this),this._engine.onEffectErrorObservable.notifyObservers({effect:this,errors:this._compilationError})};t&&(this._pipelineContext=t,this._isReady=!0,r()),i?(this._pipelineContext=null,i.hasMoreFallbacks?(this._allFallbacksProcessed=!1,a.Error("Trying next fallback."),this.defines=i.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,r(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||r())}get isSupported(){return""===this._compilationError}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const s=e+"Ex";if(-1===this._samplerList.indexOf(s+"0")){const i=this._samplerList.indexOf(e);for(let e=1;e<t.length;e++){const t=s+(e-1).toString();this._samplerList.splice(i+e,0,t)}let r=0;for(const e of this._samplerList)this._samplers[e]=r,r+=1}this._engine.setTextureArray(this._samplers[e],this._uniforms[e],t,e)}bindUniformBuffer(e,t){const s=this._uniformBuffersNames[t];void 0===s||li._BaseCache[s]===e&&this._engine._features.useUBOBindingCache||(li._BaseCache[s]=e,this._engine.bindUniformBufferBase(e,s,t))}bindUniformBlock(e,t){this._engine.bindUniformBlock(this._pipelineContext,e,t)}setInt(e,t){return this._pipelineContext.setInt(e,t),this}setInt2(e,t,s){return this._pipelineContext.setInt2(e,t,s),this}setInt3(e,t,s,i){return this._pipelineContext.setInt3(e,t,s,i),this}setInt4(e,t,s,i,r){return this._pipelineContext.setInt4(e,t,s,i,r),this}setIntArray(e,t){return this._pipelineContext.setIntArray(e,t),this}setIntArray2(e,t){return this._pipelineContext.setIntArray2(e,t),this}setIntArray3(e,t){return this._pipelineContext.setIntArray3(e,t),this}setIntArray4(e,t){return this._pipelineContext.setIntArray4(e,t),this}setUInt(e,t){return this._pipelineContext.setUInt(e,t),this}setUInt2(e,t,s){return this._pipelineContext.setUInt2(e,t,s),this}setUInt3(e,t,s,i){return this._pipelineContext.setUInt3(e,t,s,i),this}setUInt4(e,t,s,i,r){return this._pipelineContext.setUInt4(e,t,s,i,r),this}setUIntArray(e,t){return this._pipelineContext.setUIntArray(e,t),this}setUIntArray2(e,t){return this._pipelineContext.setUIntArray2(e,t),this}setUIntArray3(e,t){return this._pipelineContext.setUIntArray3(e,t),this}setUIntArray4(e,t){return this._pipelineContext.setUIntArray4(e,t),this}setFloatArray(e,t){return this._pipelineContext.setArray(e,t),this}setFloatArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setFloatArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setFloatArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setArray(e,t){return this._pipelineContext.setArray(e,t),this}setArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setMatrices(e,t){return this._pipelineContext.setMatrices(e,t),this}setMatrix(e,t){return this._pipelineContext.setMatrix(e,t),this}setMatrix3x3(e,t){return this._pipelineContext.setMatrix3x3(e,t),this}setMatrix2x2(e,t){return this._pipelineContext.setMatrix2x2(e,t),this}setFloat(e,t){return this._pipelineContext.setFloat(e,t),this}setBool(e,t){return this._pipelineContext.setInt(e,t?1:0),this}setVector2(e,t){return this._pipelineContext.setVector2(e,t),this}setFloat2(e,t,s){return this._pipelineContext.setFloat2(e,t,s),this}setVector3(e,t){return this._pipelineContext.setVector3(e,t),this}setFloat3(e,t,s,i){return this._pipelineContext.setFloat3(e,t,s,i),this}setVector4(e,t){return this._pipelineContext.setVector4(e,t),this}setQuaternion(e,t){return this._pipelineContext.setQuaternion(e,t),this}setFloat4(e,t,s,i,r){return this._pipelineContext.setFloat4(e,t,s,i,r),this}setColor3(e,t){return this._pipelineContext.setColor3(e,t),this}setColor4(e,t,s){return this._pipelineContext.setColor4(e,t,s),this}setDirectColor4(e,t){return this._pipelineContext.setDirectColor4(e,t),this}clearCodeCache(){this._vertexSourceCode="",this._fragmentSourceCode="",this._fragmentSourceCodeBeforeMigration="",this._vertexSourceCodeBeforeMigration=""}dispose(e=!1){if(e)this._refCount=0;else{if(li.PersistentMode)return;this._refCount--}this._refCount>0||this._isDisposed||(this._onReleaseEffectsObserver&&(this._engine.onReleaseEffectsObservable.remove(this._onReleaseEffectsObserver),this._onReleaseEffectsObserver=null),this._pipelineContext&&oi(this._pipelineContext),this._engine._releaseEffect(this),this.clearCodeCache(),this._isDisposed=!0)}static RegisterShader(e,t,s,i=0){t&&(qs.GetShadersStore(i)[`${e}PixelShader`]=t),s&&(qs.GetShadersStore(i)[`${e}VertexShader`]=s)}static ResetCache(){li._BaseCache={}}}li.LogShaderCodeOnCompilationError=!0,li.PersistentMode=!1,li.AutomaticallyClearCodeCache=!1,li._UniqueIdSeed=0,li._BaseCache={},li.ShadersStore=qs.ShadersStore,li.IncludesShadersStore=qs.IncludesShadersStore;class ci{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}class ui{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get backFunc(){return this._func}set backFunc(e){this._backFunc!==e&&(this._backFunc=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get backOpStencilFail(){return this._backOpStencilFail}set backOpStencilFail(e){this._backOpStencilFail!==e&&(this._backOpStencilFail=e,this._isStencilOpDirty=!0)}get backOpDepthFail(){return this._backOpDepthFail}set backOpDepthFail(e){this._backOpDepthFail!==e&&(this._backOpDepthFail=e,this._isStencilOpDirty=!0)}get backOpStencilDepthPass(){return this._backOpStencilDepthPass}set backOpStencilDepthPass(e){this._backOpStencilDepthPass!==e&&(this._backOpStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){this.stencilMaterial=void 0,this.stencilGlobal?.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){if(!e)return;const t=!this.useStencilGlobalOnly&&!!this.stencilMaterial?.enabled;this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.backFunc=t?this.stencilMaterial.backFunc:this.stencilGlobal.backFunc,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.backOpStencilFail=t?this.stencilMaterial.backOpStencilFail:this.stencilGlobal.backOpStencilFail,this.backOpDepthFail=t?this.stencilMaterial.backOpDepthFail:this.stencilGlobal.backOpDepthFail,this.backOpStencilDepthPass=t?this.stencilMaterial.backOpStencilDepthPass:this.stencilGlobal.backOpStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFuncSeparate(e.FRONT,this.func,this.funcRef,this.funcMask),e.stencilFuncSeparate(e.BACK,this.backFunc,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOpSeparate(e.FRONT,this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),e.stencilOpSeparate(e.BACK,this.backOpStencilFail,this.backOpDepthFail,this.backOpStencilDepthPass),this._isStencilOpDirty=!1))}}class di{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.funcRef=1,this.funcMask=255,this.func=di.ALWAYS,this.opStencilFail=di.KEEP,this.opDepthFail=di.KEEP,this.opStencilDepthPass=di.REPLACE,this.backFunc=di.ALWAYS,this.backOpStencilFail=di.KEEP,this.backOpDepthFail=di.KEEP,this.backOpStencilDepthPass=di.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilBackFunc(){return this.backFunc}set stencilBackFunc(e){this.backFunc=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilBackOpStencilFail(){return this.backOpStencilFail}set stencilBackOpStencilFail(e){this.backOpStencilFail=e}get stencilBackOpDepthFail(){return this.backOpDepthFail}set stencilBackOpDepthFail(e){this.backOpDepthFail=e}get stencilBackOpStencilDepthPass(){return this.backOpStencilDepthPass}set stencilBackOpStencilDepthPass(e){this.backOpStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}}di.ALWAYS=dt.ALWAYS,di.KEEP=dt.KEEP,di.REPLACE=dt.REPLACE;class _i{constructor(e){this._supportBlendParametersPerTarget=e,this._blendFunctionParameters=new Array(32),this._blendEquationParameters=new Array(16),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=Array(8).fill(!1),this._numTargetEnabled=0,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._numTargetEnabled>0}set alphaBlend(e){this.setAlphaBlend(e)}setAlphaBlend(e,t=0){this._alphaBlend[t]!==e&&(e?this._numTargetEnabled++:this._numTargetEnabled--,this._alphaBlend[t]=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,s,i){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===s&&this._blendConstants[3]===i||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=s,this._blendConstants[3]=i,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,s,i,r=0){const n=4*r;this._blendFunctionParameters[n+0]===e&&this._blendFunctionParameters[n+1]===t&&this._blendFunctionParameters[n+2]===s&&this._blendFunctionParameters[n+3]===i||(this._blendFunctionParameters[n+0]=e,this._blendFunctionParameters[n+1]=t,this._blendFunctionParameters[n+2]=s,this._blendFunctionParameters[n+3]=i,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t,s=0){const i=2*s;this._blendEquationParameters[i+0]===e&&this._blendEquationParameters[i+1]===t||(this._blendEquationParameters[i+0]=e,this._blendEquationParameters[i+1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend.fill(!1),this._numTargetEnabled=0,this._blendFunctionParameters.fill(null),this._blendEquationParameters.fill(null),this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e,t=1){if(!this.isDirty)return;if(this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1),1===t||!this._supportBlendParametersPerTarget)return this._isAlphaBlendDirty&&(this._alphaBlend[0]?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),void(this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1));const s=e;if(this._isAlphaBlendDirty){for(let i=0;i<t;i++){const t=i<this._numTargetEnabled?i:0;this._alphaBlend[t]?s.enableIndexed(e.BLEND,i):s.disableIndexed(e.BLEND,i)}this._isAlphaBlendDirty=!1}if(this._isBlendFunctionParametersDirty){for(let e=0;e<t;e++){const t=e<this._numTargetEnabled?4*e:0;s.blendFuncSeparateIndexed(e,this._blendFunctionParameters[t+0],this._blendFunctionParameters[t+1],this._blendFunctionParameters[t+2],this._blendFunctionParameters[t+3])}this._isBlendFunctionParametersDirty=!1}if(this._isBlendEquationParametersDirty){for(let e=0;e<t;e++){const t=e<this._numTargetEnabled?2*e:0;s.blendEquationSeparateIndexed(e,this._blendEquationParameters[t+0],this._blendEquationParameters[t+1])}this._isBlendEquationParametersDirty=!1}}setAlphaMode(e,t){let s=dt.GL_ALPHA_EQUATION_ADD;switch(e){case dt.ALPHA_DISABLE:break;case dt.ALPHA_PREMULTIPLIED:this.setAlphaBlendFunctionParameters(1,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,1,1,t);break;case dt.ALPHA_PREMULTIPLIED_PORTERDUFF:this.setAlphaBlendFunctionParameters(1,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,1,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,t);break;case dt.ALPHA_COMBINE:this.setAlphaBlendFunctionParameters(dt.GL_ALPHA_FUNCTION_SRC_ALPHA,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,1,1,t);break;case dt.ALPHA_ONEONE:this.setAlphaBlendFunctionParameters(1,1,0,1,t);break;case dt.ALPHA_ADD:this.setAlphaBlendFunctionParameters(dt.GL_ALPHA_FUNCTION_SRC_ALPHA,1,0,1,t);break;case dt.ALPHA_SUBTRACT:this.setAlphaBlendFunctionParameters(0,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR,1,1,t);break;case dt.ALPHA_MULTIPLY:this.setAlphaBlendFunctionParameters(dt.GL_ALPHA_FUNCTION_DST_COLOR,0,1,1,t);break;case dt.ALPHA_MAXIMIZED:this.setAlphaBlendFunctionParameters(dt.GL_ALPHA_FUNCTION_SRC_ALPHA,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR,1,1,t);break;case dt.ALPHA_INTERPOLATE:this.setAlphaBlendFunctionParameters(dt.GL_ALPHA_FUNCTION_CONSTANT_COLOR,dt.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR,dt.GL_ALPHA_FUNCTION_CONSTANT_ALPHA,dt.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA,t);break;case dt.ALPHA_SCREENMODE:this.setAlphaBlendFunctionParameters(1,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR,1,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,t);break;case dt.ALPHA_ONEONE_ONEONE:this.setAlphaBlendFunctionParameters(1,1,1,1,t);break;case dt.ALPHA_ALPHATOCOLOR:this.setAlphaBlendFunctionParameters(dt.GL_ALPHA_FUNCTION_DST_ALPHA,1,0,0,t);break;case dt.ALPHA_REVERSEONEMINUS:this.setAlphaBlendFunctionParameters(dt.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR,dt.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,t);break;case dt.ALPHA_SRC_DSTONEMINUSSRCALPHA:this.setAlphaBlendFunctionParameters(1,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,1,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,t);break;case dt.ALPHA_ONEONE_ONEZERO:this.setAlphaBlendFunctionParameters(1,1,1,0,t);break;case dt.ALPHA_EXCLUSION:this.setAlphaBlendFunctionParameters(dt.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR,0,1,t);break;case dt.ALPHA_LAYER_ACCUMULATE:this.setAlphaBlendFunctionParameters(dt.GL_ALPHA_FUNCTION_SRC_ALPHA,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,1,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,t);break;case dt.ALPHA_MIN:this.setAlphaBlendFunctionParameters(1,1,1,1,t),s=dt.GL_ALPHA_EQUATION_MIN;break;case dt.ALPHA_MAX:this.setAlphaBlendFunctionParameters(1,1,1,1,t),s=dt.GL_ALPHA_EQUATION_MAX;break;case dt.ALPHA_DUAL_SRC0_ADD_SRC1xDST:this.setAlphaBlendFunctionParameters(1,dt.GL_ALPHA_FUNCTION_SRC1_COLOR,0,1,t);break;case dt.ALPHA_REPLACE_COLOR:this.setAlphaBlendFunctionParameters(1,0,1,dt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,t)}this.setAlphaEquationParameters(s,s,t)}}class pi{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=dt.TEXTURE_WRAP_ADDRESSMODE,t=dt.TEXTURE_WRAP_ADDRESSMODE,s=dt.TEXTURE_WRAP_ADDRESSMODE,i=1,r=dt.TEXTURE_BILINEAR_SAMPLINGMODE,n=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=s,this._cachedAnisotropicFilteringLevel=i,this.samplingMode=r,this._comparisonFunction=n,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}var fi;!function(e){e[e.Unknown=0]="Unknown",e[e.Url=1]="Url",e[e.Temp=2]="Temp",e[e.Raw=3]="Raw",e[e.Dynamic=4]="Dynamic",e[e.RenderTarget=5]="RenderTarget",e[e.MultiRenderTarget=6]="MultiRenderTarget",e[e.Cube=7]="Cube",e[e.CubeRaw=8]="CubeRaw",e[e.CubePrefiltered=9]="CubePrefiltered",e[e.Raw3D=10]="Raw3D",e[e.Raw2DArray=11]="Raw2DArray",e[e.DepthStencil=12]="DepthStencil",e[e.CubeRawRGBD=13]="CubeRawRGBD",e[e.Depth=14]="Depth",e[e.External=15]="External"}(fi||(fi={}));class gi extends pi{get useMipMaps(){return null===this._useMipMaps?this.generateMipMaps:this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,s=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this._useMipMaps=null,this.mipLevelCount=1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new c,this.onErrorObservable=new c,this.onRebuildCallback=null,this.width=0,this.height=0,this.depth=0,this.baseWidth=0,this.baseHeight=0,this.baseDepth=0,this.invertY=!1,this._invertVScale=!1,this._associatedChannel=-1,this._source=0,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._creationFlags=0,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._hardwareTexture=null,this._maxLodLevel=null,this._references=1,this._gammaSpace=null,this._premulAlpha=!1,this._dynamicTextureSource=null,this._autoMSAAManagement=!1,this._engine=e,this._source=t,this._uniqueId=gi._Counter++,s||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,s=1){this._engine.updateTextureDimensions(this,e,t,s),this.width=e,this.height=t,this.depth=s,this.baseWidth=e,this.baseHeight=t,this.baseDepth=s,this._size=e*t*s}_rebuild(){if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){const e=this.onRebuildCallback(this),t=t=>{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let e;switch(this.source){case 2:break;case 1:return void(e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,e=>{e._swapAndDie(this,!1),this.isReady=!0},null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer));case 3:if(e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer,this.mipLevelCount),e._swapAndDie(this,!1),this._bufferViewArray)for(let e=0;e<this._bufferViewArray.length;e++){const t=this._bufferViewArray[e];t&&this._engine.updateRawTexture(this,t,this.format,this.invertY,this._compression,this.type,this._useSRGBBuffer,e)}this.isReady=!0;break;case 10:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 11:if(e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this.mipLevelCount),e._swapAndDie(this,!1),this._bufferViewArray)for(let e=0;e<this._bufferViewArray.length;e++){const t=this._bufferViewArray[e];t&&this._engine.updateRawTexture2DArray(this,t,this.format,this.invertY,this._compression,this.type,e)}this.isReady=!0;break;case 4:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case 7:return void(e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer,ArrayBuffer.isView(this._buffer)?this._buffer:null));case 8:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case 13:return;case 9:return e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,e=>{e&&e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension),void(e._sphericalPolynomial=this._sphericalPolynomial)}}_swapAndDie(e,t=!0){this._hardwareTexture?.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,e._setUniqueId(gi._Counter++),t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const s=this._engine.getLoadedTexturesCache();let i=s.indexOf(this);-1!==i&&s.splice(i,1),i=s.indexOf(e),-1===i&&s.push(e)}dispose(){this._references--,0===this._references&&(this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}function mi(e,t){if(t){const{requestAnimationFrame:s}=t;if("function"==typeof s)return s(e)}if(Je()){const{requestAnimationFrame:s}=t||window;if("function"==typeof s)return s(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}gi._Counter=0;class Ti{get frameId(){return this._frameId}get isWebGPU(){return this._isWebGPU}_getShaderProcessor(e){return this._shaderProcessor}_resetAlphaMode(){this._alphaMode.fill(-1),this._alphaEquation.fill(-1)}get shaderPlatformName(){return this._shaderPlatformName}_clearEmptyResources(){this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,this._depthCullingState.depthFunc=e?dt.GEQUAL:dt.LEQUAL)}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}_getGlobalDefines(e){if(e)return this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t.textures?.some(e=>15===e.source)||t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}li.ResetCache()}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){a.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout(()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,s=this._depthCullingState.depthFunc,i=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=s,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=r,this._flagContextRestored()},0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return dt.SNAPSHOTRENDERING_STANDARD}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,dt.TEXTUREFORMAT_RGBA,!1,!1,dt.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,dt.TEXTUREFORMAT_RGBA,!1,!1,dt.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,dt.TEXTUREFORMAT_RGBA,!1,!1,dt.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,dt.TEXTUREFORMAT_RGBA,dt.TEXTURETYPE_UNSIGNED_BYTE,!1,!1,dt.TEXTURE_NEAREST_SAMPLINGMODE)}return this._emptyCubeTexture}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}get activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e)return this._activeRenderLoops.length=0,void this._cancelFrame();const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(this.customAnimationFrameRequester){if(0!==this._frameHandler){this._frameHandler=0;const{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID),delete this.customAnimationFrameRequester.requestID}}else if(0!==this._frameHandler){const e=this._frameHandler;if(this._frameHandler=0,Je()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if("function"==typeof t)return t(e)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}get maxFPS(){return this._maxFPS}set maxFPS(e){this._maxFPS=e,void 0!==e&&(this._minFrameTime=e<=0?Number.MAX_VALUE:1e3/e)}_isOverFrameTime(e){if(!e||void 0===this._maxFPS)return!1;const t=e-this._lastFrameTime;return this._lastFrameTime=e,this._renderAccumulator+=t,this._renderAccumulator<this._minFrameTime||(this._renderAccumulator-=this._minFrameTime,this._renderAccumulator>this._minFrameTime&&(this._renderAccumulator=this._minFrameTime),!1)}_processFrame(e){if(this._frameHandler=0,!this._contextWasLost&&!this._isOverFrameTime(e)){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this.skipFrameRender||this._renderViews()||this._renderFrame(),this.endFrame())}}_renderLoop(e){this._processFrame(e),this._activeRenderLoops.length>0&&0===this._frameHandler&&this._queueNewFrameForRenderLoop()}_renderFrame(){for(let e=0;e<this._activeRenderLoops.length;e++){(0,this._activeRenderLoops[e])()}}_renderViews(){return!1}_queueNewFrame(e,t){return mi(e,t)}_queueNewFrameForRenderLoop(){this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())}runRenderLoop(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),1===this._activeRenderLoops.length&&0===this._frameHandler&&this._queueNewFrameForRenderLoop())}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){const e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){const e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}getHostWindow(){return Je()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=!0}_rebuildTextures(){for(const e of this.scenes)e._rebuildTextures();for(const e of this._virtualScenes)e._rebuildTextures()}_releaseRenderTargetWrapper(e){const t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}get currentViewport(){return this._cachedViewport}setViewport(e,t,s){const i=t||this.getRenderWidth(),r=s||this.getRenderHeight(),n=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(n*i,a*r,i*e.width,r*e.height)}createCanvasImage(){return document.createElement("img")}createCanvasPath2D(e){return new Path2D(e)}get description(){let e=this.name+this.version;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}_createTextureBase(e,t,s,i,r=dt.TEXTURE_TRILINEAR_SAMPLINGMODE,n=null,o=null,h,l,c=null,u=null,d=null,_=null,p,f,g){const m="data:"===(e=e||"").substring(0,5),T="blob:"===e.substring(0,5),E=m&&-1!==e.indexOf(";base64,"),R=u||new gi(this,1);R!==u&&(R.label=e.substring(0,60));const b=e;!this._transformTextureUrl||E||u||c||(e=this._transformTextureUrl(e)),b!==e&&(R._originalUrl=b);const A=e.lastIndexOf(".");let y=_||(A>-1?e.substring(A).toLowerCase():"");y.indexOf("?")>-1&&(y=y.split("?")[0]);const M=Ti.GetCompatibleTextureLoader(y,p);i&&i.addPendingData(R),R.url=e,R.generateMipMaps=!t,R.samplingMode=r,R.invertY=s,R._useSRGBBuffer=this._getUseSRGBBuffer(!!g,t),this._doNotHandleContextLost||(R._buffer=c);let x=null;n&&!u&&(x=R.onLoadedObservable.add(n)),u||this._internalTexturesCache.push(R);const S=(s,u)=>{i&&i.removePendingData(R),e===b?(x&&R.onLoadedObservable.remove(x),ee.UseFallbackTexture&&e!==ee.FallbackTexture&&this._createTextureBase(ee.FallbackTexture,t,R.invertY,i,r,null,o,h,l,c,R),s=(s||"Unknown error")+(ee.UseFallbackTexture?" - Fallback texture was used":""),R.onErrorObservable.notifyObservers({message:s,exception:u}),o&&o(s,u)):(a.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,R.invertY,i,r,n,o,h,l,c,R,d,_,p,f,g))};if(M){const t=async e=>{(await M).loadData(e,R,(e,t,s,n,a,o)=>{o?S("TextureLoader failed to load data"):h(R,y,i,{width:e,height:t},R.invertY,!s,n,()=>(a(),!1),r)},f)};if(c){const e=async e=>{try{await t(e)}catch(e){S("Failed to parse texture data",e)}};c instanceof ArrayBuffer?e(new Uint8Array(c)):ArrayBuffer.isView(c)?e(c):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null)}else this._loadFile(e,async e=>{try{await t(new Uint8Array(e))}catch(e){S("Failed to parse texture data",e)}},void 0,i?i.offlineProvider:void 0,!0,(e,t)=>{S("Unable to load "+(e&&e.responseURL,t))})}else{const s=e=>{T&&!this._doNotHandleContextLost&&(R._buffer=e),h(R,y,i,e,R.invertY,t,!1,l,r)};!m||E?c&&("string"==typeof c.decoding||c.close)?s(c):Ti._FileToolsLoadImage(e||"",s,S,i?i.offlineProvider:null,p,R.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0,this):"string"==typeof c||c instanceof ArrayBuffer||ArrayBuffer.isView(c)||c instanceof Blob?Ti._FileToolsLoadImage(c,s,S,i?i.offlineProvider:null,p,R.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0,this):c&&s(c)}return R}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuildAfterContextLost()}get _shouldUseHighPrecisionShader(){return!(!this._caps.highPrecisionShaderSupported||!this._highPrecisionShadersAllowed)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:tt()?document:null}getLoadedTexturesCache(){return this._internalTexturesCache}clearInternalTexturesCache(){this._internalTexturesCache.length=0}getCaps(){return this._caps}resetTextureCache(){for(const e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}get name(){return this._name}set name(e){this._name=e}static get NpmPackage(){return"babylonjs@9.22.2"}static get Version(){return"9.22.2"}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get isStencilEnable(){return this._isStencilEnable}getCreationOptions(){return this._creationOptions}constructor(e,t,s){this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new ci,this._stencilStateComposer=new ui,this._stencilState=new di,this._alphaState=new _i(!1),this._alphaMode=Array(8).fill(-1),this._alphaEquation=Array(8).fill(-1),this._activeRequests=[],this._badOS=!1,this._badDesktopOS=!1,this._compatibilityMode=!0,this._internalTexturesCache=new Array,this._currentRenderTarget=null,this._boundTexturesCache={},this._activeChannel=0,this._currentTextureChannel=-1,this._viewportCached={x:0,y:0,z:0,w:0},this._isWebGPU=!1,this._enableGPUDebugMarkers=!1,this.onCanvasBlurObservable=new c,this.onCanvasFocusObservable=new c,this.onNewSceneAddedObservable=new c,this.onResizeObservable=new c,this.onCanvasPointerOutObservable=new c,this.onEffectErrorObservable=new c,this.disablePerformanceMonitorInBackground=!1,this.disableVertexArrayObjects=!1,this._frameId=0,this.hostInformation={isMobile:!1},this.isFullscreen=!1,this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.currentRenderPassId=dt.RENDERPASS_MAIN,this.isPointerLock=!1,this.postProcesses=[],this.canvasTabIndex=1,this._contextWasLost=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this._renderTargetWrapperCache=new Array,this._compiledEffects={},this._isDisposed=!1,this.scenes=[],this._virtualScenes=new Array,this.onBeforeTextureInitObservable=new c,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this.customAnimationFrameRequester=null,this._windowIsBackground=!1,this._boundRenderFunction=e=>this._renderLoop(e),this._lastFrameTime=0,this._renderAccumulator=0,this.skipFrameRender=!1,this.onBeforeShaderCompilationObservable=new c,this.onAfterShaderCompilationObservable=new c,this.onBeginFrameObservable=new c,this.onEndFrameObservable=new c,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new c,this.onContextRestoredObservable=new c,this._name="",this.premultipliedAlpha=!0,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._doNotHandleContextLost=!1,this.cullBackFaces=null,this._renderPassNames=["main"],this._fps=60,this._deltaTime=0,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this.onDisposeObservable=new c,this.onReleaseEffectsObservable=new c,ee.Instances.push(this),this.startTime=nt.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,J.SetMatrixPrecision(!!t.useLargeWorldRendering||!!t.useHighPrecisionMatrix),et()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),t.antialias=e??t.antialias,t.deterministicLockstep=t.deterministicLockstep??!1,t.lockstepMaxSteps=t.lockstepMaxSteps??4,t.timeStep=t.timeStep??1/60,t.stencil=t.stencil??!0,this._audioContext=t.audioEngineOptions?.audioContext??null,this._audioDestination=t.audioEngineOptions?.audioDestination??null,this.premultipliedAlpha=t.premultipliedAlpha??!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=t.useExactSrgbConversions??!1,this.canvasTabIndex=t.canvasTabIndex??this.canvasTabIndex;const i=Je()&&window.devicePixelRatio||1,r=t.limitDeviceRatio||i;s=s||t.adaptToDeviceRatio||!1,this.adaptToDeviceRatio=s,this._hardwareScalingLevel=s?1/Math.min(r,i):1,this._lastDevicePixelRatio=i,this._creationOptions=t}resize(e=!1){let t,s;if(this.adaptToDeviceRatio){const e=Je()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if(Je()&&tt())if(this._renderingCanvas){const e=this._renderingCanvas.getBoundingClientRect?.();t=this._renderingCanvas.clientWidth||e?.width||this._renderingCanvas.width*this._hardwareScalingLevel||100,s=this._renderingCanvas.clientHeight||e?.height||this._renderingCanvas.height*this._hardwareScalingLevel||100}else t=window.innerWidth,s=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,s=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,s/this._hardwareScalingLevel,e)}setSize(e,t,s=!1){if(!this._renderingCanvas)return!1;if(e|=0,t|=0,!s&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t)return!1;if(this._renderingCanvas.width=e,this._renderingCanvas.height=t,this.scenes){for(let e=0;e<this.scenes.length;e++){const t=this.scenes[e];for(let e=0;e<t.cameras.length;e++){t.cameras[e]._currentRenderId=0}}this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this)}return!0}createRawTexture(e,t,s,i,r,n,a,o,h,l,c,u){throw Le("engine.rawTexture")}createRawCubeTexture(e,t,s,i,r,n,a,o){throw Le("engine.rawTexture")}createRawTexture3D(e,t,s,i,r,n,a,o,h,l,c){throw Le("engine.rawTexture")}createRawTexture2DArray(e,t,s,i,r,n,a,o,h,l,c,u){throw Le("engine.rawTexture")}_sharedInit(e){this._renderingCanvas=e}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&tt()&&"ontouchend"in document},this._checkForMobile(),Je()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){this._drawCalls?.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}_createImageBitmapFromSource(e,t){throw new Error("createImageBitmapFromSource is not implemented")}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,s){throw new Error("resizeImageBitmap is not implemented")}getFontOffset(e){throw new Error("getFontOffset is not implemented")}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);const s=document.createElement("canvas");return s.width=e,s.height=t,s}createCanvas(e,t){return Ti._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,s,i,r,n,a){if(!_t.loadImage)throw Le("FileTools");return _t.loadImage(e,t,s,i,r,n,a)}_loadFile(e,t,s,i,r,n){const a=ft(e,t,s,i,r,n);return this._activeRequests.push(a),a.onCompleteObservable.add(()=>{const e=this._activeRequests.indexOf(a);-1!==e&&this._activeRequests.splice(e,1)}),a}static _FileToolsLoadFile(e,t,s,i,r,n){if(_t.loadFile)return _t.loadFile(e,t,s,i,r,n);throw Le("FileTools")}dispose(){for(this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();this.releaseComputeEffects?.(),li.ResetCache();for(const e of this._activeRequests)e.abort();this._boundRenderFunction=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onNewSceneAddedObservable.clear(),this.onEffectErrorObservable.clear(),Je()&&window.removeEventListener("resize",this._checkForMobile);const e=ee.Instances.indexOf(this);e>=0&&ee.Instances.splice(e,1),ee.Instances.length||(ee.OnEnginesDisposedObservable.notifyObservers(this),ee.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw Le("LoadingScreen")}static MarkAllMaterialsAsDirty(e,t){for(let s=0;s<ee.Instances.length;s++){const i=ee.Instances[s];for(let s=0;s<i.scenes.length;s++)i.scenes[s].markAllMaterialsAsDirty(e,t)}}static GetCompatibleTextureLoader(e,t){return null}}Ti._RenderPassIdCounter=0,Ti._RescalePostProcessFactory=null,Ti.CollisionsEpsilon=.001,Ti.QueueNewFrame=mi;let Ei=!1;function Ri(){Ei||(Ei=!0,Ti.prototype.getRenderPassNames=function(){return this._renderPassNames},Ti.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]},Ti.prototype.createRenderPassId=function(e){const t=++Ti._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t},Ti.prototype.releaseRenderPassId=function(e){this._renderPassNames[e]=void 0;for(let t=0;t<this.scenes.length;++t){const s=this.scenes[t];for(let t=0;t<s.meshes.length;++t){const i=s.meshes[t];if(i._releaseRenderPassId(e),i.subMeshes)for(let t=0;t<i.subMeshes.length;++t){i.subMeshes[t]._removeDrawWrapper(e)}}}})}let bi=(()=>{var e;let t,s,i,r,n,o,h,l,u,d,_,p,f,g,m,T,E,R,y=Qe,M=[],x=[],S=[],v=[],I=[],P=[],C=[],O=[],D=[],w=[],F=[],N=[],B=[],U=[],G=[],V=[],H=[],z=[],W=[],X=[],K=[],Y=[],j=[],q=[],$=[];return e=class extends y{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){let t,s;if(this.mode===e.PERSPECTIVE_CAMERA)this.fovMode===e.FOVMODE_VERTICAL_FIXED?(s=2*this.minZ*Math.tan(this.fov/2),t=this.getEngine().getAspectRatio(this)*s):(t=2*this.minZ*Math.tan(this.fov/2),s=t/this.getEngine().getAspectRatio(this));else{const e=this.getEngine().getRenderWidth()/2,i=this.getEngine().getRenderHeight()/2;t=(this.orthoRight??e)-(this.orthoLeft??-e),s=(this.orthoTop??i)-(this.orthoBottom??-i)}return t*s}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}setFocalLength(e,t=36){this.fov=2*Math.atan(t/(2*e))}get inertia(){return this._baseInertia}set inertia(e){this._baseInertia=e}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(t,s,i,r=!0){Ri(),super(t,i,!1),this.inputs=A(this,M),this._position=A(this,x,xe.Zero()),this._upVector=(A(this,S),A(this,v,xe.Up())),this.oblique=(A(this,I),null),this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=A(this,P,.8),this.projectionPlaneTilt=(A(this,C),A(this,O,0)),this.minZ=(A(this,D),A(this,w,1)),this.maxZ=(A(this,F),A(this,N,1e4)),this._baseInertia=(A(this,B),.9),this._mode=e.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Ks(0,0,1,1),this.layerMask=A(this,U,268435455),this.fovMode=(A(this,G),A(this,V,e.FOVMODE_VERTICAL_FIXED)),this.cameraRigMode=(A(this,H),A(this,z,e.RIG_MODE_NONE)),this.interaxialDistance=(A(this,W),A(this,X,void 0)),this.isStereoscopicSideBySide=(A(this,K),A(this,Y,void 0)),this.ignoreCameraMaxZ=(A(this,j),A(this,q,!1)),this.customRenderTargets=(A(this,$),[]),this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new c,this.onProjectionMatrixChangedObservable=new c,this.onAfterCheckInputsObservable=new c,this.onRestoreStateObservable=new c,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new Ie,this._postProcesses=new Array,this._activeMeshes=new Ws(256),this._globalPosition=xe.Zero(),this._computedViewMatrix=Ie.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=Ie.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=ve.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.layerMask=this.getScene().defaultCameraLayerMask,this.getScene().addCamera(this),r&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=s,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${t}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}hasStateStored(){return!!this._stateStored}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let s=0;s<this.animations.length;s++)t+=", animation[0]: "+this.animations[s].toString(e);return t}applyVerticalCorrection(){const e=this.absoluteRotation.toEulerAngles();this.projectionPlaneTilt=this._scene.useRightHandedSystem?-e.x:e.x}get globalPosition(){return this._globalPosition}getActiveMeshes(){return this._activeMeshes}isActiveMesh(e){return-1!==this._activeMeshes.indexOf(e)}isReady(e=!1){if(e)for(const e of this._postProcesses)if(e&&!e.isReady())return!1;return super.isReady(e)}_initCache(){super._initCache(),this._cache.position=new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.obliqueAngle=void 0,this._cache.obliqueLength=void 0,this._cache.obliqueOffset=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0}_updateCache(e){e||super._updateCache(),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)}_isSynchronized(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()}_isSynchronizedViewMatrix(){return!!super._isSynchronized()&&(this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent())}_isSynchronizedProjectionMatrix(){const t=this.ignoreCameraMaxZ?0:this.maxZ;let s=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===t;if(!s)return!1;const i=this.getEngine();return this.mode===e.PERSPECTIVE_CAMERA?s=this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===i.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:(s=this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===i.getRenderWidth()&&this._cache.renderHeight===i.getRenderHeight(),this.oblique&&(s=s&&this._cache.obliqueAngle===this.oblique.angle&&this._cache.obliqueLength===this.oblique.length&&this._cache.obliqueOffset===this.oblique.offset)),s}attachControl(e,t){}detachControl(e){}update(){this._hasMoved=!1,this._checkInputs(),this.cameraRigMode!==e.RIG_MODE_NONE&&this._updateRigCameras(),this.getViewMatrix(),this.getProjectionMatrix()}_checkInputs(){this.onAfterCheckInputsObservable.notifyObservers(this)}get rigCameras(){return this._rigCameras}get rigPostProcess(){return this._rigPostProcess}_getFirstPostProcess(){for(let e=0;e<this._postProcesses.length;e++)if(null!==this._postProcesses[e])return this._postProcesses[e];return null}_cascadePostProcessesToRigCams(){const e=this._getFirstPostProcess();e&&e.markTextureDirty();for(let e=0,t=this._rigCameras.length;e<t;e++){const t=this._rigCameras[e],s=t._rigPostProcess;if(s){"pass"===s.getEffectName()&&(t.isIntermediate=0===this._postProcesses.length),t._postProcesses=this._postProcesses.slice(0).concat(s),s.markTextureDirty()}else t._postProcesses=this._postProcesses.slice(0)}}attachPostProcess(e,t=null){return!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(a.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){const t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix}_getViewMatrix(){return Ie.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._worldMatrix.getTranslationToRef(this._globalPosition)),this._computedViewMatrix}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(t){if(this._doNotComputeProjectionMatrix||!t&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;const s=this.ignoreCameraMaxZ?0:this.maxZ;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=s,this._refreshFrustumPlanes=!0;const i=this.getEngine(),r=this.getScene(),n=i.useReverseDepthBuffer;if(this.mode===e.PERSPECTIVE_CAMERA){let t;this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=i.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),t=r.useRightHandedSystem?Ie.PerspectiveFovRHToRef:Ie.PerspectiveFovLHToRef,t(this.fov,i.getAspectRatio(this),n?s:this.minZ,n?this.minZ:s,this._projectionMatrix,this.fovMode===e.FOVMODE_VERTICAL_FIXED,i.isNDCHalfZRange,this.projectionPlaneTilt,n)}else{const e=i.getRenderWidth()/2,t=i.getRenderHeight()/2;r.useRightHandedSystem?this.oblique?Ie.ObliqueOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-t,this.orthoTop??t,n?s:this.minZ,n?this.minZ:s,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,i.isNDCHalfZRange):Ie.OrthoOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-t,this.orthoTop??t,n?s:this.minZ,n?this.minZ:s,this._projectionMatrix,i.isNDCHalfZRange):this.oblique?Ie.ObliqueOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-t,this.orthoTop??t,n?s:this.minZ,n?this.minZ:s,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,i.isNDCHalfZRange):Ie.OrthoOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-t,this.orthoTop??t,n?s:this.minZ,n?this.minZ:s,this._projectionMatrix,i.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=this.oblique?.angle,this._cache.obliqueLength=this.oblique?.length,this._cache.obliqueOffset=this.oblique?.offset,this._cache.renderWidth=i.getRenderWidth(),this._cache.renderHeight=i.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){return(this.radius||(this.target?xe.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?js.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=js.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;for(const s of this.rigCameras)s._updateFrustumPlanes(),t=t||e.isInFrustum(s._frustumPlanes);return t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,s){throw Le("Ray")}getForwardRayToRef(e,t=100,s,i){throw Le("Ray")}dispose(t,s=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){const e=this._parentContainer.cameras.indexOf(this);e>-1&&this._parentContainer.cameras.splice(e,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==e.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){const t=this._postProcesses[e];t&&t.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(t,s)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(t,s){if(this.cameraRigMode!==t){for(;this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=t,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=s.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=this._cameraRigParams.interaxialDistance/.0637*(Math.PI/180),this.cameraRigMode!==e.RIG_MODE_NONE){const e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);const t=this.createRigCamera(this.name+"_R",1);t&&(t._isRightCamera=!0),e&&t&&(this._rigCameras.push(e),this._rigCameras.push(t))}this._setRigMode(s),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return Ie.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.ignoreCameraMaxZ?0:this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=t/.0637*(Math.PI/180))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.ignoreCameraMaxZ?0:this.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===e.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)}_setupInputs(){}serialize(){const e=$e.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&this.parent._serializeAsParent(e),this.inputs&&this.inputs.serialize(e),$e.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}clone(t,s=null){const i=$e.Clone(e.GetConstructorFromName(this.getClassName(),t,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this);return i.name=t,i.parent=s,this.onClonedObservable.notifyObservers(i),i}getDirection(e){const t=xe.Zero();return this.getDirectionToRef(e,t),t}get absoluteRotation(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation}getDirectionToRef(e,t){xe.TransformNormalToRef(e,this.getWorldMatrix(),t)}static GetConstructorFromName(t,s,i,r=0,n=!0){const a=Qe.Construct(t,s,i,{interaxial_distance:r,isStereoscopicSideBySide:n});return a||(()=>e._CreateDefaultParsedCamera(s,i))}computeWorldMatrix(){return this.getWorldMatrix()}_calculateHandednessMultiplier(){let e=this.getScene().useRightHandedSystem?-1:1;return this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(e*=-1),e}},(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(y[Symbol.metadata]??null):void 0;t=[k("position")],s=[k("upVector")],i=[L()],r=[L()],n=[L()],o=[L()],h=[L()],l=[L()],u=[L()],d=[L()],_=[L()],p=[L()],f=[L()],g=[L()],m=[L()],T=[L()],E=[L()],R=[L()],b(e,null,i,{kind:"getter",name:"orthoLeft",static:!1,private:!1,access:{has:e=>"orthoLeft"in e,get:e=>e.orthoLeft},metadata:a},null,M),b(e,null,r,{kind:"getter",name:"orthoRight",static:!1,private:!1,access:{has:e=>"orthoRight"in e,get:e=>e.orthoRight},metadata:a},null,M),b(e,null,n,{kind:"getter",name:"orthoBottom",static:!1,private:!1,access:{has:e=>"orthoBottom"in e,get:e=>e.orthoBottom},metadata:a},null,M),b(e,null,o,{kind:"getter",name:"orthoTop",static:!1,private:!1,access:{has:e=>"orthoTop"in e,get:e=>e.orthoTop},metadata:a},null,M),b(e,null,_,{kind:"getter",name:"inertia",static:!1,private:!1,access:{has:e=>"inertia"in e,get:e=>e.inertia},metadata:a},null,M),b(e,null,p,{kind:"getter",name:"mode",static:!1,private:!1,access:{has:e=>"mode"in e,get:e=>e.mode},metadata:a},null,M),b(null,null,t,{kind:"field",name:"_position",static:!1,private:!1,access:{has:e=>"_position"in e,get:e=>e._position,set:(e,t)=>{e._position=t}},metadata:a},x,S),b(null,null,s,{kind:"field",name:"_upVector",static:!1,private:!1,access:{has:e=>"_upVector"in e,get:e=>e._upVector,set:(e,t)=>{e._upVector=t}},metadata:a},v,I),b(null,null,h,{kind:"field",name:"fov",static:!1,private:!1,access:{has:e=>"fov"in e,get:e=>e.fov,set:(e,t)=>{e.fov=t}},metadata:a},P,C),b(null,null,l,{kind:"field",name:"projectionPlaneTilt",static:!1,private:!1,access:{has:e=>"projectionPlaneTilt"in e,get:e=>e.projectionPlaneTilt,set:(e,t)=>{e.projectionPlaneTilt=t}},metadata:a},O,D),b(null,null,u,{kind:"field",name:"minZ",static:!1,private:!1,access:{has:e=>"minZ"in e,get:e=>e.minZ,set:(e,t)=>{e.minZ=t}},metadata:a},w,F),b(null,null,d,{kind:"field",name:"maxZ",static:!1,private:!1,access:{has:e=>"maxZ"in e,get:e=>e.maxZ,set:(e,t)=>{e.maxZ=t}},metadata:a},N,B),b(null,null,f,{kind:"field",name:"layerMask",static:!1,private:!1,access:{has:e=>"layerMask"in e,get:e=>e.layerMask,set:(e,t)=>{e.layerMask=t}},metadata:a},U,G),b(null,null,g,{kind:"field",name:"fovMode",static:!1,private:!1,access:{has:e=>"fovMode"in e,get:e=>e.fovMode,set:(e,t)=>{e.fovMode=t}},metadata:a},V,H),b(null,null,m,{kind:"field",name:"cameraRigMode",static:!1,private:!1,access:{has:e=>"cameraRigMode"in e,get:e=>e.cameraRigMode,set:(e,t)=>{e.cameraRigMode=t}},metadata:a},z,W),b(null,null,T,{kind:"field",name:"interaxialDistance",static:!1,private:!1,access:{has:e=>"interaxialDistance"in e,get:e=>e.interaxialDistance,set:(e,t)=>{e.interaxialDistance=t}},metadata:a},X,K),b(null,null,E,{kind:"field",name:"isStereoscopicSideBySide",static:!1,private:!1,access:{has:e=>"isStereoscopicSideBySide"in e,get:e=>e.isStereoscopicSideBySide,set:(e,t)=>{e.isStereoscopicSideBySide=t}},metadata:a},Y,j),b(null,null,R,{kind:"field",name:"ignoreCameraMaxZ",static:!1,private:!1,access:{has:e=>"ignoreCameraMaxZ"in e,get:e=>e.ignoreCameraMaxZ,set:(e,t)=>{e.ignoreCameraMaxZ=t}},metadata:a},q,$),a&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),e._CreateDefaultParsedCamera=(e,t)=>{throw Le("UniversalCamera")},e.PERSPECTIVE_CAMERA=dt.PERSPECTIVE_CAMERA,e.ORTHOGRAPHIC_CAMERA=dt.ORTHOGRAPHIC_CAMERA,e.FOVMODE_VERTICAL_FIXED=dt.FOVMODE_VERTICAL_FIXED,e.FOVMODE_HORIZONTAL_FIXED=dt.FOVMODE_HORIZONTAL_FIXED,e.RIG_MODE_NONE=dt.RIG_MODE_NONE,e.RIG_MODE_STEREOSCOPIC_ANAGLYPH=dt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,e.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=dt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,e.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=dt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,e.RIG_MODE_STEREOSCOPIC_OVERUNDER=dt.RIG_MODE_STEREOSCOPIC_OVERUNDER,e.RIG_MODE_STEREOSCOPIC_INTERLACED=dt.RIG_MODE_STEREOSCOPIC_INTERLACED,e.RIG_MODE_VR=dt.RIG_MODE_VR,e.RIG_MODE_CUSTOM=dt.RIG_MODE_CUSTOM,e.ForceAttachControlToAlwaysPreventDefault=!1,e})();function Ai(e,t){const s=e.type,i=bi.GetConstructorFromName(s,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=$e.Parse(i,e,t);if(void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=xe.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(xe.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(xe.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t<e.animations.length;t++){const s=e.animations[t],i=Ae("BABYLON.Animation");i&&r.animations.push(i.Parse(s))}Qe.ParseAnimationRanges(r,e,t)}return e.autoAnimate&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&r.setEnabled(e.isEnabled),r}let yi=!1;function Mi(){yi||(yi=!0,bi.Parse=Ai)}class xi{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=xi._Counter++}}function Si(e){return void 0===e.getPipelineContext}xi._Counter=0;class vi{constructor(){this.shaderLanguage=0}postProcessor(e,t,s,i,r){if(r.drawBuffersExtensionDisabled){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}const Ii=/(flat\s)?\s*varying\s*.*/;class Pi{constructor(){this.shaderLanguage=0}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return Ii.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,s){const i=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),s){const s=-1!==e.search(/layout *\(location *= *0\) *out/g),r=-1!==t.indexOf("#define DUAL_SOURCE_BLENDING"),n=r?"layout(location = 0, index = 0) out vec4 glFragColor;\nlayout(location = 0, index = 1) out vec4 glFragColor2;\n":"layout(location = 0) out vec4 glFragColor;\n";r&&(e="#extension GL_EXT_blend_func_extended : require\n"+e),e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(i||s?"":n)+"void main(")}else{t.indexOf("#define VERTEXOUTPUT_INVARIANT")>=0&&(e="invariant gl_Position;\n"+e);if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}return e}}class Ci extends xi{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class Oi{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){return this._MSAARenderBuffers?.[e]??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}function Di(e){return e===dt.TEXTUREFORMAT_DEPTH24_STENCIL8||e===dt.TEXTUREFORMAT_DEPTH32_FLOAT||e===dt.TEXTUREFORMAT_DEPTH16||e===dt.TEXTUREFORMAT_DEPTH24||e===dt.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||e===dt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8||e===dt.TEXTUREFORMAT_STENCIL8}function wi(e){switch(e){case dt.TEXTUREFORMAT_DEPTH24_STENCIL8:case dt.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8:case dt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8:case dt.TEXTUREFORMAT_DEPTH32_FLOAT:case dt.TEXTUREFORMAT_DEPTH24:return dt.TEXTURETYPE_FLOAT;case dt.TEXTUREFORMAT_DEPTH16:return dt.TEXTURETYPE_UNSIGNED_SHORT;case dt.TEXTUREFORMAT_STENCIL8:return dt.TEXTURETYPE_UNSIGNED_BYTE}return dt.TEXTURETYPE_UNSIGNED_BYTE}function Li(e){return e===dt.TEXTUREFORMAT_DEPTH24_STENCIL8||e===dt.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||e===dt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8||e===dt.TEXTUREFORMAT_STENCIL8}class Fi{}class Ni extends Ti{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return li.ShadersRepository}static set ShadersRepository(e){li.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,s,i){if(s=s||{},super(t??s.antialias,s,i),this._name="WebGL",this.forcePOTTextures=!1,this.validateShaderPrograms=!1,this.disableUniformBuffers=!1,this._webGLVersion=1,this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},!e)return;let r;if(e.getContext){if(r=e,void 0===s.preserveDrawingBuffer&&(s.preserveDrawingBuffer=!1),void 0===s.xrCompatible&&(s.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of Ni.ExceptionList){const i=t.key,r=t.targets;if(new RegExp(i).test(e)){if(t.capture&&t.captureConstraint){const s=t.capture,i=t.captureConstraint,r=new RegExp(s).exec(e);if(r&&r.length>0){if(parseInt(r[r.length-1])>=i)continue}}for(const e of r)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":s.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost?this._onContextLost=()=>{ei(this._gl)}:(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,ei(this._gl),a.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},r.addEventListener("webglcontextrestored",this._onContextRestored,!1),s.powerPreference=s.powerPreference||"high-performance"),r.addEventListener("webglcontextlost",this._onContextLost,!1),this._badDesktopOS&&(s.xrCompatible=!1),!s.disableWebGL2Support)try{this._gl=r.getContext("webgl2",s)||r.getContext("experimental-webgl2",s),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!r)throw new Error("The provided canvas is null or undefined.");try{this._gl=r.getContext("webgl",s)||r.getContext("experimental-webgl",s)}catch(e){throw new Error("WebGL not supported",{cause:e})}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,r=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";const t=this._gl.getContextAttributes();t&&(s.stencil=t.stencil)}this._sharedInit(r),this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==s.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=s.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e<this._caps.maxVertexAttribs;e++)this._currentBufferPointers[e]=new Fi;this._shaderProcessor=this.webGLVersion>1?new Pi:new vi;const n=`Babylon.js v${Ni.Version}`;a.Log(n+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",n);const o=Js(this._gl);o.validateShaderPrograms=this.validateShaderPrograms,o.parallelShaderCompile=this._caps.parallelShaderCompile}_clearEmptyResources(){this._dummyFramebuffer=null,super._clearEmptyResources()}_getShaderProcessingContext(e){return null}areAllEffectsReady(){for(const e in this._compiledEffects){if(!this._compiledEffects[e].isReady())return!1}return!0}_initGLContext(){this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),shaderFloatPrecision:0,parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||null!==this._gl.getExtension("OES_standard_derivatives"),maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),blendFloat:null!==this._gl.getExtension("EXT_float_blend"),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:1!==this._webGLVersion,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1,textureNorm16:!!this._gl.getExtension("EXT_texture_norm16"),blendParametersPerTarget:!1,dualSourceBlending:!1,supportReadWriteStorageTextures:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");null!=e&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.textureNorm16&&(this._gl.R16_EXT=33322,this._gl.RG16_EXT=33324,this._gl.RGB16_EXT=32852,this._gl.RGBA16_EXT=32859,this._gl.R16_SNORM_EXT=36760,this._gl.RG16_SNORM_EXT=36761,this._gl.RGB16_SNORM_EXT=36762,this._gl.RGBA16_SNORM_EXT=36763);const t=this._gl.getExtension("OES_draw_buffers_indexed");if(this._caps.blendParametersPerTarget=!!t,this._alphaState=new _i(this._caps.blendParametersPerTarget),t&&(this._gl.blendEquationSeparateIndexed=t.blendEquationSeparateiOES.bind(t),this._gl.blendEquationIndexed=t.blendEquationiOES.bind(t),this._gl.blendFuncSeparateIndexed=t.blendFuncSeparateiOES.bind(t),this._gl.blendFuncIndexed=t.blendFunciOES.bind(t),this._gl.colorMaskIndexed=t.colorMaskiOES.bind(t),this._gl.disableIndexed=t.disableiOES.bind(t),this._gl.enableIndexed=t.enableiOES.bind(t)),this._caps.dualSourceBlending=!!this._gl.getExtension("WEBGL_blend_func_extended"),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES),this._caps.maxDrawBuffers=this._gl.getParameter(this._gl.MAX_DRAW_BUFFERS);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._caps.maxDrawBuffers=this._gl.getParameter(e.MAX_DRAW_BUFFERS_WEBGL),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);if(e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision,this._caps.shaderFloatPrecision=Math.min(e.precision,t.precision)),!this._shouldUseHighPrecisionShader){const e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.MEDIUM_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.MEDIUM_FLOAT);e&&t&&(this._caps.shaderFloatPrecision=Math.min(e.precision,t.precision))}this._caps.shaderFloatPrecision<10&&(this._caps.shaderFloatPrecision=10)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}if(this._creationOptions){const e=this._creationOptions.forceSRGBBufferSupportState;void 0!==e&&(this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&e)}}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e<this._maxSimultaneousTextures;e++)this._nextFreeTextureSlots.push(e);"Mali-G72"===this._glRenderer&&(this._caps.disableMorphTargetTexture=!0)}_initFeatures(){this._features={forceBitmapOverHTMLImageElement:"undefined"==typeof HTMLImageElement,supportRenderAndCopyToLodForFloatTextures:1!==this._webGLVersion,supportDepthStencilTexture:1!==this._webGLVersion,supportShadowSamplers:1!==this._webGLVersion,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:1!==this._webGLVersion,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:1!==this._webGLVersion,basisNeedsPOT:1===this._webGLVersion,support3DTextures:1!==this._webGLVersion,needTypeSuffixInShaderConstants:1!==this._webGLVersion,supportMSAA:1!==this._webGLVersion,supportSSAO2:1!==this._webGLVersion,supportIBLShadows:1!==this._webGLVersion,supportExtendedTextureFormats:1!==this._webGLVersion,supportSwitchCaseInShader:1!==this._webGLVersion,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1}}get webGLVersion(){return this._webGLVersion}getClassName(){return"ThinEngine"}_prepareWorkingCanvas(){if(this._workingCanvas)return;this._workingCanvas=this.createCanvas(1,1);const e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}getInfo(){return this.getGlInfo()}getGlInfo(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}}extractDriverInfo(){const e=this.getGlInfo();return e&&e.renderer?e.renderer:""}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight}clear(e,t,s,i=!1,r=0){const n=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=n;let a=0;if(t&&e){let t=!0;if(this._currentRenderTarget){const s=this._currentRenderTarget.texture?.format;if(s===dt.TEXTUREFORMAT_RED_INTEGER||s===dt.TEXTUREFORMAT_RG_INTEGER||s===dt.TEXTUREFORMAT_RGB_INTEGER||s===dt.TEXTUREFORMAT_RGBA_INTEGER){const s=this._currentRenderTarget.texture?.type;s===dt.TEXTURETYPE_UNSIGNED_INTEGER||s===dt.TEXTURETYPE_UNSIGNED_SHORT?(Ni._TempClearColorUint32[0]=255*e.r,Ni._TempClearColorUint32[1]=255*e.g,Ni._TempClearColorUint32[2]=255*e.b,Ni._TempClearColorUint32[3]=255*e.a,this._gl.clearBufferuiv(this._gl.COLOR,0,Ni._TempClearColorUint32),t=!1):(Ni._TempClearColorInt32[0]=255*e.r,Ni._TempClearColorInt32[1]=255*e.g,Ni._TempClearColorInt32[2]=255*e.b,Ni._TempClearColorInt32[3]=255*e.a,this._gl.clearBufferiv(this._gl.COLOR,0,Ni._TempClearColorInt32),t=!1)}}t&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),a|=this._gl.COLOR_BUFFER_BIT)}s&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),a|=this._gl.DEPTH_BUFFER_BIT),i&&(this._gl.clearStencil(r),a|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(a)}_viewport(e,t,s,i){e===this._viewportCached.x&&t===this._viewportCached.y&&s===this._viewportCached.z&&i===this._viewportCached.w||(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=s,this._viewportCached.w=i,this._gl.viewport(e,t,s,i))}endFrame(){super.endFrame(),this._badOS&&this.flushFramebuffer()}get performanceMonitor(){throw new Error("Not Supported by ThinEngine")}bindFramebuffer(e,t=0,s,i,r,n=0,o=0){const h=e;this._currentRenderTarget&&this._resolveAndGenerateMipMapsFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(h._framebuffer);const l=this._gl;e.isMulti||(e.is2DArray||e.is3D?(l.framebufferTextureLayer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,e.texture._hardwareTexture?.underlyingResource,n,o),h._currentLOD=n):e.isCube?l.framebufferTexture2D(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_CUBE_MAP_POSITIVE_X+t,e.texture._hardwareTexture?.underlyingResource,n):h._currentLOD!==n&&(l.framebufferTexture2D(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_2D,e.texture._hardwareTexture?.underlyingResource,n),h._currentLOD=n));const c=e._depthStencilTexture;if(c){e.is3D&&(e.texture.width===c.width&&e.texture.height===c.height&&e.texture.depth===c.depth||a.Warn("Depth/Stencil attachment for 3D target must have same dimensions as color attachment"));const s=e._depthStencilTextureWithStencil?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT;e.is2DArray||e.is3D?l.framebufferTextureLayer(l.FRAMEBUFFER,s,c._hardwareTexture?.underlyingResource,n,o):e.isCube?l.framebufferTexture2D(l.FRAMEBUFFER,s,l.TEXTURE_CUBE_MAP_POSITIVE_X+t,c._hardwareTexture?.underlyingResource,n):l.framebufferTexture2D(l.FRAMEBUFFER,s,l.TEXTURE_2D,c._hardwareTexture?.underlyingResource,n)}h._MSAAFramebuffer&&this._bindUnboundFramebuffer(h._MSAAFramebuffer),this._cachedViewport&&!r?this.setViewport(this._cachedViewport,s,i):(s||(s=e.width,n&&(s/=Math.pow(2,n))),i||(i=e.height,n&&(i/=Math.pow(2,n))),this._viewport(0,0,s,i)),this.wipeCaches()}setStateCullFaceType(e,t){const s=this.cullBackFaces??e??1?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==s||t)&&(this._depthCullingState.cullFace=s)}setState(e,t=0,s,i=!1,r,n,a=0){(this._depthCullingState.cull!==e||s)&&(this._depthCullingState.cull=e),this.setStateCullFaceType(r,s),this.setZOffset(t),this.setZOffsetUnits(a);const o=i?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==o||s)&&(this._depthCullingState.frontFace=o),this._stencilStateComposer.stencilMaterial=n}_resolveAndGenerateMipMapsFramebuffer(e,t=!1){e.disableAutomaticMSAAResolve||(e.isMulti?this.resolveMultiFramebuffer(e):this.resolveFramebuffer(e)),t||(e.isMulti?this.generateMipMapsMultiFramebuffer(e):this.generateMipMapsFramebuffer(e))}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentFramebuffer}generateMipmaps(e){const t=this._getTextureTarget(e);this._bindTextureDirectly(t,e,!0),this._gl.generateMipmap(t),this._bindTextureDirectly(t,null)}unBindFramebuffer(e,t,s){const i=e;this._currentRenderTarget=null,this._resolveAndGenerateMipMapsFramebuffer(e,t),s&&(i._MSAAFramebuffer&&this._bindUnboundFramebuffer(i._framebuffer),s()),this._bindUnboundFramebuffer(null)}generateMipMapsFramebuffer(e){e.isMulti||!e.texture?.generateMipMaps||e.isCube||this.generateMipmaps(e.texture)}resolveFramebuffer(e){const t=e,s=this._gl;if(!t._MSAAFramebuffer||t.isMulti)return;let i=t.resolveMSAAColors?s.COLOR_BUFFER_BIT:0;i|=t._generateDepthBuffer&&t.resolveMSAADepth?s.DEPTH_BUFFER_BIT:0,i|=t._generateStencilBuffer&&t.resolveMSAAStencil?s.STENCIL_BUFFER_BIT:0,s.bindFramebuffer(s.READ_FRAMEBUFFER,t._MSAAFramebuffer),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,t._framebuffer),s.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,i,s.NEAREST)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e,t,s){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){const s=this._gl.createBuffer();if(!s)throw new Error("Unable to create vertex buffer");const i=new Ci(s);return this.bindArrayBuffer(i),"number"!=typeof e?e instanceof Array?(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t),i.capacity=4*e.length):(this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),i.capacity=e.byteLength):(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Uint8Array(e),t),i.capacity=e),this._resetVertexBufferBinding(),i.references=1,i}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,s){const i=this._gl.createBuffer(),r=new Ci(i);if(!i)throw new Error("Unable to create index buffer");this.bindIndexBuffer(r);const n=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,n,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),r.references=1,r.is32Bits=4===n.BYTES_PER_ELEMENT,r}_normalizeIndexData(e){if(2===e.BYTES_PER_ELEMENT)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let t=0;t<e.length;t++)if(e[t]>=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,s){const i=e.program,r=this._gl.getUniformBlockIndex(i,t);this._gl.uniformBlockBinding(i,r,s)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,s,i,r,n,a){const o=this._currentBufferPointers[t];if(!o)return;let h=!1;o.active?(o.buffer!==e&&(o.buffer=e,h=!0),o.size!==s&&(o.size=s,h=!0),o.type!==i&&(o.type=i,h=!0),o.normalized!==r&&(o.normalized=r,h=!0),o.stride!==n&&(o.stride=n,h=!0),o.offset!==a&&(o.offset=a,h=!0)):(h=!0,o.active=!0,o.index=t,o.size=s,o.type=i,o.normalized=r,o.stride=n,o.offset=a,o.buffer=e),(h||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),i===this._gl.UNSIGNED_INT||i===this._gl.INT?this._gl.vertexAttribIPointer(t,s,i,n,a):this._gl.vertexAttribPointer(t,s,i,r,n,a))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,s){const i=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r<i.length;r++){const n=t.getAttributeLocation(r);if(n>=0){const t=i[r];let a=null;if(s&&(a=s[t]),a||(a=e[t]),!a)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const o=a.getBuffer();o&&(this._vertexAttribPointer(o,n,a.getSize(),a.type,a.normalized,a.byteStride,a.byteOffset),a.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,a.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(o))))}}}recordVertexArrayObject(e,t,s,i){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,s,i),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,s,i,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const t=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let a=0;a<t;a++)if(a<s.length){const t=r.getAttributeLocation(a);t>=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,s[a],this._gl.FLOAT,!1,i,n)),n+=4*s[a]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,s,i){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===s||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s,this._bindVertexBuffersAttributes(e,s,i)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,s=this._currentInstanceLocations.length;t<s;t++){const s=this._currentInstanceBuffers[t];e!=s&&s.references&&(e=s,this.bindArrayBuffer(s));const i=this._currentInstanceLocations[t];this._gl.vertexAttribDivisor(i,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0}releaseVertexArrayObject(e){this._gl.deleteVertexArray(e)}_releaseBuffer(e){return e.references--,0===e.references&&(this._deleteBuffer(e),!0)}_deleteBuffer(e){this._gl.deleteBuffer(e.underlyingResource)}updateAndBindInstancesBuffer(e,t,s){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),void 0!==s[0].index)this.bindInstancesBuffer(e,s,!0);else for(let t=0;t<4;t++){const i=s[t];this._vertexAttribArraysEnabled[i]||(this._gl.enableVertexAttribArray(i),this._vertexAttribArraysEnabled[i]=!0),this._vertexAttribPointer(e,i,4,this._gl.FLOAT,!1,64,16*t),this._gl.vertexAttribDivisor(i,1),this._currentInstanceLocations.push(i),this._currentInstanceBuffers.push(e)}}bindInstancesBuffer(e,t,s=!0){this.bindArrayBuffer(e);let i=0;if(s)for(let e=0;e<t.length;e++){i+=4*t[e].attributeSize}for(let s=0;s<t.length;s++){const r=t[s];void 0===r.index&&(r.index=this._currentEffect.getAttributeLocationByName(r.attributeName)),r.index<0||(this._vertexAttribArraysEnabled[r.index]||(this._gl.enableVertexAttribArray(r.index),this._vertexAttribArraysEnabled[r.index]=!0),this._vertexAttribPointer(e,r.index,r.attributeSize,r.attributeType||this._gl.FLOAT,r.normalized||!1,i,r.offset),this._gl.vertexAttribDivisor(r.index,void 0===r.divisor?1:r.divisor),this._currentInstanceLocations.push(r.index),this._currentInstanceBuffers.push(e))}}disableInstanceAttributeByName(e){if(!this._currentEffect)return;const t=this._currentEffect.getAttributeLocationByName(e);this.disableInstanceAttribute(t)}disableInstanceAttribute(e){let t,s=!1;for(;-1!==(t=this._currentInstanceLocations.indexOf(e));)this._currentInstanceLocations.splice(t,1),this._currentInstanceBuffers.splice(t,1),s=!0;s&&(this._gl.vertexAttribDivisor(e,0),this.disableAttributeByIndex(e))}disableAttributeByIndex(e){this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1}draw(e,t,s,i){this.drawElementsType(e?dt.MATERIAL_TriangleFillMode:dt.MATERIAL_WireFrameFillMode,t,s,i)}drawPointClouds(e,t,s){this.drawArraysType(dt.MATERIAL_PointFillMode,e,t,s)}drawUnIndexed(e,t,s,i){this.drawArraysType(e?dt.MATERIAL_TriangleFillMode:dt.MATERIAL_WireFrameFillMode,t,s,i)}drawElementsType(e,t,s,i){this.applyStates(),this._reportDrawCall();const r=this._drawMode(e),n=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,a=this._uintIndicesCurrentlySet?4:2;i?this._gl.drawElementsInstanced(r,s,n,t*a,i):this._gl.drawElements(r,s,n,t*a)}drawArraysType(e,t,s,i){this.applyStates(),this._reportDrawCall();const r=this._drawMode(e);i?this._gl.drawArraysInstanced(r,t,s,i):this._gl.drawArrays(r,t,s)}_drawMode(e){switch(e){case dt.MATERIAL_TriangleFillMode:return this._gl.TRIANGLES;case dt.MATERIAL_PointFillMode:return this._gl.POINTS;case dt.MATERIAL_WireFrameFillMode:return this._gl.LINES;case dt.MATERIAL_PointListDrawMode:return this._gl.POINTS;case dt.MATERIAL_LineListDrawMode:return this._gl.LINES;case dt.MATERIAL_LineLoopDrawMode:return this._gl.LINE_LOOP;case dt.MATERIAL_LineStripDrawMode:return this._gl.LINE_STRIP;case dt.MATERIAL_TriangleStripDrawMode:return this._gl.TRIANGLE_STRIP;case dt.MATERIAL_TriangleFanDrawMode:return this._gl.TRIANGLE_FAN;default:return this._gl.TRIANGLES}}_releaseEffect(e){this._compiledEffects[e._key]&&delete this._compiledEffects[e._key];const t=e.getPipelineContext();t&&this._deletePipelineContext(t)}_deletePipelineContext(e){const t=e;t&&t.program&&(t.program.__SPECTOR_rebuildProgram=null,oi(t),this._gl&&(this._currentProgram===t.program&&this._setProgram(null),this._gl.deleteProgram(t.program)))}_getGlobalDefines(e){return gt(e,this.isNDCHalfZRange,this.useReverseDepthBuffer,this.useExactSrgbConversions)}createEffect(e,t,s,i,r,n,a,o,h,l=0,c){const u="string"==typeof e?e:e.vertexToken||e.vertexSource||e.vertexElement||e.vertex,d="string"==typeof e?e:e.fragmentToken||e.fragmentSource||e.fragmentElement||e.fragment,_=this._getGlobalDefines(),p=void 0!==t.attributes;let f=r??t.defines??"";_&&(f+=_);const g=u+"+"+d+"@"+f;if(this._compiledEffects[g]){const e=this._compiledEffects[g];return a&&e.isReady()&&a(e),e._refCount++,e}this._gl&&Js(this._gl);const m=new li(e,t,p?this:s,i,this,r,n,a,o,h,g,t.shaderLanguage??l,t.extraInitializationsAsync??c);return this._compiledEffects[g]=m,m}_getShaderSource(e){return this._gl.getShaderSource(e)}createRawShaderProgram(e,t,s,i,r=null){const n=Js(this._gl);return n._contextWasLost=this._contextWasLost,n.validateShaderPrograms=this.validateShaderPrograms,ti(e,t,s,i||this._gl,r)}createShaderProgram(e,t,s,i,r,n=null){const a=Js(this._gl);return a._contextWasLost=this._contextWasLost,a.validateShaderPrograms=this.validateShaderPrograms,si(e,t,s,i,r||this._gl,n)}inlineShaderCode(e){return e}createPipelineContext(e){if(this._gl){Js(this._gl).parallelShaderCompile=this._caps.parallelShaderCompile}const t=function(e){const t=new $s,s=Js(e);return s.parallelShaderCompile&&!s.disableParallelShaderCompile&&(t.isParallelCompiled=!0),t.context=s._context,t}(this._gl);return t.engine=this,t}createMaterialContext(){}createDrawContext(){}_finalizePipelineContext(e){return ri(e,this._gl,this.validateShaderPrograms)}_preparePipelineContextAsync(e,t,s,i,r,n,a,o,h,l,c){const u=Js(this._gl);return u._contextWasLost=this._contextWasLost,u.validateShaderPrograms=this.validateShaderPrograms,u._createShaderProgramInjection=this._createShaderProgram.bind(this),u.createRawShaderProgramInjection=this.createRawShaderProgram.bind(this),u.createShaderProgramInjection=this.createShaderProgram.bind(this),u.loadFileInjection=this._loadFile.bind(this),function(e,t,s,i,r,n,a,o,h,l="",c,u,d){const _=Js(e.context);u||(u=_.createRawShaderProgramInjection??ti),d||(d=_.createShaderProgramInjection??si);const p=e;p.program=i?u(p,t,s,p.context,h):d(p,t,s,o,p.context,h),p.program.__SPECTOR_rebuildProgram=a,c()}(e,t,s,i,0,0,a,o,h,l,c)}_createShaderProgram(e,t,s,i,r=null){return ii(e,t,s,i,r)}_isRenderingStateCompiled(e){return!this._isDisposed&&function(e,t,s){const i=e;if(i._isDisposed)return!1;const r=Js(t);return!!(r&&r.parallelShaderCompile&&r.parallelShaderCompile.COMPLETION_STATUS_KHR&&i.program&&t.getProgramParameter(i.program,r.parallelShaderCompile.COMPLETION_STATUS_KHR))&&(ri(i,t,s),!0)}(e,this._gl,this.validateShaderPrograms)}_executeWhenRenderingStateIsCompiled(e,t){!function(e,t){const s=e;if(!s.isParallelCompiled)return void t(e);const i=s.onCompiled;s.onCompiled=()=>{i?.(),t(e)}}(e,t)}getUniforms(e,t){const s=new Array,i=e;for(let e=0;e<t.length;e++)s.push(this._gl.getUniformLocation(i.program,t[e]));return s}getAttributes(e,t){const s=[],i=e;for(let e=0;e<t.length;e++)try{s.push(this._gl.getAttribLocation(i.program,t[e]))}catch(e){s.push(-1)}return s}enableEffect(e){(e=null!==e&&Si(e)?e.effect:e)&&e!==this._currentEffect&&(this._stencilStateComposer.stencilMaterial=void 0,this.bindSamplers(e),this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setInt(e,t){return!!e&&(this._gl.uniform1i(e,t),!0)}setInt2(e,t,s){return!!e&&(this._gl.uniform2i(e,t,s),!0)}setInt3(e,t,s,i){return!!e&&(this._gl.uniform3i(e,t,s,i),!0)}setInt4(e,t,s,i,r){return!!e&&(this._gl.uniform4i(e,t,s,i,r),!0)}setIntArray(e,t){return!!e&&(this._gl.uniform1iv(e,t),!0)}setIntArray2(e,t){return!(!e||t.length%2!=0)&&(this._gl.uniform2iv(e,t),!0)}setIntArray3(e,t){return!(!e||t.length%3!=0)&&(this._gl.uniform3iv(e,t),!0)}setIntArray4(e,t){return!(!e||t.length%4!=0)&&(this._gl.uniform4iv(e,t),!0)}setUInt(e,t){return!!e&&(this._gl.uniform1ui(e,t),!0)}setUInt2(e,t,s){return!!e&&(this._gl.uniform2ui(e,t,s),!0)}setUInt3(e,t,s,i){return!!e&&(this._gl.uniform3ui(e,t,s,i),!0)}setUInt4(e,t,s,i,r){return!!e&&(this._gl.uniform4ui(e,t,s,i,r),!0)}setUIntArray(e,t){return!!e&&(this._gl.uniform1uiv(e,t),!0)}setUIntArray2(e,t){return!(!e||t.length%2!=0)&&(this._gl.uniform2uiv(e,t),!0)}setUIntArray3(e,t){return!(!e||t.length%3!=0)&&(this._gl.uniform3uiv(e,t),!0)}setUIntArray4(e,t){return!(!e||t.length%4!=0)&&(this._gl.uniform4uiv(e,t),!0)}setArray(e,t){return!!e&&(!(t.length<1)&&(this._gl.uniform1fv(e,t),!0))}setArray2(e,t){return!(!e||t.length%2!=0)&&(this._gl.uniform2fv(e,t),!0)}setArray3(e,t){return!(!e||t.length%3!=0)&&(this._gl.uniform3fv(e,t),!0)}setArray4(e,t){return!(!e||t.length%4!=0)&&(this._gl.uniform4fv(e,t),!0)}setMatrices(e,t){return!!e&&(this._gl.uniformMatrix4fv(e,!1,t),!0)}setMatrix3x3(e,t){return!!e&&(this._gl.uniformMatrix3fv(e,!1,t),!0)}setMatrix2x2(e,t){return!!e&&(this._gl.uniformMatrix2fv(e,!1,t),!0)}setFloat(e,t){return!!e&&(this._gl.uniform1f(e,t),!0)}setFloat2(e,t,s){return!!e&&(this._gl.uniform2f(e,t,s),!0)}setFloat3(e,t,s,i){return!!e&&(this._gl.uniform3f(e,t,s,i),!0)}setFloat4(e,t,s,i,r){return!!e&&(this._gl.uniform4f(e,t,s,i,r),!0)}applyStates(){if(this._depthCullingState.apply(this._gl),this._stencilStateComposer.apply(this._gl),this._alphaState.apply(this._gl,this._currentRenderTarget&&this._currentRenderTarget.textures?this._currentRenderTarget.textures.length:1),this._colorWriteChanged){this._colorWriteChanged=!1;const e=this._colorWrite;this._gl.colorMask(e,e,e,e)}}wipeCaches(e){this.preventCacheWipeBetweenFrames&&!e||(this._currentEffect=null,this._viewportCached.x=0,this._viewportCached.y=0,this._viewportCached.z=0,this._viewportCached.w=0,this._unbindVertexArrayObject(),e&&(this._currentProgram=null,this.resetTextureCache(),this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=this._gl.LEQUAL,this._alphaState.reset(),this._resetAlphaMode(),this._colorWrite=!0,this._colorWriteChanged=!0,this._unpackFlipYCached=null,this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this._mustWipeVertexAttributes=!0,this.unbindAllAttributes()),this._resetVertexBufferBinding(),this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null,this.bindIndexBuffer(null))}_getSamplingParameters(e,t){const s=this._gl;let i=s.NEAREST,r=s.NEAREST,n=!1;switch(e){case dt.TEXTURE_LINEAR_LINEAR_MIPNEAREST:i=s.LINEAR,r=t?s.LINEAR_MIPMAP_NEAREST:s.LINEAR;break;case dt.TEXTURE_LINEAR_LINEAR_MIPLINEAR:i=s.LINEAR,n=!0,r=t?s.LINEAR_MIPMAP_LINEAR:s.LINEAR;break;case dt.TEXTURE_NEAREST_NEAREST_MIPLINEAR:n=!0,i=s.NEAREST,r=t?s.NEAREST_MIPMAP_LINEAR:s.NEAREST;break;case dt.TEXTURE_NEAREST_NEAREST_MIPNEAREST:i=s.NEAREST,r=t?s.NEAREST_MIPMAP_NEAREST:s.NEAREST;break;case dt.TEXTURE_NEAREST_LINEAR_MIPNEAREST:i=s.NEAREST,r=t?s.LINEAR_MIPMAP_NEAREST:s.LINEAR;break;case dt.TEXTURE_NEAREST_LINEAR_MIPLINEAR:n=!0,i=s.NEAREST,r=t?s.LINEAR_MIPMAP_LINEAR:s.LINEAR;break;case dt.TEXTURE_NEAREST_LINEAR:i=s.NEAREST,r=s.LINEAR;break;case dt.TEXTURE_NEAREST_NEAREST:i=s.NEAREST,r=s.NEAREST;break;case dt.TEXTURE_LINEAR_NEAREST_MIPNEAREST:i=s.LINEAR,r=t?s.NEAREST_MIPMAP_NEAREST:s.NEAREST;break;case dt.TEXTURE_LINEAR_NEAREST_MIPLINEAR:n=!0,i=s.LINEAR,r=t?s.NEAREST_MIPMAP_LINEAR:s.NEAREST;break;case dt.TEXTURE_LINEAR_LINEAR:i=s.LINEAR,r=s.LINEAR;break;case dt.TEXTURE_LINEAR_NEAREST:i=s.LINEAR,r=s.NEAREST}return{min:r,mag:i,hasMipMaps:n}}_createTexture(){const e=this._gl.createTexture();if(!e)throw new Error("Unable to create texture");return e}_createHardwareTexture(){return new Oi(this._createTexture(),this._gl)}_createInternalTexture(e,t,s=!0,i=0){let r,n,o=!1,h=dt.TEXTURETYPE_UNSIGNED_BYTE,l=dt.TEXTURE_TRILINEAR_SAMPLINGMODE,c=dt.TEXTUREFORMAT_RGBA,u=!1,d=1,_=!1,p=0,f=!1;void 0!==t&&"object"==typeof t?(r=!!t.generateMipMaps,o=!!t.createMipMaps,h=void 0===t.type?dt.TEXTURETYPE_UNSIGNED_BYTE:t.type,l=void 0===t.samplingMode?dt.TEXTURE_TRILINEAR_SAMPLINGMODE:t.samplingMode,c=void 0===t.format?dt.TEXTUREFORMAT_RGBA:t.format,u=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,d=t.samples??1,n=t.label,_=!!t.createMSAATexture,p=t.comparisonFunction||0,f=!!t.isCube):r=!!t,u&&=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU),(h!==dt.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(h!==dt.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(l=dt.TEXTURE_NEAREST_SAMPLINGMODE),h!==dt.TEXTURETYPE_FLOAT||this._caps.textureFloat||(h=dt.TEXTURETYPE_UNSIGNED_BYTE,a.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const g=Di(c),m=Li(c),T=this._gl,E=new gi(this,i),R=e.width||e,b=e.height||e,A=e.depth||0,y=e.layers||0,M=this._getSamplingParameters(l,(r||o)&&!g),x=0!==y?T.TEXTURE_2D_ARRAY:0!==A?T.TEXTURE_3D:f?T.TEXTURE_CUBE_MAP:T.TEXTURE_2D,S=g?this._getInternalFormatFromDepthTextureFormat(c,!0,m):this._getRGBABufferInternalSizedFormat(h,c,u),v=g?m?T.DEPTH_STENCIL:T.DEPTH_COMPONENT:this._getInternalFormat(c),I=g?this._getWebGLTextureTypeFromDepthTextureFormat(c):this._getWebGLTextureType(h);if(this._bindTextureDirectly(x,E),0!==y)E.is2DArray=!0,T.texImage3D(x,0,S,R,b,y,0,v,I,null);else if(0!==A)E.is3D=!0,T.texImage3D(x,0,S,R,b,A,0,v,I,null);else if(f){E.isCube=!0;for(let e=0;e<6;e++)T.texImage2D(T.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,S,R,b,0,v,I,null)}else T.texImage2D(x,0,S,R,b,0,v,I,null);if(T.texParameteri(x,T.TEXTURE_MAG_FILTER,M.mag),T.texParameteri(x,T.TEXTURE_MIN_FILTER,M.min),T.texParameteri(x,T.TEXTURE_WRAP_S,T.CLAMP_TO_EDGE),T.texParameteri(x,T.TEXTURE_WRAP_T,T.CLAMP_TO_EDGE),g&&this.webGLVersion>1&&(0===p?(T.texParameteri(x,T.TEXTURE_COMPARE_FUNC,dt.LEQUAL),T.texParameteri(x,T.TEXTURE_COMPARE_MODE,T.NONE)):(T.texParameteri(x,T.TEXTURE_COMPARE_FUNC,p),T.texParameteri(x,T.TEXTURE_COMPARE_MODE,T.COMPARE_REF_TO_TEXTURE))),(r||o)&&this._gl.generateMipmap(x),this._bindTextureDirectly(x,null),E._useSRGBBuffer=u,E.baseWidth=R,E.baseHeight=b,E.width=R,E.height=b,E.depth=y||A,E.isReady=!0,E.samples=d,E.generateMipMaps=r,E.samplingMode=l,E.type=h,E.format=c,E.label=n,E.comparisonFunction=p,this._internalTexturesCache.push(E),_){let e;if(e=Di(E.format)?this._setupFramebufferDepthAttachments(Li(E.format),E.format!==dt.TEXTUREFORMAT_STENCIL8,E.width,E.height,d,E.format,!0):this._createRenderBuffer(E.width,E.height,d,-1,this._getRGBABufferInternalSizedFormat(E.type,E.format,E._useSRGBBuffer),-1),!e)throw new Error("Unable to create render buffer");E._autoMSAAManagement=!0;let t=E._hardwareTexture;t||(t=E._hardwareTexture=this._createHardwareTexture()),t.addMSAARenderBuffer(e)}return E}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,s,i,r=dt.TEXTURE_TRILINEAR_SAMPLINGMODE,n=null,a=null,o=null,h=null,l=null,c=null,u,d,_,p){return this._createTextureBase(e,t,s,i,r,n,a,(...e)=>this._prepareWebGLTexture(...e,l),(e,t,s,r,n,a)=>{const o=this._gl,h=s.width===e&&s.height===t;n._creationFlags=_??0;const l=this._getTexImageParametersForCreateTexture(n.format,n._useSRGBBuffer);if(h)return o.texImage2D(o.TEXTURE_2D,0,l.internalFormat,l.format,l.type,s),!1;const c=this._caps.maxTextureSize;if(s.width>c||s.height>c||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!(!this._workingCanvas||!this._workingContext)&&(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(s,0,0,s.width,s.height,0,0,e,t),o.texImage2D(o.TEXTURE_2D,0,l.internalFormat,l.format,l.type,this._workingCanvas),n.width=e,n.height=t,!1);{const e=new gi(this,2);this._bindTextureDirectly(o.TEXTURE_2D,e,!0),o.texImage2D(o.TEXTURE_2D,0,l.internalFormat,l.format,l.type,s),this._rescaleTexture(e,n,i,l.format,()=>{this._releaseTexture(e),this._bindTextureDirectly(o.TEXTURE_2D,n,!0),a()})}return!0},o,h,l,c,u,d,p)}_getTexImageParametersForCreateTexture(e,t){let s,i;return 1===this.webGLVersion?(s=this._getInternalFormat(e,t),i=s):(s=this._getInternalFormat(e,!1),i=this._getRGBABufferInternalSizedFormat(dt.TEXTURETYPE_UNSIGNED_BYTE,e,t)),{internalFormat:i,format:s,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,s,i,r){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,s=!1){const i=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||s);this._setTextureParameterInteger(i,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(i,this._gl.TEXTURE_MIN_FILTER,r.min),s&&r.hasMipMaps&&(t.generateMipMaps=!0,this._gl.generateMipmap(i)),this._bindTextureDirectly(i,null),t.samplingMode=e}updateTextureDimensions(e,t,s,i=1){}updateTextureWrappingMode(e,t,s=null,i=null){const r=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==s&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(s),e),e._cachedWrapV=s),(e.is2DArray||e.is3D)&&null!==i&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(i),e),e._cachedWrapR=i),this._bindTextureDirectly(r,null)}_uploadCompressedDataToTextureDirectly(e,t,s,i,r,n=0,a=0){const o=this._gl;let h=o.TEXTURE_2D;if(e.isCube&&(h=o.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case dt.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2:case dt.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL:this._caps.etc2?t=o.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC:this._caps.etc2?t=o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM:t=o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_5x4:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_5x5:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_6x5:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_6x6:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x5:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x6:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x8:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x5:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x6:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x8:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x10:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_12x10:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_12x12:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;break;case dt.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case dt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}if(e.generateMipMaps){const n=e._hardwareTexture;n.memoryAllocated||(o.texStorage2D(e.isCube?o.TEXTURE_CUBE_MAP:o.TEXTURE_2D,Math.floor(Math.log2(Math.max(s,i)))+1,t,e.width,e.height),n.memoryAllocated=!0),this._gl.compressedTexSubImage2D(h,a,0,0,s,i,t,r)}else this._gl.compressedTexImage2D(h,a,t,s,i,0,r)}_uploadDataToTextureDirectly(e,t,s=0,i=0,r,n=!1){const a=this._gl,o=this._getWebGLTextureType(e.type),h=this._getInternalFormat(e.format),l=void 0===r?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=a.TEXTURE_2D;e.isCube&&(c=a.TEXTURE_CUBE_MAP_POSITIVE_X+s);const u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),_=n?e.width:Math.pow(2,Math.max(u-i,0)),p=n?e.height:Math.pow(2,Math.max(d-i,0));a.texImage2D(c,i,l,_,p,0,h,o,t)}updateTextureData(e,t,s,i,r,n,a=0,o=0,h=!1){const l=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=l.TEXTURE_2D,_=l.TEXTURE_2D;e.isCube&&(_=l.TEXTURE_CUBE_MAP_POSITIVE_X+a,d=l.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),l.texSubImage2D(_,o,s,i,r,n,u,c,t),h&&this._gl.generateMipmap(_),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,s=0,i=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,s,i),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,s,i,r){const n=this._gl;if(!n)return;const a=this._getSamplingParameters(r,!s);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,a.min),s||i||n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,s,i,r,n,a,o,h,l){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?ws(i.width,c):i.width),d=Math.min(c,this.needPOTTextures?ws(i.height,c):i.height),_=this._gl;_&&(e._hardwareTexture?(this._bindTextureDirectly(_.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),e.baseWidth=i.width,e.baseHeight=i.height,e.width=u,e.height=d,e.isReady=!0,e.type=-1!==e.type?e.type:dt.TEXTURETYPE_UNSIGNED_BYTE,e.format=-1!==e.format?e.format:l??(".jpg"!==t||e._useSRGBBuffer?dt.TEXTUREFORMAT_RGBA:dt.TEXTUREFORMAT_RGB),o(u,d,i,t,e,()=>{this._prepareWebGLTextureContinuation(e,s,n,a,h)})||this._prepareWebGLTextureContinuation(e,s,n,a,h)):s&&s.removePendingData(e))}_getInternalFormatFromDepthTextureFormat(e,t,s){const i=this._gl;if(!t)return i.STENCIL_INDEX8;let r=s?i.DEPTH_STENCIL:i.DEPTH_COMPONENT;return this.webGLVersion>1?e===dt.TEXTUREFORMAT_DEPTH16?r=i.DEPTH_COMPONENT16:e===dt.TEXTUREFORMAT_DEPTH24?r=i.DEPTH_COMPONENT24:e===dt.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||e===dt.TEXTUREFORMAT_DEPTH24_STENCIL8?r=s?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24:e===dt.TEXTUREFORMAT_DEPTH32_FLOAT?r=i.DEPTH_COMPONENT32F:e===dt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8&&(r=s?i.DEPTH32F_STENCIL8:i.DEPTH_COMPONENT32F):r=i.DEPTH_COMPONENT16,r}_getWebGLTextureTypeFromDepthTextureFormat(e){const t=this._gl;let s=t.UNSIGNED_INT;return e===dt.TEXTUREFORMAT_DEPTH16?s=t.UNSIGNED_SHORT:e===dt.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||e===dt.TEXTUREFORMAT_DEPTH24_STENCIL8?s=t.UNSIGNED_INT_24_8:e===dt.TEXTUREFORMAT_DEPTH32_FLOAT?s=t.FLOAT:e===dt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8?s=t.FLOAT_32_UNSIGNED_INT_24_8_REV:e===dt.TEXTUREFORMAT_STENCIL8&&(s=t.UNSIGNED_BYTE),s}_setupFramebufferDepthAttachments(e,t,s,i,r=1,n,a=!1){const o=this._gl;n=n??(e?dt.TEXTUREFORMAT_DEPTH24_STENCIL8:dt.TEXTUREFORMAT_DEPTH32_FLOAT);const h=this._getInternalFormatFromDepthTextureFormat(n,t,e);return e&&t?this._createRenderBuffer(s,i,r,o.DEPTH_STENCIL,h,a?-1:o.DEPTH_STENCIL_ATTACHMENT):t?this._createRenderBuffer(s,i,r,h,h,a?-1:o.DEPTH_ATTACHMENT):e?this._createRenderBuffer(s,i,r,h,h,a?-1:o.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,s,i,r,n,a=!0){const o=this._gl.createRenderbuffer();return this._updateRenderBuffer(o,e,t,s,i,r,n,a)}_updateRenderBuffer(e,t,s,i,r,n,a,o=!0){const h=this._gl;return h.bindRenderbuffer(h.RENDERBUFFER,e),i>1&&h.renderbufferStorageMultisample?h.renderbufferStorageMultisample(h.RENDERBUFFER,i,n,t,s):h.renderbufferStorage(h.RENDERBUFFER,r,t,s),-1!==a&&h.framebufferRenderbuffer(h.FRAMEBUFFER,a,h.RENDERBUFFER,e),o&&h.bindRenderbuffer(h.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);-1!==t&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_deleteTexture(e){e?.release()}_setProgram(e){this._currentProgram!==e&&(!function(e,t){t.useProgram(e)}(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const s=e.getSamplers();for(let t=0;t<s.length;t++){const i=e.getUniform(s[t]);i&&(this._boundUniforms[t]=i)}this._currentEffect=null}_activateCurrentTexture(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)}_bindTextureDirectly(e,t,s=!1,i=!1){let r=!1;const n=t&&t._associatedChannel>-1;s&&n&&(this._activeChannel=t._associatedChannel);if(this._boundTexturesCache[this._activeChannel]!==t||i){if(this._activateCurrentTexture(),t&&t.isMultiview)throw a.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,t?._hardwareTexture?.underlyingResource??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else s&&(r=!0,this._activateCurrentTexture());return n&&!s&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),r}_bindTexture(e,t,s){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;const i=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(i,t)}unbindAllTextures(){for(let e=0;e<this._maxSimultaneousTextures;e++)this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,s,i){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,s))}_bindSamplerUniformToChannel(e,t){const s=this._boundUniforms[e];s&&s._currentState!==t&&(this._gl.uniform1i(s,t),s._currentState=t)}_getTextureWrapMode(e){switch(e){case dt.TEXTURE_WRAP_ADDRESSMODE:return this._gl.REPEAT;case dt.TEXTURE_CLAMP_ADDRESSMODE:return this._gl.CLAMP_TO_EDGE;case dt.TEXTURE_MIRROR_ADDRESSMODE:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,s=!1,i=!1,r=""){if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const s=t.getInternalTexture();s&&(s._associatedChannel=e),t.update()}else if(t.delayLoadState===dt.DELAYLOADSTATE_NOTLOADED)return t.delayLoad(),!1;let n;n=i?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!s&&n&&(n._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===n&&(s||this._bindSamplerUniformToChannel(n._associatedChannel,e),a=!1),this._activeChannel=e;const o=this._getTextureTarget(n);if(a&&this._bindTextureDirectly(o,n,s),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const e=t.coordinatesMode!==dt.TEXTURE_CUBIC_MODE&&t.coordinatesMode!==dt.TEXTURE_SKYBOX_MODE?dt.TEXTURE_WRAP_ADDRESSMODE:dt.TEXTURE_CLAMP_ADDRESSMODE;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(o,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,s,i){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===s.length||(this._textureUnits=new Int32Array(s.length));for(let t=0;t<s.length;t++){const i=s[t].getInternalTexture();i?(this._textureUnits[t]=e+t,i._associatedChannel=e+t):this._textureUnits[t]=-1}this._gl.uniform1iv(t,this._textureUnits);for(let e=0;e<s.length;e++)this._setTexture(this._textureUnits[e],s[e],!0)}}_setAnisotropicLevel(e,t,s){const i=this._caps.textureAnisotropicFilterExtension;t.samplingMode!==dt.TEXTURE_LINEAR_LINEAR_MIPNEAREST&&t.samplingMode!==dt.TEXTURE_LINEAR_LINEAR_MIPLINEAR&&t.samplingMode!==dt.TEXTURE_LINEAR_LINEAR&&(s=1),i&&t._cachedAnisotropicFilteringLevel!==s&&(this._setTextureParameterFloat(e,i.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s,this._caps.maxAnisotropy),t),t._cachedAnisotropicFilteringLevel=s)}_setTextureParameterFloat(e,t,s,i){this._bindTextureDirectly(e,i,!0,!0),this._gl.texParameterf(e,t,s)}_setTextureParameterInteger(e,t,s,i){i&&this._bindTextureDirectly(e,i,!0,!0),this._gl.texParameteri(e,t,s)}unbindAllAttributes(){if(this._mustWipeVertexAttributes){this._mustWipeVertexAttributes=!1;for(let e=0;e<this._caps.maxVertexAttribs;e++)this.disableAttributeByIndex(e)}else for(let e=0,t=this._vertexAttribArraysEnabled.length;e<t;e++)e>=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){this._compiledEffects={},this.onReleaseEffectsObservable.notifyObservers(this)}dispose(){Je()&&this._renderingCanvas&&(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._onContextRestored&&this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&this._gl.getExtension("WEBGL_lose_context")?.loseContext(),ei(this._gl)}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(dt.TEXTURETYPE_FLOAT)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(dt.TEXTURETYPE_HALF_FLOAT)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let s=!0;const i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(s=s&&n===t.FRAMEBUFFER_COMPLETE,s=s&&t.getError()===t.NO_ERROR,s&&(t.clear(t.COLOR_BUFFER_BIT),s=s&&t.getError()===t.NO_ERROR),s){t.bindFramebuffer(t.FRAMEBUFFER,null);const e=t.RGBA,i=t.UNSIGNED_BYTE,r=new Uint8Array(4);t.readPixels(0,0,1,1,e,i,r),s=s&&t.getError()===t.NO_ERROR}for(t.deleteTexture(i),t.deleteFramebuffer(r),t.bindFramebuffer(t.FRAMEBUFFER,null);!s&&t.getError()!==t.NO_ERROR;);return s}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case dt.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case dt.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT_OES;case dt.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case dt.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case dt.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case dt.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case dt.TEXTURETYPE_BYTE:return this._gl.BYTE;case dt.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case dt.TEXTURETYPE_SHORT:return this._gl.SHORT;case dt.TEXTURETYPE_UNSIGNED_SHORT:return this._gl.UNSIGNED_SHORT;case dt.TEXTURETYPE_INT:return this._gl.INT;case dt.TEXTURETYPE_UNSIGNED_INTEGER:return this._gl.UNSIGNED_INT;case dt.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case dt.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT;case dt.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case dt.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case dt.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5;case dt.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case dt.TEXTURETYPE_UNSIGNED_INT_24_8:return this._gl.UNSIGNED_INT_24_8;case dt.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case dt.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case dt.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let s=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case dt.TEXTUREFORMAT_ALPHA:s=this._gl.ALPHA;break;case dt.TEXTUREFORMAT_LUMINANCE:s=this._gl.LUMINANCE;break;case dt.TEXTUREFORMAT_LUMINANCE_ALPHA:s=this._gl.LUMINANCE_ALPHA;break;case dt.TEXTUREFORMAT_RED:case dt.TEXTUREFORMAT_R16_UNORM:case dt.TEXTUREFORMAT_R16_SNORM:s=this._gl.RED;break;case dt.TEXTUREFORMAT_RG:case dt.TEXTUREFORMAT_RG16_UNORM:case dt.TEXTUREFORMAT_RG16_SNORM:s=this._gl.RG;break;case dt.TEXTUREFORMAT_RGB:case dt.TEXTUREFORMAT_RGB16_UNORM:case dt.TEXTUREFORMAT_RGB16_SNORM:s=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case dt.TEXTUREFORMAT_RGBA:case dt.TEXTUREFORMAT_RGBA16_UNORM:case dt.TEXTUREFORMAT_RGBA16_SNORM:s=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case dt.TEXTUREFORMAT_RED_INTEGER:s=this._gl.RED_INTEGER;break;case dt.TEXTUREFORMAT_RG_INTEGER:s=this._gl.RG_INTEGER;break;case dt.TEXTUREFORMAT_RGB_INTEGER:s=this._gl.RGB_INTEGER;break;case dt.TEXTUREFORMAT_RGBA_INTEGER:s=this._gl.RGBA_INTEGER}return s}_getRGBABufferInternalSizedFormat(e,t,s=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case dt.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case dt.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case dt.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;case dt.TEXTUREFORMAT_RGB:return s?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case dt.TEXTURETYPE_BYTE:switch(t){case dt.TEXTUREFORMAT_RED:return this._gl.R8_SNORM;case dt.TEXTUREFORMAT_RG:return this._gl.RG8_SNORM;case dt.TEXTUREFORMAT_RGB:return this._gl.RGB8_SNORM;case dt.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8I;case dt.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8I;case dt.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8I;case dt.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case dt.TEXTURETYPE_UNSIGNED_BYTE:switch(t){case dt.TEXTUREFORMAT_RED:return this._gl.R8;case dt.TEXTUREFORMAT_RG:return this._gl.RG8;case dt.TEXTUREFORMAT_RGB:return s?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case dt.TEXTUREFORMAT_RGBA:return s?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case dt.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8UI;case dt.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8UI;case dt.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8UI;case dt.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8UI;case dt.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case dt.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case dt.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case dt.TEXTURETYPE_SHORT:switch(t){case dt.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16I;case dt.TEXTUREFORMAT_R16_SNORM:return this._gl.R16_SNORM_EXT;case dt.TEXTUREFORMAT_RG16_SNORM:return this._gl.RG16_SNORM_EXT;case dt.TEXTUREFORMAT_RGB16_SNORM:return this._gl.RGB16_SNORM_EXT;case dt.TEXTUREFORMAT_RGBA16_SNORM:return this._gl.RGBA16_SNORM_EXT;case dt.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16I;case dt.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16I;case dt.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16I}case dt.TEXTURETYPE_UNSIGNED_SHORT:switch(t){case dt.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16UI;case dt.TEXTUREFORMAT_R16_UNORM:return this._gl.R16_EXT;case dt.TEXTUREFORMAT_RG16_UNORM:return this._gl.RG16_EXT;case dt.TEXTUREFORMAT_RGB16_UNORM:return this._gl.RGB16_EXT;case dt.TEXTUREFORMAT_RGBA16_UNORM:return this._gl.RGBA16_EXT;case dt.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16UI;case dt.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16UI;case dt.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16UI}case dt.TEXTURETYPE_INT:switch(t){case dt.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32I;case dt.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32I;case dt.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32I;case dt.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32I}case dt.TEXTURETYPE_UNSIGNED_INTEGER:switch(t){case dt.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32UI;case dt.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32UI;case dt.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32UI;case dt.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32UI}case dt.TEXTURETYPE_FLOAT:switch(t){case dt.TEXTUREFORMAT_RED:return this._gl.R32F;case dt.TEXTUREFORMAT_RG:return this._gl.RG32F;case dt.TEXTUREFORMAT_RGB:return this._gl.RGB32F;case dt.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA32F}case dt.TEXTURETYPE_HALF_FLOAT:switch(t){case dt.TEXTUREFORMAT_RED:return this._gl.R16F;case dt.TEXTUREFORMAT_RG:return this._gl.RG16F;case dt.TEXTUREFORMAT_RGB:return this._gl.RGB16F;case dt.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA16F}case dt.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.RGB565;case dt.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.R11F_G11F_B10F;case dt.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.RGB9_E5;case dt.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.RGBA4;case dt.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.RGB5_A1;case dt.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:switch(t){case dt.TEXTUREFORMAT_RGBA:return this._gl.RGB10_A2;case dt.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return s?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,s,i,r=!0,n=!0,o=null){const h=r?4:3,l=r?this._gl.RGBA:this._gl.RGB,c=s*i*h;if(o){if(o.length<c)return a.Error(`Data buffer is too small to store the read pixels (${o.length} should be more than ${c})`),Promise.resolve(o)}else o=new Uint8Array(c);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,s,i,l,this._gl.UNSIGNED_BYTE,o),Promise.resolve(o)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{const e=Ti._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!globalThis.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{const e=Ti._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}}Ni._TempClearColorUint32=new Uint32Array(4),Ni._TempClearColorInt32=new Int32Array(4),Ni.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],Ni._ConcatenateShader=pt,Ni._IsSupported=null,Ni._HasMajorPerformanceCaveat=null;let Bi=!1;function Ui(){Bi||(Bi=!0,Ni.prototype.updateDynamicIndexBuffer=function(e,t,s=0){let i;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),i=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,i,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},Ni.prototype.updateDynamicVertexBuffer=function(e,t,s,i){this.bindArrayBuffer(e),void 0===s&&(s=0);const r=t.byteLength||t.length;void 0===i||i>=r&&0===s?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,s,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,s,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,s,new Float32Array(t).subarray(0,i/4)):(t=ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,i):new Uint8Array(t,0,i),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,s,t)),this._resetVertexBufferBinding()})}class ki{get isDisposed(){return this._isDisposed}constructor(e,t,s,i=0,r=!1,n=!1,a=!1,o,h){this._isAlreadyOwned=!1,this._isDisposed=!1,Ui(),e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=s,this._instanced=n,this._divisor=o||1,this._label=h,t instanceof xi?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=a?i:i*Float32Array.BYTES_PER_ELEMENT,r||this.create()}createVertexBuffer(e,t,s,i,r,n=!1,a){const o=n?t:t*Float32Array.BYTES_PER_ELEMENT,h=i?n?i:i*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new Gi(this._engine,this,e,this._updatable,!0,h,void 0===r?this._instanced:r,o,s,void 0,void 0,!0,this._divisor||a)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data)&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label))}_rebuild(){if(this._data)this._buffer=null,this.create(this._data);else{if(!this._buffer)return;if(this._buffer.capacity>0)return void(this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label));a.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,s,i=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,i?t:t*Float32Array.BYTES_PER_ELEMENT,s?s*this.byteStride:void 0),this._data=0===t&&void 0===s?e:null)}_increaseReferences(){this._buffer&&(this._isAlreadyOwned?this._buffer.references++:this._isAlreadyOwned=!0)}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class Gi{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,s,i,r,n,a,o,h,l,c=!1,u=!1,d=1,_=!1){let p;if(this._isDisposed=!1,this.engine=e,"object"==typeof i&&null!==i?(p=i.updatable??!1,r=i.postponeInternalCreation,n=i.stride,a=i.instanced,o=i.offset,h=i.size,l=i.type,c=i.normalized??!1,u=i.useBytes??!1,d=i.divisor??1,_=i.takeBufferOwnership??!1,this._label=i.label):p=!!i,t instanceof ki?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new ki(e,t,p,n,r,a,u,d,this._label),this._ownsBuffer=!0),this.uniqueId=Gi._Counter++,this._kind=s,void 0===l){const e=this.getData();this.type=e?Hi(e):Gi.FLOAT}else this.type=l;const f=ts(this.type);u?(this._size=h||(n?n/f:Vi(s)),this.byteStride=n||this._buffer.byteStride||this._size*f,this.byteOffset=o||0):(this._size=h||n||Vi(s),this.byteStride=n?n*f:this._buffer.byteStride||this._size*f,this.byteOffset=(o||0)*f),this.normalized=c,this._instanced=void 0!==a&&a,this._instanceDivisor=a?d:0,this._alignBuffer(),this._computeHashCode()}static _GetTypeHashIndex(e){switch(e){case Gi.BYTE:return 0;case Gi.UNSIGNED_BYTE:return 1;case Gi.SHORT:return 2;case Gi.UNSIGNED_SHORT:return 3;case Gi.INT:return 4;case Gi.UNSIGNED_INT:return 5;case Gi.FLOAT:return 6;case Gi.HALF_FLOAT:return 7;default:throw new Error(`Invalid vertex buffer type '${e}'`)}}_computeHashCode(){this.hashCode=(Gi._GetTypeHashIndex(this.type)|0)+((this.normalized?1:0)<<3)+(this._size-1<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){this._buffer?._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const s=this.getData();return s?rs(s,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/ts(this.type)}getOffset(){return this.byteOffset/ts(this.type)}getSize(e=!1){return e?this._size*ts(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,s=!1){this._buffer.updateDirectly(e,t,void 0,s),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){is(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,(e,s)=>{for(let i=0;i<this._size;i++)t(e[i],s+i)})}_alignBuffer(){}}function Vi(e){switch(e){case Gi.UVKind:case Gi.UV2Kind:case Gi.UV3Kind:case Gi.UV4Kind:case Gi.UV5Kind:case Gi.UV6Kind:return 2;case Gi.NormalKind:case Gi.PositionKind:return 3;case Gi.ColorKind:case Gi.ColorInstanceKind:case Gi.MatricesIndicesKind:case Gi.MatricesIndicesExtraKind:case Gi.MatricesWeightsKind:case Gi.MatricesWeightsExtraKind:case Gi.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}function Hi(e){return e instanceof Int8Array?Gi.BYTE:e instanceof Uint8Array?Gi.UNSIGNED_BYTE:e instanceof Int16Array?Gi.SHORT:e instanceof Uint16Array?Gi.UNSIGNED_SHORT:e instanceof Int32Array?Gi.INT:e instanceof Uint32Array?Gi.UNSIGNED_INT:Gi.FLOAT}function zi(e){return ts(e)}function Wi(e,t,s,i,r,n,a,o){is(e,t,s,i,r,n,a,(e,t)=>{for(let s=0;s<i;s++)o(e[s],t+s)})}function Xi(e,t,s,i,r,n,a,o){return rs(e,t,s,i,r,n,a,o)}Gi._Counter=0,Gi.BYTE=dt.BYTE,Gi.UNSIGNED_BYTE=dt.UNSIGNED_BYTE,Gi.SHORT=dt.SHORT,Gi.UNSIGNED_SHORT=dt.UNSIGNED_SHORT,Gi.INT=dt.INT,Gi.UNSIGNED_INT=dt.UNSIGNED_INT,Gi.FLOAT=dt.FLOAT,Gi.HALF_FLOAT=dt.HALF_FLOAT,Gi.PositionKind=dt.PositionKind,Gi.NormalKind=dt.NormalKind,Gi.TangentKind=dt.TangentKind,Gi.UVKind=dt.UVKind,Gi.UV2Kind=dt.UV2Kind,Gi.UV3Kind=dt.UV3Kind,Gi.UV4Kind=dt.UV4Kind,Gi.UV5Kind=dt.UV5Kind,Gi.UV6Kind=dt.UV6Kind,Gi.ColorKind=dt.ColorKind,Gi.ColorInstanceKind=dt.ColorInstanceKind,Gi.MatricesIndicesKind=dt.MatricesIndicesKind,Gi.MatricesWeightsKind=dt.MatricesWeightsKind,Gi.MatricesIndicesExtraKind=dt.MatricesIndicesExtraKind,Gi.MatricesWeightsExtraKind=dt.MatricesWeightsExtraKind;let Ki=!1;function Yi(){Ki||(Ki=!0,Gi.DeduceStride=Vi,Gi.GetDataType=Hi,Gi.GetTypeByteLength=zi,Gi.ForEach=Wi,Gi.GetFloatData=Xi)}class ji{constructor(e,t,s){this.bu=e,this.bv=t,this.distance=s,this.faceId=0,this.subMeshId=0,this._internalSubMeshId=0}}class qi{constructor(e,t,s){this.vectors=q(8,xe.Zero),this.center=xe.Zero(),this.centerWorld=xe.Zero(),this.extendSize=xe.Zero(),this.extendSizeWorld=xe.Zero(),this.directions=q(3,xe.Zero),this.vectorsWorld=q(8,xe.Zero),this.minimumWorld=xe.Zero(),this.maximumWorld=xe.Zero(),this.minimum=xe.Zero(),this.maximum=xe.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,s)}reConstruct(e,t,s){const i=e.x,r=e.y,n=e.z,a=t.x,o=t.y,h=t.z,l=this.vectors;this.minimum.copyFromFloats(i,r,n),this.maximum.copyFromFloats(a,o,h),l[0].copyFromFloats(i,r,n),l[1].copyFromFloats(a,o,h),l[2].copyFromFloats(a,r,n),l[3].copyFromFloats(i,o,n),l[4].copyFromFloats(i,r,h),l[5].copyFromFloats(a,o,n),l[6].copyFromFloats(i,o,h),l[7].copyFromFloats(a,r,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=s||Ie.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=qi._TmpVector3,s=this.maximum.subtractToRef(this.minimum,t[0]),i=s.length();s.normalizeFromLength(i);const r=i*e,n=s.scaleInPlace(.5*r),a=this.center.subtractToRef(n,t[1]),o=this.center.addToRef(n,t[2]);return this.reConstruct(a,o,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,s=this.maximumWorld,i=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),s.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(n[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),s.setAll(-Number.MAX_VALUE);for(let i=0;i<8;++i){const a=r[i];xe.TransformCoordinatesToRef(n[i],e,a),t.minimizeInPlace(a),s.maximizeInPlace(a)}s.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),s.addToRef(t,this.centerWorld).scaleInPlace(.5)}xe.FromArrayToRef(e.m,0,i[0]),xe.FromArrayToRef(e.m,4,i[1]),xe.FromArrayToRef(e.m,8,i[2]),this._worldMatrix=e}isInFrustum(e){return qi.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return qi.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,s=this.maximumWorld,i=t.x,r=t.y,n=t.z,a=s.x,o=s.y,h=s.z,l=e.x,c=e.y,u=e.z,d=-.001;return!(a-l<d||d>l-i)&&(!(o-c<d||d>c-r)&&!(h-u<d||d>u-n))}intersectsSphere(e){return qi.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const s=this.minimumWorld,i=this.maximumWorld,r=s.x,n=s.y,a=s.z,o=i.x,h=i.y,l=i.z,c=e.x,u=e.y,d=e.z,_=t.x,p=t.y,f=t.z;return!(o<c||r>_)&&(!(h<u||n>p)&&!(l<d||a>f))}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,s,i){const r=qi._TmpVector3[0];xe.ClampToRef(s,e,t,r);return xe.DistanceSquared(s,r)<=i*i}static IsCompletelyInFrustum(e,t){for(let s=0;s<6;++s){const i=t[s];for(let t=0;t<8;++t)if(i.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let s=0;s<6;++s){let i=!0;const r=t[s];for(let t=0;t<8;++t)if(r.dotCoordinate(e[t])>=0){i=!1;break}if(i)return!1}return!0}}qi._TmpVector3=q(3,xe.Zero);class $i{constructor(e,t,s){this.center=xe.Zero(),this.centerWorld=xe.Zero(),this.minimum=xe.Zero(),this.maximum=xe.Zero(),this.reConstruct(e,t,s)}reConstruct(e,t,s){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const i=xe.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*i,this._update(s||Ie.IdentityReadOnly)}scale(e){const t=$i._TmpVector3,s=this.maximum.subtractToRef(this.minimum,t[0]),i=s.length();s.normalizeFromLength(i);const r=i*e,n=s.scaleInPlace(.5*r),a=this.center.subtractToRef(n,t[1]),o=this.center.addToRef(n,t[2]);return this.reConstruct(a,o,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{xe.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=$i._TmpVector3[0];xe.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,s=this.radiusWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<=-s)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let s=0;s<6;s++)if(e[s].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=xe.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld<t)}static Intersects(e,t){const s=xe.DistanceSquared(e.centerWorld,t.centerWorld),i=e.radiusWorld+t.radiusWorld;return!(i*i<s)}static CreateFromCenterAndRadius(e,t,s){this._TmpVector3[0].copyFrom(e),this._TmpVector3[1].copyFromFloats(0,0,t),this._TmpVector3[2].copyFrom(e),this._TmpVector3[0].addInPlace(this._TmpVector3[1]),this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);const i=new $i(this._TmpVector3[0],this._TmpVector3[2]);return i._worldMatrix=s||Ie.Identity(),i}}$i._TmpVector3=q(3,xe.Zero);const Zi={min:0,max:0},Qi={min:0,max:0},Ji=(e,t,s)=>{const i=xe.Dot(t.centerWorld,e),r=Math.abs(xe.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(xe.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(xe.Dot(t.directions[2],e))*t.extendSize.z;s.min=i-r,s.max=i+r},er=(e,t,s)=>(Ji(e,t,Zi),Ji(e,s,Qi),!(Zi.min>Qi.max||Qi.min>Zi.max));class tr{constructor(e,t,s){this._isLocked=!1,this.boundingBox=new qi(e,t,s),this.boundingSphere=new $i(e,t,s)}reConstruct(e,t,s){this.boundingBox.reConstruct(e,t,s),this.boundingSphere.reConstruct(e,t,s)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){const s=tr._TmpVector3[0].copyFrom(e).subtractInPlace(t),i=tr._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(s,i,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(s,i,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=xe.Minimize(this.minimum,e),s=xe.Maximize(this.maximum,e);return this.reConstruct(t,s,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=Ce.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const s=Ce.Vector3[0];return xe.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,s),this.encapsulate(s),xe.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,s),this.encapsulate(s),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=dt.MESHES_CULLINGSTRATEGY_STANDARD){if((t===dt.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION||t===dt.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY)&&this.boundingSphere.isCenterInFrustum(e))return!0;if(!this.boundingSphere.isInFrustum(e))return!1;return!(t!==dt.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY&&t!==dt.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY)||this.boundingBox.isInFrustum(e)}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,tr._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!!this.boundingSphere.centerWorld&&(!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e))}intersects(e,t){if(!$i.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!qi.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const s=this.boundingBox,i=e.boundingBox;return!!er(s.directions[0],s,i)&&(!!er(s.directions[1],s,i)&&(!!er(s.directions[2],s,i)&&(!!er(i.directions[0],s,i)&&(!!er(i.directions[1],s,i)&&(!!er(i.directions[2],s,i)&&(!!er(xe.Cross(s.directions[0],i.directions[0]),s,i)&&(!!er(xe.Cross(s.directions[0],i.directions[1]),s,i)&&(!!er(xe.Cross(s.directions[0],i.directions[2]),s,i)&&(!!er(xe.Cross(s.directions[1],i.directions[0]),s,i)&&(!!er(xe.Cross(s.directions[1],i.directions[1]),s,i)&&(!!er(xe.Cross(s.directions[1],i.directions[2]),s,i)&&(!!er(xe.Cross(s.directions[2],i.directions[0]),s,i)&&(!!er(xe.Cross(s.directions[2],i.directions[1]),s,i)&&!!er(xe.Cross(s.directions[2],i.directions[2]),s,i))))))))))))))}}tr._TmpVector3=q(2,xe.Zero);let sr=(()=>{var e;let t,s,i=[];return e=class{static extractMinAndMaxIndexed(e,t,s,i,r,n){for(let a=s;a<s+i;a++){const s=3*t[a],i=e[s],o=e[s+1],h=e[s+2];r.minimizeInPlaceFromFloats(i,o,h),n.maximizeInPlaceFromFloats(i,o,h)}}static extractMinAndMax(e,t,s,i,r,n){for(let a=t,o=t*i;a<t+s;a++,o+=i){const t=e[o],s=e[o+1],i=e[o+2];r.minimizeInPlaceFromFloats(t,s,i),n.maximizeInPlaceFromFloats(t,s,i)}}},(()=>{const r="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[W.filter((...e)=>!Array.isArray(e[0])&&!Array.isArray(e[1]))],s=[W.filter((...e)=>!Array.isArray(e[0]))],b(e,null,t,{kind:"method",name:"extractMinAndMaxIndexed",static:!0,private:!1,access:{has:e=>"extractMinAndMaxIndexed"in e,get:e=>e.extractMinAndMaxIndexed},metadata:r},null,i),b(e,null,s,{kind:"method",name:"extractMinAndMax",static:!0,private:!1,access:{has:e=>"extractMinAndMax"in e,get:e=>e.extractMinAndMax},metadata:r},null,i),r&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:r}),A(e,i)})(),e})();function ir(e,t,s,i=null,r){const n=new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new xe(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return r||(r=3),sr.extractMinAndMax(e,t,s,r,n,a),i&&(n.x-=n.x*i.x+i.y,n.y-=n.y*i.x+i.y,n.z-=n.z*i.x+i.y,a.x+=a.x*i.x+i.y,a.y+=a.y*i.x+i.y,a.z+=a.z*i.x+i.y),{minimum:n,maximum:a}}class rr{static GetEffect(e){return void 0===e.getPipelineContext?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,s=!0){this.effect=e,void 0!==t&&(this.defines=t),s&&this.drawContext?.reset()}dispose(e=!1){if(this.effect){const t=this.effect;e?t.dispose():Xt.SetImmediate(()=>{t.getEngine().onEndFrameObservable.addOnce(()=>{t.dispose()})}),this.effect=null}this.drawContext?.dispose()}}class nr{get materialDefines(){const e=this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:this._getDrawWrapper()?.defines;return"string"==typeof e?null:e}set materialDefines(e){(this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let s=this._drawWrappers[e];return!s&&t&&(this._drawWrappers[e]=s=new rr(this._mesh.getScene().getEngine())),s}_removeDrawWrapper(e,t=!0,s=!1){t&&this._drawWrappers[e]?.dispose(s),this._drawWrappers[e]=void 0}get effect(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:this._getDrawWrapper()?.effect??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,s,i=!0){const r=this._drawWrapper;r.setEffect(e,t,i),void 0!==s&&(r.materialContext=s),e||(r.defines=null,r.materialContext=void 0)}resetDrawCache(e,t=!1){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e,!0,t);for(const e of this._drawWrappers)e?.dispose(t)}this._drawWrappers=[]}static AddToMesh(e,t,s,i,r,n,a,o=!0){return new nr(e,t,s,i,r,n,a,o)}constructor(e,t,s,i,r,n,a,o=!0,h=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=s,this.indexStart=i,this.indexCount=r,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=a||n,h&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,o&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){const e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(!t)return e&&this._mesh.getScene()._hasDefaultMaterial?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(t)){const e=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return t}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(Gi.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let s;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();s={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else s=function(e,t,s,i,r=null){const n=new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new xe(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return sr.extractMinAndMaxIndexed(e,t,s,i,n,a),r&&(n.x-=n.x*r.x+r.y,n.y-=n.y*r.x+r.y,n.z-=n.z*r.x+r.y,a.x+=a.x*r.x+r.y,a.y+=a.y*r.x+r.y,a.z+=a.z*r.x+r.y),{minimum:n,maximum:a}}(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(s.minimum,s.maximum):this._boundingInfo=new tr(s.minimum,s.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const s=6*Math.floor(this.indexCount/3),i=this.verticesStart+this.verticesCount>65535?new Uint32Array(s):new Uint16Array(s);let r=0;if(0===e.length)for(let e=this.indexStart;e<this.indexStart+this.indexCount;e+=3)i[r++]=e,i[r++]=e+1,i[r++]=e+1,i[r++]=e+2,i[r++]=e+2,i[r++]=e;else for(let t=this.indexStart;t<this.indexStart+this.indexCount;t+=3)i[r++]=e[t],i[r++]=e[t+1],i[r++]=e[t+1],i[r++]=e[t+2],i[r++]=e[t+2],i[r++]=e[t];this._linesIndexBuffer=t.createIndexBuffer(i),this._linesIndexCount=i.length}return this._linesIndexBuffer}canIntersects(e){const t=this.getBoundingInfo();return!!t&&e.intersectsBox(t.boundingBox)}intersects(e,t,s,i,r){const n=this.getMaterial();if(!n)return null;let a=3,o=!1;switch(n.fillMode){case dt.MATERIAL_PointListDrawMode:case dt.MATERIAL_LineLoopDrawMode:case dt.MATERIAL_LineStripDrawMode:case dt.MATERIAL_TriangleFanDrawMode:return null;case dt.MATERIAL_TriangleStripDrawMode:a=1,o=!0}return n.fillMode===dt.MATERIAL_LineListDrawMode?s.length?this._intersectLines(e,t,s,this._mesh.intersectionThreshold,i):this._intersectUnIndexedLines(e,t,s,this._mesh.intersectionThreshold,i):!s.length&&this._mesh._unIndexed?this._intersectUnIndexedTriangles(e,t,s,i,r):this._intersectTriangles(e,t,s,a,o,i,r)}_intersectLines(e,t,s,i,r){let n=null;for(let a=this.indexStart;a<this.indexStart+this.indexCount;a+=2){const o=t[s[a]],h=t[s[a+1]],l=e.intersectionSegment(o,h,i);if(!(l<0)&&((r||!n||l<n.distance)&&(n=new ji(null,null,l),n.faceId=a/2,r)))break}return n}_intersectUnIndexedLines(e,t,s,i,r){let n=null;for(let s=this.verticesStart;s<this.verticesStart+this.verticesCount;s+=2){const a=t[s],o=t[s+1],h=e.intersectionSegment(a,o,i);if(!(h<0)&&((r||!n||h<n.distance)&&(n=new ji(null,null,h),n.faceId=s/2,r)))break}return n}_intersectTriangles(e,t,s,i,r,n,a){let o=null,h=-1;for(let l=this.indexStart;l<this.indexStart+this.indexCount-(3-i);l+=i){h++;const i=s[l],c=s[l+1],u=s[l+2];if(r&&4294967295===u){l+=2;continue}const d=t[i],_=t[c],p=t[u];if(!d||!_||!p)continue;if(a&&!a(d,_,p,e,i,c,u))continue;const f=e.intersectsTriangle(d,_,p);if(f){if(f.distance<0)continue;if((n||!o||f.distance<o.distance)&&(o=f,o.faceId=h,n))break}}return o}_intersectUnIndexedTriangles(e,t,s,i,r){let n=null;for(let s=this.verticesStart;s<this.verticesStart+this.verticesCount;s+=3){const a=t[s],o=t[s+1],h=t[s+2];if(r&&!r(a,o,h,e,-1,-1,-1))continue;const l=e.intersectsTriangle(a,o,h);if(l){if(l.distance<0)continue;if((i||!n||l.distance<n.distance)&&(n=l,n.faceId=s/3,i))break}}return n}_rebuild(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)}clone(e,t){const s=new nr(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,e,t,!1);if(!this.IsGlobal){const e=this.getBoundingInfo();if(!e)return s;s._boundingInfo=new tr(e.minimum,e.maximum)}return s}dispose(e=!1){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);const t=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(t,1),this.resetDrawCache(void 0,e)}getClassName(){return"SubMesh"}static CreateFromIndices(e,t,s,i,r,n=!0){let a=Number.MAX_VALUE,o=-Number.MAX_VALUE;const h=(r||i).getIndices();for(let e=t;e<t+s;e++){const t=h[e];t<a&&(a=t),t>o&&(o=t)}return new nr(e,a,o-a+1,t,s,i,r,n)}}nr.prototype.projectToRef??=Ne("SubMesh","projectToRef");class ar{}let or=(()=>{var e;let i,r,n,o,h=[];return e=class{constructor(){var t;this.uniqueId=0,this.metadata={},this._applyTo=(t=this._applyToCoroutine.bind(this),(...e)=>Hs(t(...e))),this.uniqueId=e._UniqueIdGenerator,e._UniqueIdGenerator++}set(e,t){switch(e.length||a.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case Gi.PositionKind:this.positions=e;break;case Gi.NormalKind:this.normals=e;break;case Gi.TangentKind:this.tangents=e;break;case Gi.UVKind:this.uvs=e;break;case Gi.UV2Kind:this.uvs2=e;break;case Gi.UV3Kind:this.uvs3=e;break;case Gi.UV4Kind:this.uvs4=e;break;case Gi.UV5Kind:this.uvs5=e;break;case Gi.UV6Kind:this.uvs6=e;break;case Gi.ColorKind:this.colors=e;break;case Gi.MatricesIndicesKind:this.matricesIndices=e;break;case Gi.MatricesWeightsKind:this.matricesWeights=e;break;case Gi.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case Gi.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,s){if(this.positions&&(e.setVerticesData(Gi.PositionKind,this.positions,t),s&&(yield)),this.normals&&(e.setVerticesData(Gi.NormalKind,this.normals,t),s&&(yield)),this.tangents&&(e.setVerticesData(Gi.TangentKind,this.tangents,t),s&&(yield)),this.uvs&&(e.setVerticesData(Gi.UVKind,this.uvs,t),s&&(yield)),this.uvs2&&(e.setVerticesData(Gi.UV2Kind,this.uvs2,t),s&&(yield)),this.uvs3&&(e.setVerticesData(Gi.UV3Kind,this.uvs3,t),s&&(yield)),this.uvs4&&(e.setVerticesData(Gi.UV4Kind,this.uvs4,t),s&&(yield)),this.uvs5&&(e.setVerticesData(Gi.UV5Kind,this.uvs5,t),s&&(yield)),this.uvs6&&(e.setVerticesData(Gi.UV6Kind,this.uvs6,t),s&&(yield)),this.colors){const i=this.positions&&this.colors.length===this.positions.length?3:4;e.setVerticesData(Gi.ColorKind,this.colors,t,i),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),s&&(yield)}if(this.matricesIndices&&(e.setVerticesData(Gi.MatricesIndicesKind,this.matricesIndices,t),s&&(yield)),this.matricesWeights&&(e.setVerticesData(Gi.MatricesWeightsKind,this.matricesWeights,t),s&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(Gi.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),s&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(Gi.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),s&&(yield)),this.indices?(e.setIndices(this.indices,null,t),s&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const t=e;t.subMeshes=[];for(const e of this.materialInfos)new nr(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,t)}return this}_update(e,t,s){return this.positions&&e.updateVerticesData(Gi.PositionKind,this.positions,t,s),this.normals&&e.updateVerticesData(Gi.NormalKind,this.normals,t,s),this.tangents&&e.updateVerticesData(Gi.TangentKind,this.tangents,t,s),this.uvs&&e.updateVerticesData(Gi.UVKind,this.uvs,t,s),this.uvs2&&e.updateVerticesData(Gi.UV2Kind,this.uvs2,t,s),this.uvs3&&e.updateVerticesData(Gi.UV3Kind,this.uvs3,t,s),this.uvs4&&e.updateVerticesData(Gi.UV4Kind,this.uvs4,t,s),this.uvs5&&e.updateVerticesData(Gi.UV5Kind,this.uvs5,t,s),this.uvs6&&e.updateVerticesData(Gi.UV6Kind,this.uvs6,t,s),this.colors&&e.updateVerticesData(Gi.ColorKind,this.colors,t,s),this.matricesIndices&&e.updateVerticesData(Gi.MatricesIndicesKind,this.matricesIndices,t,s),this.matricesWeights&&e.updateVerticesData(Gi.MatricesWeightsKind,this.matricesWeights,t,s),this.matricesIndicesExtra&&e.updateVerticesData(Gi.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,s),this.matricesWeightsExtra&&e.updateVerticesData(Gi.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,s),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,s=0,i=e.length){const r=Ce.Vector3[0],n=Ce.Vector3[1];for(let a=s;a<s+i;a+=3)xe.FromArrayToRef(e,a,r),xe.TransformCoordinatesToRef(r,t,n),e[a]=n.x,e[a+1]=n.y,e[a+2]=n.z}static _TransformVector3Normals(e,t,s=0,i=e.length){const r=Ce.Vector3[0],n=Ce.Vector3[1];for(let a=s;a<s+i;a+=3)xe.FromArrayToRef(e,a,r),xe.TransformNormalToRef(r,t,n),e[a]=n.x,e[a+1]=n.y,e[a+2]=n.z}static _TransformVector4Normals(e,t,s=0,i=e.length){const r=Ce.Vector4[0],n=Ce.Vector4[1];for(let a=s;a<s+i;a+=4)Se.FromArrayToRef(e,a,r),Se.TransformNormalToRef(r,t,n),e[a]=n.x,e[a+1]=n.y,e[a+2]=n.z,e[a+3]=n.w}static _FlipFaces(e,t=0,s=e.length){for(let i=t;i<t+s;i+=3){const t=e[i+1];e[i+1]=e[i+2],e[i+2]=t}}transform(t){const s=t.determinant()<0;return this.positions&&e._TransformVector3Coordinates(this.positions,t),this.normals&&e._TransformVector3Normals(this.normals,t),this.tangents&&e._TransformVector4Normals(this.tangents,t),s&&this.indices&&e._FlipFaces(this.indices),this}splitBasedOnMaterialID(){if(!this.materialInfos||this.materialInfos.length<2)return[this];const t=[];for(const s of this.materialInfos){const i=new e;if(this.positions&&(i.positions=this.positions.slice(3*s.verticesStart,3*(s.verticesCount+s.verticesStart))),this.normals&&(i.normals=this.normals.slice(3*s.verticesStart,3*(s.verticesCount+s.verticesStart))),this.tangents&&(i.tangents=this.tangents.slice(4*s.verticesStart,4*(s.verticesCount+s.verticesStart))),this.colors&&(i.colors=this.colors.slice(4*s.verticesStart,4*(s.verticesCount+s.verticesStart))),this.uvs&&(i.uvs=this.uvs.slice(2*s.verticesStart,2*(s.verticesCount+s.verticesStart))),this.uvs2&&(i.uvs2=this.uvs2.slice(2*s.verticesStart,2*(s.verticesCount+s.verticesStart))),this.uvs3&&(i.uvs3=this.uvs3.slice(2*s.verticesStart,2*(s.verticesCount+s.verticesStart))),this.uvs4&&(i.uvs4=this.uvs4.slice(2*s.verticesStart,2*(s.verticesCount+s.verticesStart))),this.uvs5&&(i.uvs5=this.uvs5.slice(2*s.verticesStart,2*(s.verticesCount+s.verticesStart))),this.uvs6&&(i.uvs6=this.uvs6.slice(2*s.verticesStart,2*(s.verticesCount+s.verticesStart))),this.matricesIndices&&(i.matricesIndices=this.matricesIndices.slice(4*s.verticesStart,4*(s.verticesCount+s.verticesStart))),this.matricesIndicesExtra&&(i.matricesIndicesExtra=this.matricesIndicesExtra.slice(4*s.verticesStart,4*(s.verticesCount+s.verticesStart))),this.matricesWeights&&(i.matricesWeights=this.matricesWeights.slice(4*s.verticesStart,4*(s.verticesCount+s.verticesStart))),this.matricesWeightsExtra&&(i.matricesWeightsExtra=this.matricesWeightsExtra.slice(4*s.verticesStart,4*(s.verticesCount+s.verticesStart))),this.indices){i.indices=[];for(let e=s.indexStart;e<s.indexStart+s.indexCount;e++)i.indices.push(this.indices[e]-s.verticesStart)}const r=new ar;r.indexStart=0,r.indexCount=i.indices?i.indices.length:0,r.materialIndex=s.materialIndex,r.verticesStart=0,r.verticesCount=(i.positions?i.positions.length:0)/3,i.materialInfos=[r],t.push(i)}return t}merge(e,t=!1,s=!1,i=!1,r=!1){const n=Array.isArray(e)?e.map(e=>({vertexData:e})):[{vertexData:e}];return Hs(this._mergeCoroutine(void 0,n,t,!1,s,i,r))}*_mergeCoroutine(t,s,i=!1,r,n,a=!1,o=!1){this._validate();let h=s.map(e=>e.vertexData),l=this;if(o)for(const e of h)e&&(e._validate(),!this.normals&&e.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&e.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&e.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&e.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&e.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&e.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&e.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&e.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&e.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&e.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&e.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&e.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&e.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const e of h)if(e)if(o)this.normals&&!e.normals&&(e.normals=new Float32Array(e.positions.length)),this.tangents&&!e.tangents&&(e.tangents=new Float32Array(e.positions.length/3*4)),this.uvs&&!e.uvs&&(e.uvs=new Float32Array(e.positions.length/3*2)),this.uvs2&&!e.uvs2&&(e.uvs2=new Float32Array(e.positions.length/3*2)),this.uvs3&&!e.uvs3&&(e.uvs3=new Float32Array(e.positions.length/3*2)),this.uvs4&&!e.uvs4&&(e.uvs4=new Float32Array(e.positions.length/3*2)),this.uvs5&&!e.uvs5&&(e.uvs5=new Float32Array(e.positions.length/3*2)),this.uvs6&&!e.uvs6&&(e.uvs6=new Float32Array(e.positions.length/3*2)),this.colors&&!e.colors&&(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)),this.matricesIndices&&!e.matricesIndices&&(e.matricesIndices=new Float32Array(e.positions.length/3*4)),this.matricesWeights&&!e.matricesWeights&&(e.matricesWeights=new Float32Array(e.positions.length/3*4)),this.matricesIndicesExtra&&!e.matricesIndicesExtra&&(e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4)),this.matricesWeightsExtra&&!e.matricesWeightsExtra&&(e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4));else if(e._validate(),!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(a){let e,i=0,r=0;const n=[];let a=null;const o=[];for(const e of this.splitBasedOnMaterialID())o.push({vertexData:e,transform:t});for(const e of s)if(e.vertexData)for(const t of e.vertexData.splitBasedOnMaterialID())o.push({vertexData:t,transform:e.transform});o.sort((e,t)=>{const s=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,i=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return s>i?1:s===i?0:-1});for(const t of o){const s=t.vertexData;if(e=s.materialInfos?s.materialInfos[0].materialIndex:0,a&&a.materialIndex===e)a.indexCount+=s.indices.length,a.verticesCount+=s.positions.length/3;else{const t=new ar;t.materialIndex=e,t.indexStart=i,t.indexCount=s.indices.length,t.verticesStart=r,t.verticesCount=s.positions.length/3,n.push(t),a=t}i+=s.indices.length,r+=s.positions.length/3}const c=o.splice(0,1)[0];l=c.vertexData,t=c.transform,h=o.map(e=>e.vertexData),s=o,this.materialInfos=n}const c=h.reduce((e,t)=>e+(t.indices?.length??0),l.indices?.length??0);let u=n||h.some(e=>e.indices===l.indices)?l.indices?.slice():l.indices;if(c>0){let n=u?.length??0;if(u||(u=new Array(c)),u.length!==c){if(Array.isArray(u))u.length=c;else{const e=i||u instanceof Uint32Array?new Uint32Array(c):new Uint16Array(c);e.set(u),u=e}t&&t.determinant()<0&&e._FlipFaces(u,0,n)}let a=l.positions?l.positions.length/3:0;for(const{vertexData:t,transform:i}of s)if(t.indices){for(let e=0;e<t.indices.length;e++)u[n+e]=t.indices[e]+a;i&&i.determinant()<0&&e._FlipFaces(u,n,t.indices.length),a+=t.positions.length/3,n+=t.indices.length,r&&(yield)}}return this.indices=u,this.positions=e._MergeElement(Gi.PositionKind,l.positions,t,s.map(e=>[e.vertexData.positions,e.transform])),r&&(yield),l.normals&&(this.normals=e._MergeElement(Gi.NormalKind,l.normals,t,s.map(e=>[e.vertexData.normals,e.transform])),r&&(yield)),l.tangents&&(this.tangents=e._MergeElement(Gi.TangentKind,l.tangents,t,s.map(e=>[e.vertexData.tangents,e.transform])),r&&(yield)),l.uvs&&(this.uvs=e._MergeElement(Gi.UVKind,l.uvs,t,s.map(e=>[e.vertexData.uvs,e.transform])),r&&(yield)),l.uvs2&&(this.uvs2=e._MergeElement(Gi.UV2Kind,l.uvs2,t,s.map(e=>[e.vertexData.uvs2,e.transform])),r&&(yield)),l.uvs3&&(this.uvs3=e._MergeElement(Gi.UV3Kind,l.uvs3,t,s.map(e=>[e.vertexData.uvs3,e.transform])),r&&(yield)),l.uvs4&&(this.uvs4=e._MergeElement(Gi.UV4Kind,l.uvs4,t,s.map(e=>[e.vertexData.uvs4,e.transform])),r&&(yield)),l.uvs5&&(this.uvs5=e._MergeElement(Gi.UV5Kind,l.uvs5,t,s.map(e=>[e.vertexData.uvs5,e.transform])),r&&(yield)),l.uvs6&&(this.uvs6=e._MergeElement(Gi.UV6Kind,l.uvs6,t,s.map(e=>[e.vertexData.uvs6,e.transform])),r&&(yield)),l.colors&&(this.colors=e._MergeElement(Gi.ColorKind,l.colors,t,s.map(e=>[e.vertexData.colors,e.transform])),(void 0!==l.hasVertexAlpha||s.some(e=>void 0!==e.vertexData.hasVertexAlpha))&&(this.hasVertexAlpha=l.hasVertexAlpha||s.some(e=>e.vertexData.hasVertexAlpha)),r&&(yield)),l.matricesIndices&&(this.matricesIndices=e._MergeElement(Gi.MatricesIndicesKind,l.matricesIndices,t,s.map(e=>[e.vertexData.matricesIndices,e.transform])),r&&(yield)),l.matricesWeights&&(this.matricesWeights=e._MergeElement(Gi.MatricesWeightsKind,l.matricesWeights,t,s.map(e=>[e.vertexData.matricesWeights,e.transform])),r&&(yield)),l.matricesIndicesExtra&&(this.matricesIndicesExtra=e._MergeElement(Gi.MatricesIndicesExtraKind,l.matricesIndicesExtra,t,s.map(e=>[e.vertexData.matricesIndicesExtra,e.transform])),r&&(yield)),l.matricesWeightsExtra&&(this.matricesWeightsExtra=e._MergeElement(Gi.MatricesWeightsExtraKind,l.matricesWeightsExtra,t,s.map(e=>[e.vertexData.matricesWeightsExtra,e.transform]))),this}static _MergeElement(t,s,i,r){const n=r.filter(e=>null!==e[0]&&void 0!==e[0]);if(!s&&0==n.length)return s;if(!s)return this._MergeElement(t,n[0][0],n[0][1],n.slice(1));const a=n.reduce((e,t)=>e+t[0].length,s.length),o=t===Gi.PositionKind?e._TransformVector3Coordinates:t===Gi.NormalKind?e._TransformVector3Normals:t===Gi.TangentKind?e._TransformVector4Normals:()=>{};if(s instanceof Float32Array){const e=new Float32Array(a);e.set(s),i&&o(e,i,0,s.length);let t=s.length;for(const[s,i]of n)e.set(s,t),i&&o(e,i,t,s.length),t+=s.length;return e}{const e=new Array(a);for(let t=0;t<s.length;t++)e[t]=s[t];i&&o(e,i,0,s.length);let t=s.length;for(const[s,i]of n){for(let i=0;i<s.length;i++)e[t+i]=s[i];i&&o(e,i,t,s.length),t+=s.length}return e}}_validate(){if(!this.positions)throw new s("Positions are required",t.MeshInvalidPositionsError);const e=(e,t)=>{const s=Vi(e);if(t.length%s!==0)throw new Error("The "+e+"s array count must be a multiple of "+s);return t.length/s},i=e(Gi.PositionKind,this.positions),r=(t,s)=>{const r=e(t,s);if(r!==i)throw new Error("The "+t+"s element count ("+r+") does not match the positions count ("+i+")")};this.normals&&r(Gi.NormalKind,this.normals),this.tangents&&r(Gi.TangentKind,this.tangents),this.uvs&&r(Gi.UVKind,this.uvs),this.uvs2&&r(Gi.UV2Kind,this.uvs2),this.uvs3&&r(Gi.UV3Kind,this.uvs3),this.uvs4&&r(Gi.UV4Kind,this.uvs4),this.uvs5&&r(Gi.UV5Kind,this.uvs5),this.uvs6&&r(Gi.UV6Kind,this.uvs6),this.colors&&r(Gi.ColorKind,this.colors),this.matricesIndices&&r(Gi.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&r(Gi.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&r(Gi.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&r(Gi.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const t=this.serialize();return e.Parse(t)}serialize(){const e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndicesExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtraExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=this.indices?Array.from(this.indices):[],this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const s={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(s)}}return e}static ExtractFromMesh(t,s,i){return e._ExtractFrom(t,s,i)}static ExtractFromGeometry(t,s,i){return e._ExtractFrom(t,s,i)}static _ExtractFrom(t,s,i){const r=new e;if(t.isVerticesDataPresent(Gi.PositionKind)&&(r.positions=t.getVerticesData(Gi.PositionKind,s,i)),t.isVerticesDataPresent(Gi.NormalKind)&&(r.normals=t.getVerticesData(Gi.NormalKind,s,i)),t.isVerticesDataPresent(Gi.TangentKind)&&(r.tangents=t.getVerticesData(Gi.TangentKind,s,i)),t.isVerticesDataPresent(Gi.UVKind)&&(r.uvs=t.getVerticesData(Gi.UVKind,s,i)),t.isVerticesDataPresent(Gi.UV2Kind)&&(r.uvs2=t.getVerticesData(Gi.UV2Kind,s,i)),t.isVerticesDataPresent(Gi.UV3Kind)&&(r.uvs3=t.getVerticesData(Gi.UV3Kind,s,i)),t.isVerticesDataPresent(Gi.UV4Kind)&&(r.uvs4=t.getVerticesData(Gi.UV4Kind,s,i)),t.isVerticesDataPresent(Gi.UV5Kind)&&(r.uvs5=t.getVerticesData(Gi.UV5Kind,s,i)),t.isVerticesDataPresent(Gi.UV6Kind)&&(r.uvs6=t.getVerticesData(Gi.UV6Kind,s,i)),t.isVerticesDataPresent(Gi.ColorKind)){const e=t.geometry||t,n=e.getVertexBuffer(Gi.ColorKind),a=e.getVerticesData(Gi.ColorKind,s,i);if(3===n.getSize()){const e=new Float32Array(4*a.length/3);for(let t=0,s=0;t<a.length;t+=3,s+=4)e[s]=a[t],e[s+1]=a[t+1],e[s+2]=a[t+2],e[s+3]=1;r.colors=e}else{if(4!==n.getSize())throw new Error(`Unexpected number of color components: ${n.getSize()}`);r.colors=a}}return t.isVerticesDataPresent(Gi.MatricesIndicesKind)&&(r.matricesIndices=t.getVerticesData(Gi.MatricesIndicesKind,s,i)),t.isVerticesDataPresent(Gi.MatricesWeightsKind)&&(r.matricesWeights=t.getVerticesData(Gi.MatricesWeightsKind,s,i)),t.isVerticesDataPresent(Gi.MatricesIndicesExtraKind)&&(r.matricesIndicesExtra=t.getVerticesData(Gi.MatricesIndicesExtraKind,s,i)),t.isVerticesDataPresent(Gi.MatricesWeightsExtraKind)&&(r.matricesWeightsExtra=t.getVerticesData(Gi.MatricesWeightsExtraKind,s,i)),r.indices=t.getIndices(s,i),r}static CreateRibbon(e){throw Le("ribbonBuilder")}static CreateBox(e){throw Le("boxBuilder")}static CreateTiledBox(e){throw Le("tiledBoxBuilder")}static CreateTiledPlane(e){throw Le("tiledPlaneBuilder")}static CreateSphere(e){throw Le("sphereBuilder")}static CreateCylinder(e){throw Le("cylinderBuilder")}static CreateTorus(e){throw Le("torusBuilder")}static CreateLineSystem(e){throw Le("linesBuilder")}static CreateDashedLines(e){throw Le("linesBuilder")}static CreateGround(e){throw Le("groundBuilder")}static CreateTiledGround(e){throw Le("groundBuilder")}static CreateGroundFromHeightMap(e){throw Le("groundBuilder")}static CreatePlane(e){throw Le("planeBuilder")}static CreateDisc(e){throw Le("discBuilder")}static CreatePolygon(e,t,s,i,r,n,a){throw Le("polygonBuilder")}static CreateIcoSphere(e){throw Le("icoSphereBuilder")}static CreatePolyhedron(e){throw Le("polyhedronBuilder")}static CreateCapsule(e={orientation:xe.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw Le("capsuleBuilder")}static CreateTorusKnot(e){throw Le("torusKnotBuilder")}static ComputeNormals(e,t,s,i){let r,n,a,o,h,l,c,u,d,_,p,f,g,m,T,E,R,b,A,y,M=!1,x=!1,S=!1,v=!1,I=1,P=0,C=null;i&&(M=!!i.facetNormals,x=!!i.facetPositions,S=!!i.facetPartitioning,I=!0===i.useRightHandedSystem?-1:1,P=i.ratio||0,v=!!i.depthSort,C=i.distanceTo,v&&void 0===C&&(C=xe.Zero()));let O=0,D=0,w=0,L=0;for(S&&i&&i.bbSize&&(O=i.subDiv.X*P/i.bbSize.x,D=i.subDiv.Y*P/i.bbSize.y,w=i.subDiv.Z*P/i.bbSize.z,L=i.subDiv.max*i.subDiv.max,i.facetPartitioning.length=0),r=0;r<e.length;r++)s[r]=0;const F=t.length/3|0;for(r=0;r<F;r++){if(f=3*t[3*r],g=f+1,m=f+2,T=3*t[3*r+1],E=T+1,R=T+2,b=3*t[3*r+2],A=b+1,y=b+2,n=e[f]-e[T],a=e[g]-e[E],o=e[m]-e[R],h=e[b]-e[T],l=e[A]-e[E],c=e[y]-e[R],u=I*(a*c-o*l),d=I*(o*h-n*c),_=I*(n*l-a*h),p=Math.sqrt(u*u+d*d+_*_),p=0===p?1:p,u/=p,d/=p,_/=p,M&&i&&(i.facetNormals[r].x=u,i.facetNormals[r].y=d,i.facetNormals[r].z=_),x&&i&&(i.facetPositions[r].x=(e[f]+e[T]+e[b])/3,i.facetPositions[r].y=(e[g]+e[E]+e[A])/3,i.facetPositions[r].z=(e[m]+e[R]+e[y])/3),S&&i){const t=Math.floor((i.facetPositions[r].x-i.bInfo.minimum.x*P)*O),s=Math.floor((i.facetPositions[r].y-i.bInfo.minimum.y*P)*D),n=Math.floor((i.facetPositions[r].z-i.bInfo.minimum.z*P)*w),a=Math.floor((e[f]-i.bInfo.minimum.x*P)*O),o=Math.floor((e[g]-i.bInfo.minimum.y*P)*D),h=Math.floor((e[m]-i.bInfo.minimum.z*P)*w),l=Math.floor((e[T]-i.bInfo.minimum.x*P)*O),c=Math.floor((e[E]-i.bInfo.minimum.y*P)*D),u=Math.floor((e[R]-i.bInfo.minimum.z*P)*w),d=Math.floor((e[b]-i.bInfo.minimum.x*P)*O),_=Math.floor((e[A]-i.bInfo.minimum.y*P)*D),p=Math.floor((e[y]-i.bInfo.minimum.z*P)*w),M=a+i.subDiv.max*o+L*h,x=l+i.subDiv.max*c+L*u,S=d+i.subDiv.max*_+L*p,v=t+i.subDiv.max*s+L*n;i.facetPartitioning[v]=i.facetPartitioning[v]?i.facetPartitioning[v]:[],i.facetPartitioning[M]=i.facetPartitioning[M]?i.facetPartitioning[M]:[],i.facetPartitioning[x]=i.facetPartitioning[x]?i.facetPartitioning[x]:[],i.facetPartitioning[S]=i.facetPartitioning[S]?i.facetPartitioning[S]:[],i.facetPartitioning[M].push(r),x!=M&&i.facetPartitioning[x].push(r),S!=x&&S!=M&&i.facetPartitioning[S].push(r),v!=M&&v!=x&&v!=S&&i.facetPartitioning[v].push(r)}if(v&&i&&i.facetPositions){const e=i.depthSortedFacets[r];e.ind=3*r,e.sqDistance=xe.DistanceSquared(i.facetPositions[r],C)}s[f]+=u,s[g]+=d,s[m]+=_,s[T]+=u,s[E]+=d,s[R]+=_,s[b]+=u,s[A]+=d,s[y]+=_}for(r=0;r<s.length/3;r++)u=s[3*r],d=s[3*r+1],_=s[3*r+2],p=Math.sqrt(u*u+d*d+_*_),p=0===p?1:p,u/=p,d/=p,_/=p,s[3*r]=u,s[3*r+1]=d,s[3*r+2]=_}static _ComputeSides(t,s,i,r,n,a,o){const h=i.length,l=r.length;let c,u;switch(t=t||e.DEFAULTSIDE){case e.FRONTSIDE:break;case e.BACKSIDE:for(c=0;c<h;c+=3){const e=i[c];i[c]=i[c+2],i[c+2]=e}for(u=0;u<l;u++)r[u]=-r[u];break;case e.DOUBLESIDE:{const e=s.length,t=e/3;for(let t=0;t<e;t++)s[e+t]=s[t];for(c=0;c<h;c+=3)i[c+h]=i[c+2]+t,i[c+1+h]=i[c+1]+t,i[c+2+h]=i[c]+t;for(u=0;u<l;u++)r[l+u]=-r[u];const d=n.length;let _;for(_=0;_<d;_++)n[_+d]=n[_];for(a=a||new Se(0,0,1,1),o=o||new Se(0,0,1,1),_=0,c=0;c<d/2;c++)n[_]=a.x+(a.z-a.x)*n[_],n[_+1]=a.y+(a.w-a.y)*n[_+1],n[_+d]=o.x+(o.z-o.x)*n[_+d],n[_+d+1]=o.y+(o.w-o.y)*n[_+d+1],_+=2;break}}}static Parse(t){const s=new e,i=t.positions;i&&s.set(i,Gi.PositionKind);const r=t.normals;r&&s.set(r,Gi.NormalKind);const n=t.tangents;n&&s.set(n,Gi.TangentKind);const a=t.uvs;a&&s.set(a,Gi.UVKind);const o=t.uvs2;o&&s.set(o,Gi.UV2Kind);const h=t.uvs3;h&&s.set(h,Gi.UV3Kind);const l=t.uvs4;l&&s.set(l,Gi.UV4Kind);const c=t.uvs5;c&&s.set(c,Gi.UV5Kind);const u=t.uvs6;u&&s.set(u,Gi.UV6Kind);const d=t.colors;d&&(s.set(Ke.CheckColors4(d,i.length/3),Gi.ColorKind),void 0!==t.hasVertexAlpha&&(s.hasVertexAlpha=t.hasVertexAlpha));const _=t.matricesIndices;_&&s.set(_,Gi.MatricesIndicesKind);const p=t.matricesWeights;p&&s.set(p,Gi.MatricesWeightsKind);const f=t.indices;f&&(s.indices=f);const g=t.materialInfos;if(g){s.materialInfos=[];for(const e of g){const t=new ar;t.indexCount=e.indexCount,t.indexStart=e.indexStart,t.verticesCount=e.verticesCount,t.verticesStart=e.verticesStart,t.materialIndex=e.materialIndex,s.materialInfos.push(t)}}return s}static ImportVertexData(t,s){const i=e.Parse(t);s.setAllVerticesData(i,t.updatable)}},(()=>{const t="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;i=[W.filter((...e)=>!Array.isArray(e[0]))],r=[W.filter((...e)=>!Array.isArray(e[0]))],n=[W.filter((...e)=>!Array.isArray(e[0]))],o=[W.filter((...e)=>!Array.isArray(e[0]))],b(e,null,i,{kind:"method",name:"_TransformVector3Coordinates",static:!0,private:!1,access:{has:e=>"_TransformVector3Coordinates"in e,get:e=>e._TransformVector3Coordinates},metadata:t},null,h),b(e,null,r,{kind:"method",name:"_TransformVector3Normals",static:!0,private:!1,access:{has:e=>"_TransformVector3Normals"in e,get:e=>e._TransformVector3Normals},metadata:t},null,h),b(e,null,n,{kind:"method",name:"_TransformVector4Normals",static:!0,private:!1,access:{has:e=>"_TransformVector4Normals"in e,get:e=>e._TransformVector4Normals},metadata:t},null,h),b(e,null,o,{kind:"method",name:"_FlipFaces",static:!0,private:!1,access:{has:e=>"_FlipFaces"in e,get:e=>e._FlipFaces},metadata:t},null,h),t&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:t})})(),e.FRONTSIDE=(A(e,h),0),e.BACKSIDE=1,e.DOUBLESIDE=2,e.DEFAULTSIDE=0,e._UniqueIdGenerator=0,e})();class hr{static get ForceFullSceneLoadingForIncremental(){return hr._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){hr._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return hr._ShowLoadingScreen}static set ShowLoadingScreen(e){hr._ShowLoadingScreen=e}static get loggingLevel(){return hr._LoggingLevel}static set loggingLevel(e){hr._LoggingLevel=e}static get CleanBoneMatrixWeights(){return hr._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){hr._CleanBoneMatrixWeights=e}}hr._ForceFullSceneLoadingForIncremental=!1,hr._ShowLoadingScreen=!0,hr._CleanBoneMatrixWeights=!1,hr._LoggingLevel=dt.SCENELOADER_NO_LOGGING;class lr{get boundingBias(){return this._boundingBias}set boundingBias(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)}static CreateGeometryForMesh(e){const t=new lr(lr.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,s,i=!1,r=null,n=null){this.delayLoadState=dt.DELAYLOADSTATE_NONE,this._totalVertices=0,this._isDisposed=!1,this._extend={minimum:new xe(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),maximum:new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||ee.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=i,null!==n&&(this._totalVertices=n),s?this.setAllVerticesData(s,i):null===n&&(this._totalVertices=0),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return this.delayLoadState===dt.DELAYLOADSTATE_LOADED||this.delayLoadState===dt.DELAYLOADSTATE_NONE}get doNotSerialize(){for(let e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0}_rebuild(){this._vertexArrayObjects&&(this._vertexArrayObjects={}),0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer"));const e=new Set;for(const t in this._vertexBuffers)e.add(this._vertexBuffers[t].getWrapperBuffer());e.forEach(e=>{e._rebuild()})}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,s=!1,i){s&&Array.isArray(t)&&(t=new Float32Array(t));const r=new Gi(this._engine,t,e,{updatable:s,postponeInternalCreation:0===this._meshes.length,stride:i,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(r)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,s=!0){const i=e.getKind();this._vertexBuffers[i]&&s&&this._vertexBuffers[i].dispose(),e._buffer&&e._ownsBuffer&&e._buffer._increaseReferences(),this._vertexBuffers[i]=e;const r=this._meshes,n=r.length;if(i===Gi.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(this.useBoundingInfoFromGeometry&&this._boundingInfo?null:e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const s=this._extend&&this._extend.minimum||new xe(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),i=this._extend&&this._extend.maximum||new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e<n;e++){const t=r[e];t.buildBoundingInfo(s,i),t._createGlobalSubMesh(t.isUnIndexed),t.computeWorldMatrix(!0),t.synchronizeInstances()}}this._notifyUpdate(i)}updateVerticesDataDirectly(e,t,s,i=!1){const r=this.getVertexBuffer(e);r&&(r.updateDirectly(t,s,i),this._notifyUpdate(e))}updateVerticesData(e,t,s=!1){const i=this.getVertexBuffer(e);i&&(i.update(t),e===Gi.PositionKind&&this._updateBoundingInfo(s,t),this._notifyUpdate(e))}_updateBoundingInfo(e,t){if(e&&this._updateExtend(t),this._resetPointsArrayCache(),e){const e=this._meshes;for(const t of e){t.hasBoundingInfo?t.getBoundingInfo().reConstruct(this._extend.minimum,this._extend.maximum):t.buildBoundingInfo(this._extend.minimum,this._extend.maximum);const e=t.subMeshes;for(const t of e)t.refreshBoundingInfo()}}}_bind(e,t,s,i){if(!e)return;void 0===t&&(t=this._indexBuffer);const r=this.getVertexBuffers();if(!r)return;if(t!=this._indexBuffer||!this._vertexArrayObjects&&!i)return void this._engine.bindBuffers(r,t,e,s);const n=i||this._vertexArrayObjects,a=this._engine;n[e.key]||(n[e.key]=a.recordVertexArrayObject(r,t,e,s)),a.bindVertexArrayObject(n[e.key],t)}getTotalVertices(){return this.isReady()?this._totalVertices:0}getVerticesData(e,t,s){const i=this.getVertexBuffer(e);return i?i.getFloatData(this._totalVertices,s||t&&1!==this._meshes.length):null}copyVerticesData(e,t){const s=this.getVertexBuffer(e);if(!s)return;t[e]||=new Float32Array(this._totalVertices*s.getSize());const i=s.getData();i&&function(e,t,s,i,r,n,o,h){const l=t*ts(s),c=o*t;if(h.length!==c)throw new Error("Output length is not valid");if(s===dt.FLOAT&&r===l)if(e instanceof Array){const t=i/4;h.set(e,t)}else if(ArrayBuffer.isView(e)){const t=e.byteOffset+i;if(3&t)return a.Warn("Float array must be aligned to 4-bytes border"),void h.set(new Float32Array(e.buffer.slice(t,t+c*Float32Array.BYTES_PER_ELEMENT)));const s=new Float32Array(e.buffer,t,c);h.set(s)}else{const t=new Float32Array(e,i,c);h.set(t)}else is(e,i,r,t,s,c,n,(e,s)=>{for(let i=0;i<t;i++)h[s+i]=e[i]})}(i,s.getSize(),s.type,s.byteOffset,s.byteStride,s.normalized,this._totalVertices,t[e])}isVertexBufferUpdatable(e){const t=this._vertexBuffers[e];return!!t&&t.isUpdatable()}getVertexBuffer(e){return this.isReady()?this._vertexBuffers[e]:null}getVertexBuffers(){return this.isReady()?this._vertexBuffers:null}isVerticesDataPresent(e){return this._vertexBuffers?void 0!==this._vertexBuffers[e]:!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)}getVerticesDataKinds(){const e=[];let t;if(!this._vertexBuffers&&this._delayInfo)for(t in this._delayInfo)e.push(t);else for(t in this._vertexBuffers)e.push(t);return e}updateIndices(e,t,s=!1){if(this._indexBuffer)if(this._indexBufferIsUpdatable){const i=e.length!==this._indices.length;if(s||(this._indices=e.slice()),this._engine.updateDynamicIndexBuffer(this._indexBuffer,e,t),i)for(const e of this._meshes)e._createGlobalSubMesh(!0)}else this.setIndices(e,null,!0)}setIndexBuffer(e,t,s,i=null){this._indices=[],this._indexBufferIsUpdatable=!1,this._indexBuffer=e,this._totalVertices=t,this._totalIndices=s,e.is32Bits=null===i?t>65535:i;for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,s=!1,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=s,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,s,"Geometry_"+this.id+"_IndexBuffer")),null!=t&&(this._totalVertices=t);for(const e of this._meshes)e._createGlobalSubMesh(!i),e.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?void 0!==this._totalIndices?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const s=this._indices;return t||e&&1!==this._meshes.length?s.slice():s}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const s=this._meshes,i=s.indexOf(e);-1!==i&&(s.splice(i,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===s.length&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const s=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),s.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&!(e=this.getVerticesData(Gi.PositionKind)))return;this._extend=ir(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){for(const t in this._vertexBuffers){const s=this._vertexBuffers[t];s._buffer.getBuffer()||s.create(),t===Gi.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo())}!this._indexBuffer&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const e of this._meshes)e._markSubMeshesAsAttributesDirty()}load(e,t){this.delayLoadState!==dt.DELAYLOADSTATE_LOADING&&(this.isReady()?t&&t():(this.delayLoadState=dt.DELAYLOADSTATE_LOADING,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),(async()=>{try{const s=await e._loadDelayedFileAsync(this.delayLoadingFile,!1,!0);if(!this._delayLoadingFunction)return void e.removePendingData(this);this._delayLoadingFunction(JSON.parse(s),this),this.delayLoadState=dt.DELAYLOADSTATE_LOADED,this._delayInfo=[],e.removePendingData(this);const i=this._meshes,r=i.length;for(let e=0;e<r;e++)this._applyToMesh(i[e]);t&&t()}catch(t){e.removePendingData(this),e.isDisposed||a.Error(`Unable to delay load geometry "${this.id}" from "${this.delayLoadingFile}": ${t}`)}})())}toLeftHanded(){const e=this.getIndices(!1);if(null!=e&&e.length>0){for(let t=0;t<e.length;t+=3){const s=e[t+0];e[t+0]=e[t+2],e[t+2]=s}this.setIndices(e)}const t=this.getVerticesData(Gi.PositionKind,!1);if(null!=t&&t.length>0){for(let e=0;e<t.length;e+=3)t[e+2]=-t[e+2];this.setVerticesData(Gi.PositionKind,t,!1)}const s=this.getVerticesData(Gi.NormalKind,!1);if(null!=s&&s.length>0){for(let e=0;e<s.length;e+=3)s[e+2]=-s[e+2];this.setVerticesData(Gi.NormalKind,s,!1)}}_resetPointsArrayCache(){this._positions=null}_generatePointsArray(){if(this._positions)return!0;const e=this.getVerticesData(Gi.PositionKind);if(!e||0===e.length)return!1;for(let t=3*this._positionsCache.length,s=this._positionsCache.length;t<e.length;t+=3,++s)this._positionsCache[s]=xe.FromArray(e,t);for(let t=0,s=0;t<e.length;t+=3,++s)this._positionsCache[s].set(e[0+t],e[1+t],e[2+t]);return this._positionsCache.length=e.length/3,this._positions=this._positionsCache,!0}isDisposed(){return this._isDisposed}_disposeVertexArrayObjects(){if(this._vertexArrayObjects){for(const e in this._vertexArrayObjects)this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e]);this._vertexArrayObjects={};const e=this._meshes,t=e.length;for(let s=0;s<t;s++)e[s]._invalidateInstanceVertexArrayObject()}}dispose(){const e=this._meshes,t=e.length;let s;for(s=0;s<t;s++)this.releaseForMesh(e[s]);this._meshes.length=0,this._disposeVertexArrayObjects();for(const e in this._vertexBuffers)this._vertexBuffers[e].dispose();if(this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=dt.DELAYLOADSTATE_NONE,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._parentContainer){const e=this._parentContainer.geometries.indexOf(this);e>-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new lr(e,this._scene),s=this.getIndices(void 0,!0);s&&t.setIndices(s);let i,r=!1;for(i in this._vertexBuffers){const e=this.getVertexBuffer(i),s=e.getData();if(!s)continue;const n=e.isUpdatable(),a=e.getSize(),{type:o,byteOffset:h,byteStride:l,normalized:c}=e;r=r||n;let u=this._totalVertices;if(e.getIsInstanced()){let e;e=s instanceof Array?4*s.length:s.byteLength,u=e/l}const d=ns(s,a,o,h,l,u,!0),_=new Gi(this._engine,d,i,{updatable:n,useBytes:!1,stride:a,size:a,offset:0,type:o,normalized:c,takeBufferOwnership:!0,instanced:e.getIsInstanced()});t.setVerticesBuffer(_,u)}for(i in t._updatable=r,t.delayLoadState=this.delayLoadState,t.delayLoadingFile=this.delayLoadingFile,t._delayLoadingFunction=this._delayLoadingFunction,this._delayInfo)t._delayInfo=t._delayInfo||[],t._delayInfo.push(i);return t._boundingInfo=new tr(this._extend.minimum,this._extend.maximum),t}serialize(){const e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,Ge&&Ge.HasTags(this)&&(e.tags=Ge.GetTags(this)),e}_toNumberArray(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)}clearCachedData(){this._totalIndices=this._indices.length,this._indices=[],this._resetPointsArrayCache();for(const e in this._vertexBuffers)Object.prototype.hasOwnProperty.call(this._vertexBuffers,e)&&(this._vertexBuffers[e]._buffer._data=null)}serializeVerticeData(){const e=this.serialize();return this.isVerticesDataPresent(Gi.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(Gi.PositionKind)),this.isVertexBufferUpdatable(Gi.PositionKind)&&(e.positionsUpdatable=!0)),this.isVerticesDataPresent(Gi.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(Gi.NormalKind)),this.isVertexBufferUpdatable(Gi.NormalKind)&&(e.normalsUpdatable=!0)),this.isVerticesDataPresent(Gi.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(Gi.TangentKind)),this.isVertexBufferUpdatable(Gi.TangentKind)&&(e.tangentsUpdatable=!0)),this.isVerticesDataPresent(Gi.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(Gi.UVKind)),this.isVertexBufferUpdatable(Gi.UVKind)&&(e.uvsUpdatable=!0)),this.isVerticesDataPresent(Gi.UV2Kind)&&(e.uvs2=this._toNumberArray(this.getVerticesData(Gi.UV2Kind)),this.isVertexBufferUpdatable(Gi.UV2Kind)&&(e.uvs2Updatable=!0)),this.isVerticesDataPresent(Gi.UV3Kind)&&(e.uvs3=this._toNumberArray(this.getVerticesData(Gi.UV3Kind)),this.isVertexBufferUpdatable(Gi.UV3Kind)&&(e.uvs3Updatable=!0)),this.isVerticesDataPresent(Gi.UV4Kind)&&(e.uvs4=this._toNumberArray(this.getVerticesData(Gi.UV4Kind)),this.isVertexBufferUpdatable(Gi.UV4Kind)&&(e.uvs4Updatable=!0)),this.isVerticesDataPresent(Gi.UV5Kind)&&(e.uvs5=this._toNumberArray(this.getVerticesData(Gi.UV5Kind)),this.isVertexBufferUpdatable(Gi.UV5Kind)&&(e.uvs5Updatable=!0)),this.isVerticesDataPresent(Gi.UV6Kind)&&(e.uvs6=this._toNumberArray(this.getVerticesData(Gi.UV6Kind)),this.isVertexBufferUpdatable(Gi.UV6Kind)&&(e.uvs6Updatable=!0)),this.isVerticesDataPresent(Gi.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(Gi.ColorKind)),this.isVertexBufferUpdatable(Gi.ColorKind)&&(e.colorsUpdatable=!0)),this.isVerticesDataPresent(Gi.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(Gi.MatricesIndicesKind)),e.matricesIndicesExpanded=!0,this.isVertexBufferUpdatable(Gi.MatricesIndicesKind)&&(e.matricesIndicesUpdatable=!0)),this.isVerticesDataPresent(Gi.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(Gi.MatricesWeightsKind)),this.isVertexBufferUpdatable(Gi.MatricesWeightsKind)&&(e.matricesWeightsUpdatable=!0)),e.indices=this._toNumberArray(this.getIndices()),e}static ExtractFromMesh(e,t){const s=e._geometry;return s?s.copy(t):null}static RandomId(){return Fs.RandomId()}static _GetGeometryByLoadedUniqueId(e,t){for(let s=0;s<t.geometries.length;s++)if(t.geometries[s]._loadedUniqueId===e)return t.geometries[s];return null}static _ImportGeometry(e,t){const s=t.getScene(),i=e.geometryUniqueId,r=e.geometryId;if(i||r){const e=i?this._GetGeometryByLoadedUniqueId(i,s):s.getGeometryById(r);e&&e.applyToMesh(t)}else if(e instanceof ArrayBuffer){const s=t._binaryInfo;if(s.positionsAttrDesc&&s.positionsAttrDesc.count>0){const i=new Float32Array(e,s.positionsAttrDesc.offset,s.positionsAttrDesc.count);t.setVerticesData(Gi.PositionKind,i,!1)}if(s.normalsAttrDesc&&s.normalsAttrDesc.count>0){const i=new Float32Array(e,s.normalsAttrDesc.offset,s.normalsAttrDesc.count);t.setVerticesData(Gi.NormalKind,i,!1)}if(s.tangetsAttrDesc&&s.tangetsAttrDesc.count>0){const i=new Float32Array(e,s.tangetsAttrDesc.offset,s.tangetsAttrDesc.count);t.setVerticesData(Gi.TangentKind,i,!1)}if(s.uvsAttrDesc&&s.uvsAttrDesc.count>0){const i=new Float32Array(e,s.uvsAttrDesc.offset,s.uvsAttrDesc.count);t.setVerticesData(Gi.UVKind,i,!1)}if(s.uvs2AttrDesc&&s.uvs2AttrDesc.count>0){const i=new Float32Array(e,s.uvs2AttrDesc.offset,s.uvs2AttrDesc.count);t.setVerticesData(Gi.UV2Kind,i,!1)}if(s.uvs3AttrDesc&&s.uvs3AttrDesc.count>0){const i=new Float32Array(e,s.uvs3AttrDesc.offset,s.uvs3AttrDesc.count);t.setVerticesData(Gi.UV3Kind,i,!1)}if(s.uvs4AttrDesc&&s.uvs4AttrDesc.count>0){const i=new Float32Array(e,s.uvs4AttrDesc.offset,s.uvs4AttrDesc.count);t.setVerticesData(Gi.UV4Kind,i,!1)}if(s.uvs5AttrDesc&&s.uvs5AttrDesc.count>0){const i=new Float32Array(e,s.uvs5AttrDesc.offset,s.uvs5AttrDesc.count);t.setVerticesData(Gi.UV5Kind,i,!1)}if(s.uvs6AttrDesc&&s.uvs6AttrDesc.count>0){const i=new Float32Array(e,s.uvs6AttrDesc.offset,s.uvs6AttrDesc.count);t.setVerticesData(Gi.UV6Kind,i,!1)}if(s.colorsAttrDesc&&s.colorsAttrDesc.count>0){const i=new Float32Array(e,s.colorsAttrDesc.offset,s.colorsAttrDesc.count);t.setVerticesData(Gi.ColorKind,i,!1,s.colorsAttrDesc.stride)}if(s.matricesIndicesAttrDesc&&s.matricesIndicesAttrDesc.count>0){const i=new Int32Array(e,s.matricesIndicesAttrDesc.offset,s.matricesIndicesAttrDesc.count),r=[];for(let e=0;e<i.length;e++){const t=i[e];r.push(255&t),r.push((65280&t)>>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(Gi.MatricesIndicesKind,r,!1)}if(s.matricesIndicesExtraAttrDesc&&s.matricesIndicesExtraAttrDesc.count>0){const i=new Int32Array(e,s.matricesIndicesExtraAttrDesc.offset,s.matricesIndicesExtraAttrDesc.count),r=[];for(let e=0;e<i.length;e++){const t=i[e];r.push(255&t),r.push((65280&t)>>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(Gi.MatricesIndicesExtraKind,r,!1)}if(s.matricesWeightsAttrDesc&&s.matricesWeightsAttrDesc.count>0){const i=new Float32Array(e,s.matricesWeightsAttrDesc.offset,s.matricesWeightsAttrDesc.count);t.setVerticesData(Gi.MatricesWeightsKind,i,!1)}if(s.indicesAttrDesc&&s.indicesAttrDesc.count>0){const i=new Int32Array(e,s.indicesAttrDesc.offset,s.indicesAttrDesc.count);t.setIndices(i,null)}if(s.subMeshesAttrDesc&&s.subMeshesAttrDesc.count>0){const i=new Int32Array(e,s.subMeshesAttrDesc.offset,5*s.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e<s.subMeshesAttrDesc.count;e++){const s=i[5*e+0],r=i[5*e+1],n=i[5*e+2],a=i[5*e+3],o=i[5*e+4];nr.AddToMesh(s,r,n,a,o,t)}}}else if(e.positions&&e.normals&&e.indices){if(t.setVerticesData(Gi.PositionKind,e.positions,e.positions._updatable||e.positionsUpdatable),t.setVerticesData(Gi.NormalKind,e.normals,e.normals._updatable||e.normalsUpdatable),e.tangents&&t.setVerticesData(Gi.TangentKind,e.tangents,e.tangents._updatable||e.tangentsUpdatable),e.uvs&&t.setVerticesData(Gi.UVKind,e.uvs,e.uvs._updatable||e.uvsUpdatable),e.uvs2&&t.setVerticesData(Gi.UV2Kind,e.uvs2,e.uvs2._updatable||e.uvs2Updatable),e.uvs3&&t.setVerticesData(Gi.UV3Kind,e.uvs3,e.uvs3._updatable||e.uvs3Updatable),e.uvs4&&t.setVerticesData(Gi.UV4Kind,e.uvs4,e.uvs4._updatable||e.uvs4Updatable),e.uvs5&&t.setVerticesData(Gi.UV5Kind,e.uvs5,e.uvs5._updatable||e.uvs5Updatable),e.uvs6&&t.setVerticesData(Gi.UV6Kind,e.uvs6,e.uvs6._updatable||e.uvs6Updatable),e.colors&&t.setVerticesData(Gi.ColorKind,Ke.CheckColors4(e.colors,e.positions.length/3),e.colors._updatable),e.matricesIndices)if(e.matricesIndices._isExpanded||e.matricesIndicesExpanded)delete e.matricesIndices._isExpanded,delete e.matricesIndicesExpanded,t.setVerticesData(Gi.MatricesIndicesKind,e.matricesIndices,e.matricesIndices._updatable||e.matricesIndicesUpdatable);else{const s=[];for(let t=0;t<e.matricesIndices.length;t++){const i=e.matricesIndices[t];s.push(255&i),s.push((65280&i)>>8),s.push((16711680&i)>>16),s.push(i>>24&255)}t.setVerticesData(Gi.MatricesIndicesKind,s,e.matricesIndices._updatable||e.matricesIndicesUpdatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtraExpanded||e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,delete e.matricesIndicesExtraExpanded,t.setVerticesData(Gi.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable||e.matricesIndicesExtraUpdatable);else{const s=[];for(let t=0;t<e.matricesIndicesExtra.length;t++){const i=e.matricesIndicesExtra[t];s.push(255&i),s.push((65280&i)>>8),s.push((16711680&i)>>16),s.push(i>>24&255)}t.setVerticesData(Gi.MatricesIndicesExtraKind,s,e.matricesIndicesExtra._updatable||e.matricesIndicesExtraUpdatable)}e.matricesWeights&&(lr._CleanMatricesWeights(e,t),t.setVerticesData(Gi.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(Gi.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let s=0;s<e.subMeshes.length;s++){const i=e.subMeshes[s];nr.AddToMesh(i.materialIndex,i.verticesStart,i.verticesCount,i.indexStart,i.indexCount,t)}}t._shouldGenerateFlatShading&&(t.convertToFlatShadedMesh(),t._shouldGenerateFlatShading=!1),t.computeWorldMatrix(!0),s.onMeshImportedObservable.notifyObservers(t)}static _CleanMatricesWeights(e,t){const s=.001;if(!hr.CleanBoneMatrixWeights)return;let i;if(!(e.skeletonId>-1))return;{const s=t.getScene().getLastSkeletonById(e.skeletonId);if(!s)return;i=s.bones.length}const r=t.getVerticesData(Gi.MatricesIndicesKind),n=t.getVerticesData(Gi.MatricesIndicesExtraKind),a=e.matricesWeights,o=e.matricesWeightsExtra,h=e.numBoneInfluencer,l=a.length;for(let e=0;e<l;e+=4){let t=0,l=-1;for(let i=0;i<4;i++){const r=a[e+i];t+=r,r<s&&l<0&&(l=i)}if(o)for(let i=0;i<4;i++){const r=o[e+i];t+=r,r<s&&l<0&&(l=i+4)}if((l<0||l>h-1)&&(l=h-1),t>s){const s=1/t;for(let t=0;t<4;t++)a[e+t]*=s;if(o)for(let t=0;t<4;t++)o[e+t]*=s}else l>=4?(o[e+l-4]=1-t,n[e+l-4]=i):(a[e+l]=1-t,r[e+l]=i)}t.setVerticesData(Gi.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(Gi.MatricesIndicesExtraKind,n)}static Parse(e,t,s){const i=new lr(e.id,t,void 0,e.updatable);return i._loadedUniqueId=e.uniqueId,Ge&&Ge.AddTagsTo(i,e.tags),e.delayLoadingFile?(i.delayLoadState=dt.DELAYLOADSTATE_NOTLOADED,i.delayLoadingFile=s+e.delayLoadingFile,i._boundingInfo=new tr(xe.FromArray(e.boundingBoxMinimum),xe.FromArray(e.boundingBoxMaximum)),i._delayInfo=[],e.hasUVs&&i._delayInfo.push(Gi.UVKind),e.hasUVs2&&i._delayInfo.push(Gi.UV2Kind),e.hasUVs3&&i._delayInfo.push(Gi.UV3Kind),e.hasUVs4&&i._delayInfo.push(Gi.UV4Kind),e.hasUVs5&&i._delayInfo.push(Gi.UV5Kind),e.hasUVs6&&i._delayInfo.push(Gi.UV6Kind),e.hasColors&&i._delayInfo.push(Gi.ColorKind),e.hasMatricesIndices&&i._delayInfo.push(Gi.MatricesIndicesKind),e.hasMatricesWeights&&i._delayInfo.push(Gi.MatricesWeightsKind),i._delayLoadingFunction=or.ImportVertexData):or.ImportVertexData(e,i),t.pushGeometry(i,!0),i}}let cr=(()=>{var e;let t,s,i,r,n,a,o,h,l,u=Qe,d=[],_=[],p=[],f=[],g=[],m=[],T=[],E=[],R=[],y=[],M=[],x=[],S=[],v=[],I=[],P=[],C=[],O=[];return e=class extends u{get billboardMode(){return this._billboardMode}set billboardMode(t){this._billboardMode!==t&&(this._billboardMode=t,this._cache.useBillboardPosition=0!==(this._billboardMode&e.BILLBOARDMODE_USE_POSITION))}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(t,s=null,i=!0){super(t,s,!1),this._forward=new xe(0,0,1),this._up=new xe(0,1,0),this._right=new xe(1,0,0),this._position=A(this,d,xe.Zero()),this._rotation=(A(this,_),A(this,p,xe.Zero())),this._rotationQuaternion=(A(this,f),A(this,g,null)),this._scaling=(A(this,m),A(this,T,xe.One())),this._transformToBoneReferal=(A(this,E),null),this._isAbsoluteSynced=!1,this._billboardMode=A(this,R,e.BILLBOARDMODE_NONE),this.scalingDeterminant=(A(this,y),A(this,M,1)),this._infiniteDistance=(A(this,x),A(this,S,!1)),this.ignoreNonUniformScaling=(A(this,v),A(this,I,!1)),this.reIntegrateRotationIntoRotationQuaternion=(A(this,P),A(this,C,!1)),this._poseMatrix=(A(this,O),null),this._localMatrix=Ie.Zero(),this._usePivotMatrix=!1,this._absolutePosition=xe.Zero(),this._absoluteScaling=xe.Zero(),this._absoluteRotationQuaternion=ve.Identity(),this._pivotMatrix=Ie.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new c,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._markAsDirtyInternal()}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._markAsDirtyInternal()}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._markAsDirtyInternal()}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._markAsDirtyInternal()}_markAsDirtyInternal(){this._isDirty||(this._isDirty=!0,this.customMarkAsDirty&&this.customMarkAsDirty())}get forward(){return xe.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return xe.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return xe.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=Ie.Identity()),this._poseMatrix}_isSynchronized(){const t=this._cache;return this._billboardMode===t.billboardMode&&this._billboardMode===e.BILLBOARDMODE_NONE&&(!t.pivotMatrixUpdated&&(!this._infiniteDistance&&(!this._position._isDirty&&(!this._scaling._isDirty&&!(this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)))))}_initCache(){super._initCache();const e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=Ie.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,s){const i=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);i&&s&&s(this,i);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(i,t,s);return i}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||ve.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,s,i;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],s=arguments[1],i=arguments[2]}else t=e.x,s=e.y,i=e.z;if(this.parent){const e=Ce.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),xe.TransformCoordinatesFromFloatsToRef(t,s,i,e,this.position)}else this.position.x=t,this.position.y=s,this.position.z=i;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=xe.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=Ce.Matrix[0];return this._localMatrix.invertToRef(e),xe.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=xe.TransformCoordinates(e,this._localMatrix),this}lookAt(t,s=0,i=0,r=0,n=0){const a=e._LookAtVectorCache,o=0===n?this.position:this.getAbsolutePosition();if(t.subtractToRef(o,a),this.setDirection(a,s,i,r),1===n&&this.parent)if(this.rotationQuaternion){const e=Ce.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=Ce.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=Ce.Quaternion[0];ve.FromEulerVectorToRef(this.rotation,e);const t=Ce.Matrix[0];e.toRotationMatrix(t);const s=Ce.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(s),s.invert(),t.multiplyToRef(s,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=xe.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return xe.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,s=0,i=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,n);return this.rotationQuaternion?ve.RotationYawPitchRollToRef(r+t,a+s,i,this.rotationQuaternion):(this.rotation.x=a+s,this.rotation.y=r+t,this.rotation.z=i),this}setPivotPoint(e,t=0){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const s=this.getWorldMatrix();if(1==t){const t=Ce.Matrix[0];s.invertToRef(t),e=xe.TransformCoordinates(e,t)}return this.setPivotMatrix(Ie.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=xe.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){const e=xe.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),xe.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(t,s=!1,i=!1){if(!t&&!this.parent)return this;const r=Ce.Quaternion[0],n=Ce.Vector3[0],a=Ce.Vector3[1],o=Ce.Matrix[1];Ie.IdentityToRef(o);const h=Ce.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=e._TmpRotation,ve.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),Ie.ComposeToRef(this.scaling,l,this.position,h),this.parent&&h.multiplyToRef(this.parent.computeWorldMatrix(!0),h),t&&(t.computeWorldMatrix(!0).invertToRef(o),h.multiplyToRef(o,h)),h.decompose(a,r,n,s?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(a),this.position.copyFrom(n),this.parent=t,i&&this.setPivotMatrix(Ie.Identity()),this}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.parent!==this||e.setParent(null,t),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=e?this._currentParentWhenAttachingToBone:null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(t,s,i){let r;if(t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&0!==i){if(this.parent){const e=this.parent.getWorldMatrix(),i=Ce.Matrix[0];e.invertToRef(i),t=xe.TransformNormal(t,i),e.determinant()<0&&(s*=-1)}r=ve.RotationAxisToRef(t,s,e._RotationAxisCache),r.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else r=ve.RotationAxisToRef(t,s,e._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);return this}rotateAround(e,t,s){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=ve.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const i=Ce.Vector3[0],r=Ce.Vector3[1],n=Ce.Vector3[2],a=Ce.Quaternion[0],o=Ce.Matrix[0],h=Ce.Matrix[1],l=Ce.Matrix[2],c=Ce.Matrix[3];return e.subtractToRef(this.position,i),Ie.TranslationToRef(i.x,i.y,i.z,o),Ie.TranslationToRef(-i.x,-i.y,-i.z,h),Ie.RotationAxisToRef(t,s,l),h.multiplyToRef(l,c),c.multiplyToRef(o,c),c.decompose(r,a,n),this.position.addInPlace(n),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,s){const i=e.scale(t);if(s&&0!==s)this.setAbsolutePosition(this.getAbsolutePosition().add(i));else{const e=this.getPositionExpressedInLocalSpace().add(i);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,s){let i;this.rotationQuaternion?i=this.rotationQuaternion:(i=Ce.Quaternion[1],ve.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,i));const r=Ce.Quaternion[0];return ve.RotationYawPitchRollToRef(t,e,s,r),i.multiplyInPlace(r),this.rotationQuaternion||i.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==e.BILLBOARDMODE_NONE}computeWorldMatrix(t=!1,s=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!t&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;s=s||this.getScene().activeCamera,this._updateCache();const r=this._cache;r.pivotMatrixUpdated=!1,r.billboardMode=this.billboardMode,r.infiniteDistance=this.infiniteDistance,r.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const n=this._getEffectiveParent(),a=e._TmpScaling;let o,h=this._position;if(this._infiniteDistance&&!this.parent&&s){const t=s.getWorldMatrix().m;h=e._TmpTranslation,h.copyFromFloats(this._position.x+t[12],this._position.y+t[13],this._position.z+t[14])}if(a.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion){if(this._rotationQuaternion._isDirty=!1,o=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion){this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(ve.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))}}else o=e._TmpRotation,ve.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,o);if(this._usePivotMatrix){const e=Ce.Matrix[1];Ie.ScalingToRef(a.x,a.y,a.z,e);const t=Ce.Matrix[0];o.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,Ce.Matrix[4]),Ce.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(h.x,h.y,h.z)}else Ie.ComposeToRef(a,o,h,this._localMatrix);if(n&&n.getWorldMatrix){if(t&&n.computeWorldMatrix(t),this.billboardMode){if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),Ce.Matrix[7])}else Ce.Matrix[7].copyFrom(n.getWorldMatrix());const t=Ce.Vector3[5],s=Ce.Vector3[6],i=Ce.Quaternion[0];Ce.Matrix[7].decompose(s,i,t),Ie.ScalingToRef(s.x,s.y,s.z,Ce.Matrix[7]),Ce.Matrix[7].setTranslation(t),e.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,t),this._localMatrix.setTranslation(t)),this._localMatrix.multiplyToRef(Ce.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),Ce.Matrix[6]),Ce.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(n.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s&&this.billboardMode)if(r.useBillboardPosition){const t=Ce.Vector3[0];this._worldMatrix.getTranslationToRef(t);const i=s.globalPosition;this._worldMatrix.invertToRef(Ce.Matrix[1]);const r=Ce.Vector3[1];xe.TransformCoordinatesToRef(i,Ce.Matrix[1],r),r.normalize();const n=-Math.atan2(r.z,r.x)+Math.PI/2,a=Math.sqrt(r.x*r.x+r.z*r.z),o=-Math.atan2(r.y,a);if(ve.RotationYawPitchRollToRef(n,o,0,Ce.Quaternion[0]),(this.billboardMode&e.BILLBOARDMODE_ALL)!==e.BILLBOARDMODE_ALL){const t=Ce.Vector3[1];Ce.Quaternion[0].toEulerAnglesToRef(t),(this.billboardMode&e.BILLBOARDMODE_X)!==e.BILLBOARDMODE_X&&(t.x=0),(this.billboardMode&e.BILLBOARDMODE_Y)!==e.BILLBOARDMODE_Y&&(t.y=0),(this.billboardMode&e.BILLBOARDMODE_Z)!==e.BILLBOARDMODE_Z&&(t.z=0),Ie.RotationYawPitchRollToRef(t.y,t.x,t.z,Ce.Matrix[0])}else Ie.FromQuaternionToRef(Ce.Quaternion[0],Ce.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(Ce.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(Ce.Vector3[0])}else{const t=Ce.Vector3[0];this._worldMatrix.getTranslationToRef(t),Ce.Matrix[1].copyFrom(s.getViewMatrix());const i=this.getScene().useRightHandedSystem;if(i&&Ce.Matrix[1].multiplyToRef(e._TmpRHRestore,Ce.Matrix[1]),Ce.Matrix[1].setTranslationFromFloats(0,0,0),Ce.Matrix[1].invertToRef(Ce.Matrix[0]),(this.billboardMode&e.BILLBOARDMODE_ALL)!==e.BILLBOARDMODE_ALL){Ce.Matrix[0].decompose(void 0,Ce.Quaternion[0],void 0);const t=Ce.Vector3[1];Ce.Quaternion[0].toEulerAnglesToRef(t),(this.billboardMode&e.BILLBOARDMODE_X)!==e.BILLBOARDMODE_X&&(t.x=0),(this.billboardMode&e.BILLBOARDMODE_Y)!==e.BILLBOARDMODE_Y&&(t.y=0),(this.billboardMode&e.BILLBOARDMODE_Z)!==e.BILLBOARDMODE_Z&&(t.z=0),i&&(t.y+=Math.PI),Ie.RotationYawPitchRollToRef(t.y,t.x,t.z,Ce.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(Ce.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(Ce.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):n&&n._nonUniformScaling?this._updateNonUniformScalingState(n._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=Ie.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;t<e.length;++t){const s=e[t];if(s){s.computeWorldMatrix();const e=Ce.Matrix[0];s._localMatrix.multiplyToRef(this._localMatrix,e);const t=Ce.Quaternion[0];e.decompose(s.scaling,t,s.position),s.rotationQuaternion?s.rotationQuaternion.copyFrom(t):t.toEulerAnglesToRef(s.rotation)}}}this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=ve.Identity()),this._worldMatrix=Ie.Identity()}_afterComputeWorldMatrix(){}registerAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this}unregisterAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this}getPositionInCameraSpace(e=null){return e||(e=this.getScene().activeCamera),xe.TransformCoordinates(this.getAbsolutePosition(),e.getViewMatrix())}getDistanceToCamera(e=null){return e||(e=this.getScene().activeCamera),this.getAbsolutePosition().subtract(e.globalPosition).length()}clone(t,s,i){const r=$e.Clone(()=>new e(t,this.getScene()),this);if(r.name=t,r.id=t,s&&(r.parent=s),!i){const e=this.getDescendants(!0);for(let s=0;s<e.length;s++){const i=e[s];i.clone&&i.clone(t+"."+i.name,r)}}return r}serialize(e){const t=$e.Serialize(this,e);return t.type=this.getClassName(),t.uniqueId=this.uniqueId,this.parent&&this.parent._serializeAsParent(t),t.localMatrix=this.getPivotMatrix().asArray(),t.isEnabled=this.isEnabled(),this._isWorldMatrixFrozen&&(t.freezeWorldMatrix=!0),$e.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t}getChildTransformNodes(t,s){const i=[];return this._getDescendants(i,t,t=>(!s||s(t))&&t instanceof e),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const e=this.getChildTransformNodes(!0);for(const t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,s){let i=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(i=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,s),a=n.max.subtract(n.min),o=Math.max(a.x,a.y,a.z);if(0===o)return this;const h=1/o;return this.scaling.scaleInPlace(h),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&i&&this.rotation.copyFrom(i)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}},(()=>{const c="function"==typeof Symbol&&Symbol.metadata?Object.create(u[Symbol.metadata]??null):void 0;var A;t=[k("position")],s=[k("rotation")],i=[(A="rotationQuaternion",D(10,A))],r=[k("scaling")],n=[L("billboardMode")],a=[L()],o=[L("infiniteDistance")],h=[L()],l=[L()],b(null,null,t,{kind:"field",name:"_position",static:!1,private:!1,access:{has:e=>"_position"in e,get:e=>e._position,set:(e,t)=>{e._position=t}},metadata:c},d,_),b(null,null,s,{kind:"field",name:"_rotation",static:!1,private:!1,access:{has:e=>"_rotation"in e,get:e=>e._rotation,set:(e,t)=>{e._rotation=t}},metadata:c},p,f),b(null,null,i,{kind:"field",name:"_rotationQuaternion",static:!1,private:!1,access:{has:e=>"_rotationQuaternion"in e,get:e=>e._rotationQuaternion,set:(e,t)=>{e._rotationQuaternion=t}},metadata:c},g,m),b(null,null,r,{kind:"field",name:"_scaling",static:!1,private:!1,access:{has:e=>"_scaling"in e,get:e=>e._scaling,set:(e,t)=>{e._scaling=t}},metadata:c},T,E),b(null,null,n,{kind:"field",name:"_billboardMode",static:!1,private:!1,access:{has:e=>"_billboardMode"in e,get:e=>e._billboardMode,set:(e,t)=>{e._billboardMode=t}},metadata:c},R,y),b(null,null,a,{kind:"field",name:"scalingDeterminant",static:!1,private:!1,access:{has:e=>"scalingDeterminant"in e,get:e=>e.scalingDeterminant,set:(e,t)=>{e.scalingDeterminant=t}},metadata:c},M,x),b(null,null,o,{kind:"field",name:"_infiniteDistance",static:!1,private:!1,access:{has:e=>"_infiniteDistance"in e,get:e=>e._infiniteDistance,set:(e,t)=>{e._infiniteDistance=t}},metadata:c},S,v),b(null,null,h,{kind:"field",name:"ignoreNonUniformScaling",static:!1,private:!1,access:{has:e=>"ignoreNonUniformScaling"in e,get:e=>e.ignoreNonUniformScaling,set:(e,t)=>{e.ignoreNonUniformScaling=t}},metadata:c},I,P),b(null,null,l,{kind:"field",name:"reIntegrateRotationIntoRotationQuaternion",static:!1,private:!1,access:{has:e=>"reIntegrateRotationIntoRotationQuaternion"in e,get:e=>e.reIntegrateRotationIntoRotationQuaternion,set:(e,t)=>{e.reIntegrateRotationIntoRotationQuaternion=t}},metadata:c},C,O),c&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:c})})(),e.BILLBOARDMODE_NONE=0,e.BILLBOARDMODE_X=1,e.BILLBOARDMODE_Y=2,e.BILLBOARDMODE_Z=4,e.BILLBOARDMODE_ALL=7,e.BILLBOARDMODE_USE_POSITION=128,e.BillboardUseParentOrientation=!1,e._TmpRotation=ve.Zero(),e._TmpScaling=xe.Zero(),e._TmpTranslation=xe.Zero(),e._TmpRHRestore=Ie.Scaling(1,1,-1),e._LookAtVectorCache=new xe(0,0,0),e._RotationAxisCache=new ve,e})();cr.prototype.getPhysicsBody??=Ne("TransformNode","getPhysicsBody"),cr.prototype.applyImpulse??=Ne("TransformNode","applyImpulse"),cr.prototype.applyAngularImpulse??=Ne("TransformNode","applyAngularImpulse"),cr.prototype.applyTorque??=Ne("TransformNode","applyTorque"),Object.getOwnPropertyDescriptor(cr.prototype,"physicsBody")||Object.defineProperty(cr.prototype,"physicsBody",Ue(0,"physicsBody"));class ur{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(Gi.NormalKind))return null;let s,i=this.pickedMesh.getIndices();0===i?.length&&(i=null);const r=Ce.Vector3[0],n=Ce.Vector3[1],a=Ce.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(Gi.NormalKind);let t=i?xe.FromArrayToRef(e,3*i[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),o=i?xe.FromArrayToRef(e,3*i[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),h=i?xe.FromArrayToRef(e,3*i[3*this.faceId+2],a):a.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),o=o.scale(this.bv),h=h.scale(1-this.bu-this.bv),s=new xe(t.x+o.x+h.x,t.y+o.y+h.y,t.z+o.z+h.z)}else{const e=this.pickedMesh.getVerticesData(Gi.PositionKind),t=i?xe.FromArrayToRef(e,3*i[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),o=i?xe.FromArrayToRef(e,3*i[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),h=i?xe.FromArrayToRef(e,3*i[3*this.faceId+2],a):a.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),l=t.subtract(o),c=h.subtract(o);s=xe.Cross(l,c)}const o=(e,t)=>{if(-1!==this.thinInstanceIndex){const s=e._thinInstanceDataStorage.matrixData,i=this.thinInstanceIndex<<4;if(s&&s.length>i){const e=Ce.Matrix[0];Ie.FromArrayToRef(s,i,e),xe.TransformNormalToRef(t,e,t)}}let s=e.getWorldMatrix();e.nonUniformScaling&&(Ce.Matrix[0].copyFrom(s),s=Ce.Matrix[0],s.setTranslationFromFloats(0,0,0),s.invert(),s.transposeToRef(Ce.Matrix[1]),s=Ce.Matrix[1]),xe.TransformNormalToRef(t,s,t)};if(e&&o(this.pickedMesh,s),this.ray){const t=Ce.Vector3[0].copyFrom(s);e||o(this.pickedMesh,t),xe.Dot(t,this.ray.direction)>0&&s.negateInPlace()}return s.normalize(),s}getTextureCoordinates(e=Gi.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const s=this.pickedMesh.getVerticesData(e);if(!s)return null;let i=Me.FromArray(s,2*t[3*this.faceId]),r=Me.FromArray(s,2*t[3*this.faceId+1]),n=Me.FromArray(s,2*t[3*this.faceId+2]);return i=i.scale(this.bu),r=r.scale(this.bv),n=n.scale(1-this.bu-this.bv),new Me(i.x+r.x+n.x,i.y+r.y+n.y)}}class dr{constructor(e,t,s=!1,i,r=!1,n){this._uniformNames=[],this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=s,this._name=i??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._trackUBOsInFrame=!1,(void 0===n&&this._engine._features.trackUbosInFrame||!0===n)&&(this._buffers=[],this._bufferIndex=-1,this._bufferUpdatedLastFrame=!1,this._createBufferOnWrite=!1,this._currentFrameId=0,this._trackUBOsInFrame=!0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}getUniformNames(){return this._uniformNames}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!==0){const e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const s=this._uniformLocationPointer-e;for(let e=0;e<s;e++)this._data.push(0)}}addUniform(e,t,s=0){if(s>0&&"number"==typeof t&&(this._uniformArraySizes[e]={strideSize:t,arraySize:s}),void 0!==this._uniformLocations[e])return;if(this._uniformNames.push(e),this._noUBO)return;let i;if(s>0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),16==t)t*=s;else{t=t*s+(4-t)*s}i=[];for(let e=0;e<t;e++)i.push(0)}else{if(t instanceof Array)i=t,t=i.length;else{i=[];for(let e=0;e<t;e++)i.push(0)}this._fillAlignment(t)}this._uniformSizes[e]=t,this._uniformLocations[e]=this._uniformLocationPointer,this._uniformLocationPointer+=t;for(let e=0;e<t;e++)this._data.push(i[e]);this._needSync=!0}addMatrix(e,t){this.addUniform(e,Array.prototype.slice.call(t.asArray()))}addFloat2(e,t,s){const i=[t,s];this.addUniform(e,i)}addFloat3(e,t,s,i){const r=[t,s,i];this.addUniform(e,r)}addColor3(e,t){const s=[t.r,t.g,t.b];this.addUniform(e,s)}addColor4(e,t,s){const i=[t.r,t.g,t.b,s];this.addUniform(e,i)}addVector3(e,t){const s=[t.x,t.y,t.z];this.addUniform(e,s)}addMatrix3x3(e){this.addUniform(e,12)}addMatrix2x2(e){this.addUniform(e,8)}create(){this._noUBO||this._buffer||(this._fillAlignment(4),this._bufferData=new Float32Array(this._data),this._rebuild(),this._needSync=!0)}_getNamesDebug(){const e=[];let t=0;for(const s in this._uniformLocations)if(e.push(s),10===++t)break;return e.join(",")}_rebuild(){!this._noUBO&&this._bufferData&&(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNamesDebug()):this._buffer=this._engine.createUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNamesDebug()),this._trackUBOsInFrame&&(this._buffers.push([this._buffer,this._engine._features.checkUbosContentBeforeUpload?this._bufferData.slice():void 0]),this._bufferIndex=this._buffers.length-1,this._createBufferOnWrite=!1))}_rebuildAfterContextLost(){this._trackUBOsInFrame&&(this._buffers=[],this._currentFrameId=0),this._rebuild()}get _numBuffers(){return this._buffers.length}get _indexBuffer(){return this._bufferIndex}get name(){return this._name}set name(e){this._name=e}get currentEffect(){return this._currentEffect}_buffersEqual(e,t){for(let s=0;s<e.length;++s)if(e[s]!==t[s])return!1;return!0}_copyBuffer(e,t){for(let s=0;s<e.length;++s)t[s]=e[s]}update(){if(!this._noUBO)if(this.bindUniformBuffer(),this._buffer)if(this._dynamic||this._needSync){if(this._buffers&&this._buffers.length>1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._trackUBOsInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._bufferUpdatedLastFrame=!0,this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._needSync=!1,this._createBufferOnWrite=this._trackUBOsInFrame}else this._createBufferOnWrite=this._trackUBOsInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+1<this._buffers.length?(this._bufferIndex++,this._buffer=this._buffers[this._bufferIndex][0],this._createBufferOnWrite=!1,this._needSync=!0):this._rebuild()}_checkNewFrame(){this._trackUBOsInFrame&&this._currentFrameId!==this._engine.frameId&&(this._currentFrameId=this._engine.frameId,this._createBufferOnWrite=!1,this._buffers&&this._buffers.length>0?(1===this._buffers.length?this._needSync=!this._bufferUpdatedLastFrame:this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,s){this._checkNewFrame();let i=this._uniformLocations[e];if(void 0===i){if(this._buffer)return void a.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,s),i=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e<s;e++)this._bufferData[i+e]=t[e];else{let e=!1;for(let r=0;r<s;r++)(16===s&&!this._engine._features.uniformBufferHardCheckMatrix||this._bufferData[i+r]!==Math.fround(t[r]))&&(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[i+r]=t[r]);this._needSync=this._needSync||e}}updateUniformArray(e,t,s){this._checkNewFrame();const i=this._uniformLocations[e];if(void 0===i)return void a.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine.");this._buffer||this.create();const r=this._uniformArraySizes[e];if(this._dynamic)for(let e=0;e<s;e++)this._bufferData[i+e]=t[e];else{let e=!1,n=0,a=0;for(let o=0;o<s;o++)if(this._bufferData[i+4*a+n]!==Fs.FloatRound(t[o])&&(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[i+4*a+n]=t[o]),n++,n===r.strideSize){for(;n<4;n++)this._bufferData[i+4*a+n]=0;n=0,a++}this._needSync=this._needSync||e}}_cacheMatrix(e,t){this._checkNewFrame();const s=this._valueCache[e],i=t.updateFlag;return(void 0===s||s!==i)&&(this._valueCache[e]=i,!0)}_updateMatrix3x3ForUniform(e,t){for(let e=0;e<3;e++)dr._TempBuffer[4*e]=t[3*e],dr._TempBuffer[4*e+1]=t[3*e+1],dr._TempBuffer[4*e+2]=t[3*e+2],dr._TempBuffer[4*e+3]=0;this.updateUniform(e,dr._TempBuffer,12)}_updateMatrix3x3ForEffect(e,t){this._currentEffect.setMatrix3x3(e,t)}_updateMatrix2x2ForEffect(e,t){this._currentEffect.setMatrix2x2(e,t)}_updateMatrix2x2ForUniform(e,t){for(let e=0;e<2;e++)dr._TempBuffer[4*e]=t[2*e],dr._TempBuffer[4*e+1]=t[2*e+1],dr._TempBuffer[4*e+2]=0,dr._TempBuffer[4*e+3]=0;this.updateUniform(e,dr._TempBuffer,8)}_updateFloatForEffect(e,t,s=""){this._currentEffect.setFloat(e+s,t)}_updateFloatForUniform(e,t){dr._TempBuffer[0]=t,this.updateUniform(e,dr._TempBuffer,1)}_updateFloat2ForEffect(e,t,s,i=""){this._currentEffect.setFloat2(e+i,t,s)}_updateFloat2ForUniform(e,t,s){dr._TempBuffer[0]=t,dr._TempBuffer[1]=s,this.updateUniform(e,dr._TempBuffer,2)}_updateFloat3ForEffect(e,t,s,i,r=""){this._currentEffect.setFloat3(e+r,t,s,i)}_updateFloat3ForUniform(e,t,s,i){dr._TempBuffer[0]=t,dr._TempBuffer[1]=s,dr._TempBuffer[2]=i,this.updateUniform(e,dr._TempBuffer,3)}_updateFloat4ForEffect(e,t,s,i,r,n=""){this._currentEffect.setFloat4(e+n,t,s,i,r)}_updateFloat4ForUniform(e,t,s,i,r){dr._TempBuffer[0]=t,dr._TempBuffer[1]=s,dr._TempBuffer[2]=i,dr._TempBuffer[3]=r,this.updateUniform(e,dr._TempBuffer,4)}_updateFloatArrayForEffect(e,t,s=""){switch(this._uniformArraySizes[e]?.strideSize){case 2:this._currentEffect.setFloatArray2(e+s,t);break;case 3:this._currentEffect.setFloatArray3(e+s,t);break;case 4:this._currentEffect.setFloatArray4(e+s,t);break;default:this._currentEffect.setFloatArray(e+s,t)}}_updateFloatArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateArrayForEffect(e,t){this._currentEffect.setArray(e,t)}_updateArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateIntArrayForEffect(e,t){this._currentEffect.setIntArray(e,t)}_updateIntArrayForUniform(e,t){dr._TempBufferInt32View.set(t),this.updateUniformArray(e,dr._TempBuffer,t.length)}_updateUIntArrayForEffect(e,t){this._currentEffect.setUIntArray(e,t)}_updateUIntArrayForUniform(e,t){dr._TempBufferUInt32View.set(t),this.updateUniformArray(e,dr._TempBuffer,t.length)}_updateMatrixForEffect(e,t){this._currentEffect.setMatrix(e,t)}_updateMatrixForUniform(e,t){this._cacheMatrix(e,t)&&this.updateUniform(e,t.asArray(),16)}_updateMatricesForEffect(e,t){this._currentEffect.setMatrices(e,t)}_updateMatricesForUniform(e,t){this.updateUniform(e,t,t.length)}_updateVector3ForEffect(e,t){this._currentEffect.setVector3(e,t)}_updateVector3ForUniform(e,t){dr._TempBuffer[0]=t.x,dr._TempBuffer[1]=t.y,dr._TempBuffer[2]=t.z,this.updateUniform(e,dr._TempBuffer,3)}_updateVector4ForEffect(e,t){this._currentEffect.setVector4(e,t)}_updateVector4ForUniform(e,t){dr._TempBuffer[0]=t.x,dr._TempBuffer[1]=t.y,dr._TempBuffer[2]=t.z,dr._TempBuffer[3]=t.w,this.updateUniform(e,dr._TempBuffer,4)}_updateColor3ForEffect(e,t,s=""){this._currentEffect.setColor3(e+s,t)}_updateColor3ForUniform(e,t){dr._TempBuffer[0]=t.r,dr._TempBuffer[1]=t.g,dr._TempBuffer[2]=t.b,this.updateUniform(e,dr._TempBuffer,3)}_updateColor4ForEffect(e,t,s,i=""){this._currentEffect.setColor4(e+i,t,s)}_updateDirectColor4ForEffect(e,t,s=""){this._currentEffect.setDirectColor4(e+s,t)}_updateColor4ForUniform(e,t,s){dr._TempBuffer[0]=t.r,dr._TempBuffer[1]=t.g,dr._TempBuffer[2]=t.b,dr._TempBuffer[3]=s,this.updateUniform(e,dr._TempBuffer,4)}_updateDirectColor4ForUniform(e,t){dr._TempBuffer[0]=t.r,dr._TempBuffer[1]=t.g,dr._TempBuffer[2]=t.b,dr._TempBuffer[3]=t.a,this.updateUniform(e,dr._TempBuffer,4)}_updateIntForEffect(e,t,s=""){this._currentEffect.setInt(e+s,t)}_updateIntForUniform(e,t){dr._TempBufferInt32View[0]=t,this.updateUniform(e,dr._TempBuffer,1)}_updateInt2ForEffect(e,t,s,i=""){this._currentEffect.setInt2(e+i,t,s)}_updateInt2ForUniform(e,t,s){dr._TempBufferInt32View[0]=t,dr._TempBufferInt32View[1]=s,this.updateUniform(e,dr._TempBuffer,2)}_updateInt3ForEffect(e,t,s,i,r=""){this._currentEffect.setInt3(e+r,t,s,i)}_updateInt3ForUniform(e,t,s,i){dr._TempBufferInt32View[0]=t,dr._TempBufferInt32View[1]=s,dr._TempBufferInt32View[2]=i,this.updateUniform(e,dr._TempBuffer,3)}_updateInt4ForEffect(e,t,s,i,r,n=""){this._currentEffect.setInt4(e+n,t,s,i,r)}_updateInt4ForUniform(e,t,s,i,r){dr._TempBufferInt32View[0]=t,dr._TempBufferInt32View[1]=s,dr._TempBufferInt32View[2]=i,dr._TempBufferInt32View[3]=r,this.updateUniform(e,dr._TempBuffer,4)}_updateUIntForEffect(e,t,s=""){this._currentEffect.setUInt(e+s,t)}_updateUIntForUniform(e,t){dr._TempBufferUInt32View[0]=t,this.updateUniform(e,dr._TempBuffer,1)}_updateUInt2ForEffect(e,t,s,i=""){this._currentEffect.setUInt2(e+i,t,s)}_updateUInt2ForUniform(e,t,s){dr._TempBufferUInt32View[0]=t,dr._TempBufferUInt32View[1]=s,this.updateUniform(e,dr._TempBuffer,2)}_updateUInt3ForEffect(e,t,s,i,r=""){this._currentEffect.setUInt3(e+r,t,s,i)}_updateUInt3ForUniform(e,t,s,i){dr._TempBufferUInt32View[0]=t,dr._TempBufferUInt32View[1]=s,dr._TempBufferUInt32View[2]=i,this.updateUniform(e,dr._TempBuffer,3)}_updateUInt4ForEffect(e,t,s,i,r,n=""){this._currentEffect.setUInt4(e+n,t,s,i,r)}_updateUInt4ForUniform(e,t,s,i,r){dr._TempBufferUInt32View[0]=t,dr._TempBufferUInt32View[1]=s,dr._TempBufferUInt32View[2]=i,dr._TempBufferUInt32View[3]=r,this.updateUniform(e,dr._TempBuffer,4)}setTexture(e,t){this._currentEffect.setTexture(e,t)}setTextureArray(e,t){this._currentEffect.setTextureArray(e,t)}bindTexture(e,t){this._currentEffect._bindTexture(e,t)}updateUniformDirectly(e,t){this.updateUniform(e,t,t.length),this.update()}bindToEffect(e,t){this._currentEffect=e,this._currentEffectName=t}bindUniformBuffer(){!this._noUBO&&this._buffer&&this._currentEffect&&this._currentEffect.bindUniformBuffer(this._buffer,this._currentEffectName)}unbindEffect(){this._currentEffect=void 0,this._currentEffectName=void 0}setDataBuffer(e){if(!this._buffers)return this._buffer===e;for(let t=0;t<this._buffers.length;++t){if(this._buffers[t][0]===e)return this._bufferIndex=t,this._buffer=e,this._createBufferOnWrite=!1,this._currentEffect=void 0,this._buffers.length>1&&this._buffers[t][1]&&this._bufferData.set(this._buffers[t][1]),this._valueCache={},this._currentFrameId=this._engine.frameId,!0}return!1}has(e){return void 0!==this._uniformLocations[e]}dispose(){if(this._noUBO)return;const e=this._engine._uniformBuffers,t=e.indexOf(this);if(-1!==t&&(e[t]=e[e.length-1],e.pop()),this._trackUBOsInFrame&&this._buffers)for(let e=0;e<this._buffers.length;++e){const t=this._buffers[e][0];this._engine._releaseBuffer(t)}else this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)}}dr._MAX_UNIFORM_SIZE=256,dr._TempBuffer=new Float32Array(dr._MAX_UNIFORM_SIZE),dr._TempBufferInt32View=new Int32Array(dr._TempBuffer.buffer),dr._TempBufferUInt32View=new Uint32Array(dr._TempBuffer.buffer);class _r{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new xe(0,0,0),this._diffPositionForCollisions=new xe(0,0,0),this._collisionResponse=!0}}var pr,fr;!function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(pr||(pr={}));class gr{}function mr(e,t){return e-Math.floor(e/t)*t}function Tr(e,t,s){e instanceof Float32Array?Ie.FromArrayToRef(e,t,s):s.copyFromFloats(Qt(e[t]),Qt(e[t+1]),Qt(e[t+2]),Qt(e[t+3]),Qt(e[t+4]),Qt(e[t+5]),Qt(e[t+6]),Qt(e[t+7]),Qt(e[t+8]),Qt(e[t+9]),Qt(e[t+10]),Qt(e[t+11]),Qt(e[t+12]),Qt(e[t+13]),Qt(e[t+14]),Qt(e[t+15]))}function Er(e,t,s,i,r,n,o,h,l){const c=s.texture,u=c?.getInternalTexture(),d=u?._bufferView;if(!(d instanceof Float32Array||d instanceof Uint16Array))return a.Warn("Baked vertex animation bounding info requires CPU-readable Float32Array or Uint16Array texture data.",1),!1;const _=c.getSize(),p=function(e,t){const s=e.y-e.x+1,i=t*e.w/s,r=i<1?0:1,n=s-r;let a=mr(i-Math.floor(i),1)*n;return a=mr(a+e.z,n),Math.floor(a)+e.x+r}(i,s.time);if(!isFinite(p)||p<0||p>=_.height)return a.Warn("Baked vertex animation bounding info could not be refreshed because the computed frame is outside the texture.",1),!1;const f=Ce.Vector3[0],g=Ce.Matrix[0],m=Ce.Matrix[1],T=p*_.width*4,E=t===Gi.NormalKind?xe.TransformNormalFromFloatsToRef:xe.TransformCoordinatesFromFloatsToRef;for(let t=0,s=0;t<e.length;t+=3,s+=4){let i,a;for(g.reset(),i=0;i<4&&i<l;i++)a=n[s+i],a>0&&(Tr(d,T+16*Math.floor(r[s+i]),m),m.scaleAndAddToRef(a,g));if(o&&h)for(i=0;i<4&&i+4<l;i++)a=h[s+i],a>0&&(Tr(d,T+16*Math.floor(o[s+i]),m),m.scaleAndAddToRef(a,g));E(e[t],e[t+1],e[t+2],g,f),f.toArray(e,t)}return!0}gr.X=new xe(1,0,0),gr.Y=new xe(0,1,0),gr.Z=new xe(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(fr||(fr={}));class Rr{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=xe.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class br{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Rr,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=new Map,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new _r,this._enableDistantPicking=!1,this._rawBoundingInfo=null,this._sideOrientationHint=!1,this._wasActiveLastFrame=!1}}let Ar=(()=>{var e;let t,s=cr,i=[];return e=class extends s{static get BILLBOARDMODE_NONE(){return cr.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return cr.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return cr.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return cr.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return cr.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return cr.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return!!super._updateNonUniformScalingState(e)&&(this._markSubMeshesAsMiscDirty(),!0)}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty(e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()})}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._setMaterial(e)}_setMaterial(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(void 0,null==e),this._unBindEffect()))}getMaterialForRenderPass(e){return this._internalAbstractMeshDataInfo._materialForRenderPass?.[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]);const s=this._internalAbstractMeshDataInfo._materialForRenderPass[e];s?.meshMap?.[this.uniqueId]&&(s.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t,t&&t.meshMap&&(t.meshMap[this.uniqueId]=this)}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(t,s=null){switch(super(t,s,!1),this._internalAbstractMeshDataInfo=new br,this._waitingMaterialId=null,this._waitingMorphTargetManagerId=null,this._waitingSkeletonId=null,this._waitingSkeletonUniqueId=null,this.cullingStrategy=e.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new c,this.onCollisionPositionChangeObservable=new c,this.onMaterialChangedObservable=new c,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this.isPickable=e.DefaultIsPickable,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=Xe.Red(),this.outlineWidth=.02,this.overlayColor=Xe.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new xe(.5,1,.5),this.ellipsoidOffset=new xe(0,0,0),this.edgesWidth=1,this.edgesColor=new Ke(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new c,this._onCollisionPositionChange=(e,t,s=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Ti.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),s&&this.onCollideObservable.notifyObservers(s),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},s=this.getScene(),this.layerMask=s.defaultRenderableLayerMask,s.addMesh(this),this._resyncLightSources(),this._uniformBuffer=new dr(this.getScene().getEngine(),void 0,void 0,t,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),s.performancePriority){case 2:this.doNotSyncBoundingInfo=!0;case 1:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){const t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+("InstancedMesh"===this.getClassName()?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);const s=this._internalAbstractMeshDataInfo._skeleton;return s&&(t+=", skeleton: "+s.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==cr.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_releaseRenderPassId(e){}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),null!==this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes){for(const e of this.subMeshes)e._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),s=this._lightSources.indexOf(e);let i=!1;if(-1===s){if(!t)return;this._lightSources.push(e)}else{if(t)return;i=!0,this._lightSources.splice(s,1)}this._markSubMeshesAsLightDirty(i)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const s=this._lightSources.indexOf(e);-1!==s&&(this._lightSources.splice(s,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let s=0;s<t._drawWrappers.length;++s){const i=t._drawWrappers[s];i&&i.defines&&i.defines.markAllAsDirty&&e(i.defines)}}_markSubMeshesAsLightDirty(e=!1){this._markSubMeshesAsDirty(t=>t.markAsLightDirty(e))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty(e=>e.markAsAttributesDirty())}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty(e=>e.markAsMiscDirty())}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,super.markAsDirty(e),this._isDirty=!0,this}resetDrawCache(e,t=!1){if(this.subMeshes)for(const s of this.subMeshes)s.resetDrawCache(e,t)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,s,i){return this}updateVerticesData(e,t,s,i){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,s){return this._boundingInfo=new tr(e,t,s),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,s){return super.normalizeToUnitCube(e,t,s)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(Gi.MatricesIndicesKind)&&this.isVerticesDataPresent(Gi.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===cr.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,s){return this.position.addInPlace(this.calcMovePOV(e,t,s)),this}calcMovePOV(e,t,s){const i=new Ie;(this.rotationQuaternion?this.rotationQuaternion:ve.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(i);const r=xe.Zero(),n=this.definedFacingForward?-1:1;return xe.TransformCoordinatesFromFloatsToRef(e*n,t,s*n,i,r),r}rotatePOV(e,t,s){return this.rotation.addInPlace(this.calcRotatePOV(e,t,s)),this}calcRotatePOV(e,t,s){const i=this.definedFacingForward?1:-1;return new xe(e*i,t,s*i)}_refreshBoundingInfo(e,t){if(e){const s=ir(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(s.minimum,s.maximum):this._boundingInfo=new tr(s.minimum,s.maximum)}if(this.subMeshes)for(let t=0;t<this.subMeshes.length;t++)this.subMeshes[t].refreshBoundingInfo(e);this._updateBoundingInfo()}_refreshBoundingInfoDirect(e){if(this._boundingInfo?this._boundingInfo.reConstruct(e.minimum,e.maximum):this._boundingInfo=new tr(e.minimum,e.maximum),this.subMeshes)for(let e=0;e<this.subMeshes.length;e++)this.subMeshes[e].refreshBoundingInfo(null);this._updateBoundingInfo()}static _ApplySkeleton(e,t,s,i,r,n,a){!function(e,t,s,i,r,n,a){const o=Ce.Vector3[0],h=Ce.Matrix[0],l=Ce.Matrix[1],c=t===Gi.NormalKind?xe.TransformNormalFromFloatsToRef:xe.TransformCoordinatesFromFloatsToRef;for(let t=0,u=0;t<e.length;t+=3,u+=4){let d,_;for(h.reset(),d=0;d<4;d++)_=r[u+d],_>0&&(Ie.FromFloat32ArrayToRefScaled(s,Math.floor(16*i[u+d]),_,l),h.addToSelf(l));if(n&&a)for(d=0;d<4;d++)_=a[u+d],_>0&&(Ie.FromFloat32ArrayToRefScaled(s,Math.floor(16*n[u+d]),_,l),h.addToSelf(l));c(e[t],e[t+1],e[t+2],h,o),o.toArray(e,t)}}(e,t,s,i,r,n,a)}_getData(t,s,i=Gi.PositionKind){const r=t.cache,n=e=>{if(r){const t=r._vertexData||={};return t[e]||this.copyVerticesData(e,t),t[e]}return this.getVerticesData(e)};if(s||=n(i),!s)return null;r?(r._outputData?r._outputData.set(s):r._outputData=new Float32Array(s),s=r._outputData):(t.applyMorph&&this.morphTargetManager||t.applySkeleton&&this.skeleton||t.applyBakedVertexAnimation&&this.bakedVertexAnimationManager?.isEnabled)&&(s=s.slice()),t.applyMorph&&this.morphTargetManager&&function(e,t,s){let i;switch(t){case Gi.PositionKind:i=e=>e.getPositions();break;case Gi.NormalKind:i=e=>e.getNormals();break;case Gi.TangentKind:i=e=>e.getTangents();break;case Gi.UVKind:i=e=>e.getUVs();break;case Gi.UV2Kind:i=e=>e.getUV2s();break;case Gi.ColorKind:i=e=>e.getColors();break;default:return}for(let t=0;t<e.length;t++){let r=e[t];for(let n=0;n<s.numTargets;n++){const a=s.getTarget(n),o=a.influence;if(0!==o){const s=i(a);s&&(r+=(s[t]-e[t])*o)}}e[t]=r}}(s,i,this.morphTargetManager);const a=this.bakedVertexAnimationManager;let o=!1;if(t.applyBakedVertexAnimation&&a?.isEnabled){const e=n(Gi.MatricesIndicesKind),r=n(Gi.MatricesWeightsKind);if(r&&e){const h=this.numBoneInfluencers>4,l=h?n(Gi.MatricesIndicesExtraKind):null,c=h?n(Gi.MatricesWeightsExtraKind):null;o=Er(s,i,a,t.bakedVertexAnimationSettings??a.animationParameters,e,r,l,c,this.numBoneInfluencers)}}if(!o&&t.applySkeleton&&this.skeleton){const t=n(Gi.MatricesIndicesKind),r=n(Gi.MatricesWeightsKind);if(r&&t){const a=this.numBoneInfluencers>4,o=a?n(Gi.MatricesIndicesExtraKind):null,h=a?n(Gi.MatricesWeightsExtraKind):null,l=this.skeleton.getTransformMatrices(this);e._ApplySkeleton(s,i,l,t,r,o,h)}}if(!1!==t.updatePositionsArray&&i===Gi.PositionKind){const e=this._internalAbstractMeshDataInfo._positions||[],t=e.length;if(e.length=s.length/3,t<e.length)for(let s=t;s<e.length;s++)e[s]=new xe;for(let t=0,i=0;t<e.length;t++,i+=3)e[t].copyFromFloats(s[i],s[i+1],s[i+2]);this._internalAbstractMeshDataInfo._positions=e}return s}getNormalsData(e=!1,t=!1){return this._getData({applySkeleton:e,applyMorph:t,updatePositionsArray:!1},null,Gi.NormalKind)}getPositionData(e=!1,t=!1,s=null){return this._getData({applySkeleton:e,applyMorph:t,updatePositionsArray:!1},s,Gi.PositionKind)}_updateBoundingInfo(){return this._boundingInfo?this._boundingInfo.update(this.worldMatrixFromCache):this._boundingInfo=new tr(xe.Zero(),xe.Zero(),this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}_updateSubMeshesBoundingInfo(e){if(!this.subMeshes)return this;const t=this.subMeshes.length;for(let s=0;s<t;s++){const i=this.subMeshes[s];(t>1||!i.IsGlobal)&&i.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,s){const i=this.getBoundingInfo(),r=e.getBoundingInfo();if(i.intersects(r,t))return!0;if(s)for(const s of this.getChildMeshes())if(s.intersectsMesh(e,t,!0))return!0;return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e,t=!0){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const s=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=s.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,s.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId,t),this}_collideForSubMesh(e,t,s){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const s=e.verticesStart,i=e.verticesStart+e.verticesCount;for(let r=s;r<i;r++)e._lastColliderWorldVertices.push(xe.TransformCoordinates(this._positions[r],t))}return s._collide(e._trianglePlanes,e._lastColliderWorldVertices,this.getIndices(),e.indexStart,e.indexStart+e.indexCount,e.verticesStart,!!e.getMaterial(),this,this._shouldConvertRHS(),e.getMaterial()?.fillMode===dt.MATERIAL_TriangleStripDrawMode),this}_processCollisionsForSubMeshes(e,t){const s=this._scene.getCollidingSubMeshCandidates(this,e),i=s.length;for(let r=0;r<i;r++){const n=s.data[r];i>1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=Ce.Matrix[0],s=Ce.Matrix[1];return Ie.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,s),this._processCollisionsForSubMeshes(e,s),this}_generatePointsArray(){return!1}intersects(e,t,s,i=!1,r,n=!1){const a=new ur,o=this.getClassName(),h="InstancedLinesMesh"===o||"LinesMesh"===o||"GreasedLineMesh"===o?this.intersectionThreshold:0,l=this.getBoundingInfo();if(!this.subMeshes)return a;if(!(n||e.intersectsSphere(l.boundingSphere,h)&&e.intersectsBox(l.boundingBox,h)))return a;if(i)return a.hit=!n,a.pickedMesh=n?null:this,a.distance=n?0:xe.Distance(e.origin,l.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;let c=null;const u=this._scene.getIntersectingSubMeshCandidates(this,e),d=u.length;let _=!1;for(let e=0;e<d;e++){const t=u.data[e].getMaterial();if(t&&(t.fillMode==dt.MATERIAL_TriangleStripDrawMode||t.fillMode==dt.MATERIAL_TriangleFillMode||t.fillMode==dt.MATERIAL_WireFrameFillMode||t.fillMode==dt.MATERIAL_PointFillMode||t.fillMode==dt.MATERIAL_LineListDrawMode)){_=!0;break}}if(!_)return a.hit=!0,a.pickedMesh=this,a.distance=xe.Distance(e.origin,l.boundingSphere.center),a.subMeshId=-1,a;for(let i=0;i<d;i++){const r=u.data[i];if(d>1&&!n&&!r.canIntersects(e))continue;const a=r.intersects(e,this._positions,this.getIndices(),t,s);if(a&&(t||!c||a.distance<c.distance)&&(c=a,c.subMeshId=r._id,c._internalSubMeshId=i,t))break}if(c){const t=r??this.getWorldMatrix(),s=Ce.Vector3[0],i=Ce.Vector3[1];xe.TransformCoordinatesToRef(e.origin,t,s),e.direction.scaleToRef(c.distance,i);const n=xe.TransformNormal(i,t).addInPlace(s);return a.hit=!0,a.distance=xe.Distance(s,n),a.pickedPoint=n,a.pickedMesh=this,a.bu=c.bu||0,a.bv=c.bv||0,a.subMeshFaceId=c.faceId,a.faceId=c.faceId+u.data[c._internalSubMeshId].indexStart/(-1!==this.getClassName().indexOf("LinesMesh")?2:3),a.subMeshId=c.subMeshId,a}return a}clone(e,t,s){return null}releaseSubMeshes(e=!1){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose(e);else this.subMeshes=[];return this}dispose(e,t=!1){let s;const i=this.getScene();for(this._scene.useMaterialMeshMap&&this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),i.freeActiveMeshes(),i.freeRenderingGroups(),i.renderingManager.maintainStateBetweenFrames&&i.renderingManager.restoreDispachedFlags(),void 0!==this.actionManager&&null!==this.actionManager&&(this.actionManager.disposeWhenUnowned&&!this._scene.meshes.some(e=>e!==this&&e.actionManager===this.actionManager)&&this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),s=0;s<this._intersectionsInProgress.length;s++){const e=this._intersectionsInProgress[s],t=e._intersectionsInProgress.indexOf(this);e._intersectionsInProgress.splice(t,1)}this._intersectionsInProgress.length=0;const r=i.lights;for(const e of r){let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(this),-1!==t&&e.excludedMeshes.splice(t,1);const s=e.getShadowGenerators();if(s){const e=s.values();for(let s=e.next();!0!==s.done;s=e.next()){const e=s.value.getShadowMap();e&&e.renderList&&(t=e.renderList.indexOf(this),-1!==t&&e.renderList.splice(t,1))}}}this.releaseSubMeshes(i._isDisposing);const n=i.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,n.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),n.wipeCaches(),i.removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(s=0;s<i.particleSystems.length;s++)i.particleSystems[s].emitter===this&&(i.particleSystems[s].dispose(),s--);this._internalAbstractMeshDataInfo._facetData.facetDataEnabled&&this.disableFacetData(),this._uniformBuffer.dispose(),this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this.onRebuildObservable.clear(),super.dispose(e,t)}_initFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;e.facetNormals||(e.facetNormals=[]),e.facetPositions||(e.facetPositions=[]),e.facetPartitioning||(e.facetPartitioning=new Array),e.facetNb=this.getIndices().length/3|0,e.partitioningSubdivisions=e.partitioningSubdivisions?e.partitioningSubdivisions:10,e.partitioningBBoxRatio=e.partitioningBBoxRatio?e.partitioningBBoxRatio:1.01;for(let t=0;t<e.facetNb;t++)e.facetNormals[t]=xe.Zero(),e.facetPositions[t]=xe.Zero();return e.facetDataEnabled=!0,this}updateFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();const t=this.getVerticesData(Gi.PositionKind),s=this.getIndices(),i=this.getVerticesData(Gi.NormalKind)?.slice(),r=this.getBoundingInfo();if(e.facetDepthSort&&!e.facetDepthSortEnabled){if(e.facetDepthSortEnabled=!0,s instanceof Uint16Array)e.depthSortedIndices=new Uint16Array(s);else if(s instanceof Uint32Array)e.depthSortedIndices=new Uint32Array(s);else{let t=!1;for(let e=0;e<s.length;e++)if(s[e]>65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(s):new Uint16Array(s)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:xe.Zero()}e.depthSortedFacets=[];for(let t=0;t<e.facetNb;t++){const s={ind:3*t,sqDistance:0};e.depthSortedFacets.push(s)}e.invertedMatrix=Ie.Identity(),e.facetDepthSortOrigin=xe.Zero()}e.bbSize.x=r.maximum.x-r.minimum.x>j?r.maximum.x-r.minimum.x:j,e.bbSize.y=r.maximum.y-r.minimum.y>j?r.maximum.y-r.minimum.y:j,e.bbSize.z=r.maximum.z-r.minimum.z>j?r.maximum.z-r.minimum.z:j;let n=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(n=n>e.bbSize.z?n:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/n),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/n),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/n),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),xe.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,i&&or.ComputeNormals(t,s,i,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let i=0;i<t;i++){const t=e.depthSortedFacets[i].ind;e.depthSortedIndices[3*i]=s[t],e.depthSortedIndices[3*i+1]=s[t+1],e.depthSortedIndices[3*i+2]=s[t+2]}this.updateIndices(e.depthSortedIndices,void 0,!0)}return this}getFacetLocalNormals(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetNormals||this.updateFacetData(),e.facetNormals}getFacetLocalPositions(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetPositions||this.updateFacetData(),e.facetPositions}getFacetLocalPartitioning(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetPartitioning||this.updateFacetData(),e.facetPartitioning}getFacetPosition(e){const t=xe.Zero();return this.getFacetPositionToRef(e,t),t}getFacetPositionToRef(e,t){const s=this.getFacetLocalPositions()[e],i=this.getWorldMatrix();return xe.TransformCoordinatesToRef(s,i,t),this}getFacetNormal(e){const t=xe.Zero();return this.getFacetNormalToRef(e,t),t}getFacetNormalToRef(e,t){const s=this.getFacetLocalNormals()[e];return xe.TransformNormalToRef(s,this.getWorldMatrix(),t),this}getFacetsAtLocalCoordinates(e,t,s){const i=this.getBoundingInfo(),r=this._internalAbstractMeshDataInfo._facetData,n=Math.floor((e-i.minimum.x*r.partitioningBBoxRatio)*r.subDiv.X*r.partitioningBBoxRatio/r.bbSize.x),a=Math.floor((t-i.minimum.y*r.partitioningBBoxRatio)*r.subDiv.Y*r.partitioningBBoxRatio/r.bbSize.y),o=Math.floor((s-i.minimum.z*r.partitioningBBoxRatio)*r.subDiv.Z*r.partitioningBBoxRatio/r.bbSize.z);return n<0||n>r.subDiv.max||a<0||a>r.subDiv.max||o<0||o>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*a+r.subDiv.max*r.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,s,i,r=!1,n=!0){const a=this.getWorldMatrix(),o=Ce.Matrix[5];a.invertToRef(o);const h=Ce.Vector3[8];xe.TransformCoordinatesFromFloatsToRef(e,t,s,o,h);const l=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,i,r,n);return i&&xe.TransformCoordinatesFromFloatsToRef(i.x,i.y,i.z,a,i),l}getClosestFacetAtLocalCoordinates(e,t,s,i,r=!1,n=!0){let a,o,h,l,c,u,d,_,p=null;const f=this.getFacetLocalPositions(),g=this.getFacetLocalNormals(),m=this.getFacetsAtLocalCoordinates(e,t,s);if(!m)return null;let T,E,R,b,A=Number.MAX_VALUE;for(let y=0;y<m.length;y++)E=m[y],R=g[E],b=f[E],l=(e-b.x)*R.x+(t-b.y)*R.y+(s-b.z)*R.z,(!r||r&&n&&l>=0||r&&!n&&l<=0)&&(l=R.x*b.x+R.y*b.y+R.z*b.z,c=-(R.x*e+R.y*t+R.z*s-l)/(R.x*R.x+R.y*R.y+R.z*R.z),u=e+R.x*c,d=t+R.y*c,_=s+R.z*c,a=u-e,o=d-t,h=_-s,T=a*a+o*o+h*h,T<A&&(A=T,p=E,i&&(i.x=u,i.y=d,i.z=_)));return p}getFacetDataParameters(){return this._internalAbstractMeshDataInfo._facetData.facetParameters}disableFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetDataEnabled&&(e.facetDataEnabled=!1,e.facetPositions=[],e.facetNormals=[],e.facetPartitioning=new Array,e.facetParameters={},e.depthSortedIndices=new Uint32Array(0)),this}updateIndices(e,t,s=!1){return this}createNormals(e){const t=this.getVerticesData(Gi.PositionKind),s=this.getIndices();let i;return i=this.isVerticesDataPresent(Gi.NormalKind)?this.getVerticesData(Gi.NormalKind):[],or.ComputeNormals(t,s,i,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(Gi.NormalKind,i,e),this}async optimizeIndicesAsync(){const e=this.getIndices();if(!e)return this;const{OptimizeIndices:t}=await import("./mesh.vertexData.functions-D0Kx5Kh7.esm.min.js");return t(e),this.setIndices(e,this.getTotalVertices()),this}alignWithNormal(e,t){t||(t=gr.Y);const s=Ce.Vector3[0],i=Ce.Vector3[1];return xe.CrossToRef(t,e,i),xe.CrossToRef(e,i,s),this.rotationQuaternion?ve.RotationQuaternionFromAxisToRef(s,e,i,this.rotationQuaternion):xe.RotationFromAxisToRef(s,e,i,this.rotation),this}_checkOcclusionQuery(e=!1){return!1}disableEdgesRendering(){throw Le("EdgesRenderer")}enableEdgesRendering(e,t,s){throw Le("EdgesRenderer")}getConnectedParticleSystems(){return this._scene.particleSystems.filter(e=>e.emitter===this)}},(()=>{const r="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;t=[W.filter((...e)=>!(Array.isArray(e[0])||Array.isArray(e[3])||Array.isArray(e[4])||Array.isArray(e[5])||Array.isArray(e[6])))],b(e,null,t,{kind:"method",name:"_ApplySkeleton",static:!0,private:!1,access:{has:e=>"_ApplySkeleton"in e,get:e=>e._ApplySkeleton},metadata:r},null,i),r&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:r})})(),e.OCCLUSION_TYPE_NONE=(A(e,i),0),e.OCCLUSION_TYPE_OPTIMISTIC=1,e.OCCLUSION_TYPE_STRICT=2,e.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,e.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,e.CULLINGSTRATEGY_STANDARD=dt.MESHES_CULLINGSTRATEGY_STANDARD,e.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=dt.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,e.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=dt.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION,e.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=dt.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY,e.DefaultIsPickable=!0,e})();Ar.prototype.createOrUpdateSubmeshesOctree??=Ne("AbstractMesh","createOrUpdateSubmeshesOctree"),Ar.prototype.getPhysicsImpostor??=Ne("AbstractMesh","getPhysicsImpostor"),Ar.prototype.setPhysicsLinkWith??=Ne("AbstractMesh","setPhysicsLinkWith"),Object.getOwnPropertyDescriptor(Ar.prototype,"occlusionRetryCount")||Object.defineProperty(Ar.prototype,"occlusionRetryCount",Ue(0,"occlusionRetryCount")),Object.getOwnPropertyDescriptor(Ar.prototype,"occlusionType")||Object.defineProperty(Ar.prototype,"occlusionType",Ue(0,"occlusionType")),Object.getOwnPropertyDescriptor(Ar.prototype,"occlusionQueryAlgorithmType")||Object.defineProperty(Ar.prototype,"occlusionQueryAlgorithmType",Ue(0,"occlusionQueryAlgorithmType")),Object.getOwnPropertyDescriptor(Ar.prototype,"isOccluded")||Object.defineProperty(Ar.prototype,"isOccluded",Ue(0,"isOccluded")),Object.getOwnPropertyDescriptor(Ar.prototype,"isOcclusionQueryInProgress")||Object.defineProperty(Ar.prototype,"isOcclusionQueryInProgress",Ue(0,"isOcclusionQueryInProgress")),Object.getOwnPropertyDescriptor(Ar.prototype,"forceRenderingWhenOccluded")||Object.defineProperty(Ar.prototype,"forceRenderingWhenOccluded",Ue(0,"forceRenderingWhenOccluded")),Object.getOwnPropertyDescriptor(Ar.prototype,"occlusionForRenderPassId")||Object.defineProperty(Ar.prototype,"occlusionForRenderPassId",Ue(0,"occlusionForRenderPassId")),Object.getOwnPropertyDescriptor(Ar.prototype,"decalMap")||Object.defineProperty(Ar.prototype,"decalMap",Ue(0,"decalMap")),Object.getOwnPropertyDescriptor(Ar.prototype,"instancedBuffers")||Object.defineProperty(Ar.prototype,"instancedBuffers",Ue(0,"instancedBuffers")),Object.getOwnPropertyDescriptor(Ar.prototype,"physicsImpostor")||Object.defineProperty(Ar.prototype,"physicsImpostor",Ue(0,"physicsImpostor")),Object.getOwnPropertyDescriptor(Ar.prototype,"showBoundingBox")||Object.defineProperty(Ar.prototype,"showBoundingBox",Ue(0,"showBoundingBox")),Object.getOwnPropertyDescriptor(Ar.prototype,"edgesRenderer")||Object.defineProperty(Ar.prototype,"edgesRenderer",Ue(0,"edgesRenderer")),Object.getOwnPropertyDescriptor(Ar.prototype,"renderOutline")||Object.defineProperty(Ar.prototype,"renderOutline",Ue(0,"renderOutline")),Object.getOwnPropertyDescriptor(Ar.prototype,"renderOverlay")||Object.defineProperty(Ar.prototype,"renderOverlay",Ue(0,"renderOverlay"));let yr=(()=>{var e;let t,s,i,r,n,a,o,h,l,c,u,d,_=[];return e=class{constructor(){this._func=A(this,_),this.reset()}reset(){this.enabled=!1,this.mask=255,this.funcRef=1,this.funcMask=255,this.func=dt.ALWAYS,this.opStencilFail=dt.KEEP,this.opDepthFail=dt.KEEP,this.opStencilDepthPass=dt.REPLACE,this.backFunc=dt.ALWAYS,this.backOpStencilFail=dt.KEEP,this.backOpDepthFail=dt.KEEP,this.backOpStencilDepthPass=dt.REPLACE}get func(){return this._func}set func(e){this._func=e}get backFunc(){return this._backFunc}set backFunc(e){this._backFunc=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get backOpStencilFail(){return this._backOpStencilFail}set backOpStencilFail(e){this._backOpStencilFail=e}get backOpDepthFail(){return this._backOpDepthFail}set backOpDepthFail(e){this._backOpDepthFail=e}get backOpStencilDepthPass(){return this._backOpStencilDepthPass}set backOpStencilDepthPass(e){this._backOpStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){$e.Clone(()=>e,this)}serialize(){return $e.Serialize(this)}parse(e,t,s){$e.Parse(()=>this,e,t,s)}},(()=>{const p="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[L()],s=[L()],i=[L()],r=[L()],n=[L()],a=[L()],o=[L()],h=[L()],l=[L()],c=[L()],u=[L()],d=[L()],b(e,null,t,{kind:"getter",name:"func",static:!1,private:!1,access:{has:e=>"func"in e,get:e=>e.func},metadata:p},null,_),b(e,null,s,{kind:"getter",name:"backFunc",static:!1,private:!1,access:{has:e=>"backFunc"in e,get:e=>e.backFunc},metadata:p},null,_),b(e,null,i,{kind:"getter",name:"funcRef",static:!1,private:!1,access:{has:e=>"funcRef"in e,get:e=>e.funcRef},metadata:p},null,_),b(e,null,r,{kind:"getter",name:"funcMask",static:!1,private:!1,access:{has:e=>"funcMask"in e,get:e=>e.funcMask},metadata:p},null,_),b(e,null,n,{kind:"getter",name:"opStencilFail",static:!1,private:!1,access:{has:e=>"opStencilFail"in e,get:e=>e.opStencilFail},metadata:p},null,_),b(e,null,a,{kind:"getter",name:"opDepthFail",static:!1,private:!1,access:{has:e=>"opDepthFail"in e,get:e=>e.opDepthFail},metadata:p},null,_),b(e,null,o,{kind:"getter",name:"opStencilDepthPass",static:!1,private:!1,access:{has:e=>"opStencilDepthPass"in e,get:e=>e.opStencilDepthPass},metadata:p},null,_),b(e,null,h,{kind:"getter",name:"backOpStencilFail",static:!1,private:!1,access:{has:e=>"backOpStencilFail"in e,get:e=>e.backOpStencilFail},metadata:p},null,_),b(e,null,l,{kind:"getter",name:"backOpDepthFail",static:!1,private:!1,access:{has:e=>"backOpDepthFail"in e,get:e=>e.backOpDepthFail},metadata:p},null,_),b(e,null,c,{kind:"getter",name:"backOpStencilDepthPass",static:!1,private:!1,access:{has:e=>"backOpStencilDepthPass"in e,get:e=>e.backOpStencilDepthPass},metadata:p},null,_),b(e,null,u,{kind:"getter",name:"mask",static:!1,private:!1,access:{has:e=>"mask"in e,get:e=>e.mask},metadata:p},null,_),b(e,null,d,{kind:"getter",name:"enabled",static:!1,private:!1,access:{has:e=>"enabled"in e,get:e=>e.enabled},metadata:p},null,_),p&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:p})})(),e})();class Mr{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}Mr.FALLOFF_DEFAULT=0,Mr.FALLOFF_PHYSICAL=1,Mr.FALLOFF_GLTF=2,Mr.FALLOFF_STANDARD=3,Mr.LIGHTMAP_DEFAULT=0,Mr.LIGHTMAP_SPECULAR=1,Mr.LIGHTMAP_SHADOWSONLY=2,Mr.INTENSITYMODE_AUTOMATIC=0,Mr.INTENSITYMODE_LUMINOUSPOWER=1,Mr.INTENSITYMODE_LUMINOUSINTENSITY=2,Mr.INTENSITYMODE_ILLUMINANCE=3,Mr.INTENSITYMODE_LUMINANCE=4,Mr.LIGHTTYPEID_POINTLIGHT=0,Mr.LIGHTTYPEID_DIRECTIONALLIGHT=1,Mr.LIGHTTYPEID_SPOTLIGHT=2,Mr.LIGHTTYPEID_HEMISPHERICLIGHT=3,Mr.LIGHTTYPEID_RECT_AREALIGHT=4,Mr.LIGHTTYPEID_CLUSTERED_CONTAINER=5;const xr=new Ie,Sr=new Ie,vr=new Ie,Ir={getScene:()=>{},eyeAtCamera:!0};function Pr(e,t,s){const i=s.asArray(),r=t.asArray();for(let e=0;e<16;e++)i[e]=r[e];return i[12]-=e.x,i[13]-=e.y,i[14]-=e.z,s.markAsUpdated(),s}function Cr(e,t,s){return Te(t,Sr),Pr(e,Sr,vr),Te(vr,s),s}function Or(e,t,s){if(!Ir.eyeAtCamera)return Cr(e,t,s);const i=s.asArray(),r=t.asArray();for(let e=0;e<16;e++)i[e]=r[e];return i[12]=0,i[13]=0,i[14]=0,s.markAsUpdated(),s}function Dr(e,t,s,i){return me(Or(e,t,i),s,i),i}function wr(e,t,s,i){return Te(s,Sr),me(t,Sr,vr),Pr(e,vr,Sr),Or(e,s,vr),me(Sr,vr,i),i}function Lr(e,t,s,i){return Cr(e,t,vr),me(vr,s,i),i}function Fr(e,t,s,i,r,n){return Te(s,Sr),me(t,Sr,vr),Pr(e,vr,Sr),Dr(e,i,r,vr),me(Sr,vr,n),n}function Nr(e,t){const s=Ir.getScene();if(!s||xr===t)return t;xr.updateFlag=t.updateFlag;const i=s.floatingOriginOffset;switch(e){case"world":return Pr(i,t,xr);case"view":return Or(i,t,xr);case"worldView":return wr(i,t,s.getViewMatrix(),xr);case"viewProjection":return Dr(i,s.getViewMatrix(),s.getProjectionMatrix(),xr);case"worldViewProjection":return Fr(i,t,s.getTransformMatrix(),s.getViewMatrix(),s.getProjectionMatrix(),xr);default:if(e.startsWith("u_")){const r=e.toLowerCase();if(r.startsWith("u_worldviewprojection"))return Fr(i,t,s.getTransformMatrix(),s.getViewMatrix(),s.getProjectionMatrix(),xr);if(r.startsWith("u_viewprojection"))return Dr(i,s.getViewMatrix(),s.getProjectionMatrix(),xr);if(r.startsWith("u_worldview"))return wr(i,t,s.getViewMatrix(),xr);if(r.startsWith("u_world"))return Pr(i,t,xr);if(r.startsWith("u_view"))return Or(i,t,xr)}return t}}const Br=dr,Ur=li,kr=Br.prototype._updateMatrixForUniform,Gr=li.prototype.setMatrix;function Vr(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function Hr(e,t,s){const i=!!(e.clipPlane??t.clipPlane),r=!!(e.clipPlane2??t.clipPlane2),n=!!(e.clipPlane3??t.clipPlane3),a=!!(e.clipPlane4??t.clipPlane4),o=!!(e.clipPlane5??t.clipPlane5),h=!!(e.clipPlane6??t.clipPlane6);i&&s.push("#define CLIPPLANE"),r&&s.push("#define CLIPPLANE2"),n&&s.push("#define CLIPPLANE3"),a&&s.push("#define CLIPPLANE4"),o&&s.push("#define CLIPPLANE5"),h&&s.push("#define CLIPPLANE6")}function zr(e,t,s){let i=t.clipPlane??s.clipPlane;Wr(e,"vClipPlane",i),i=t.clipPlane2??s.clipPlane2,Wr(e,"vClipPlane2",i),i=t.clipPlane3??s.clipPlane3,Wr(e,"vClipPlane3",i),i=t.clipPlane4??s.clipPlane4,Wr(e,"vClipPlane4",i),i=t.clipPlane5??s.clipPlane5,Wr(e,"vClipPlane5",i),i=t.clipPlane6??s.clipPlane6,Wr(e,"vClipPlane6",i)}function Wr(e,t,s){if(s){const i=Ir.getScene()?.floatingOriginOffset||xe.ZeroReadOnly;e.setFloat4(t,s.normal.x,s.normal.y,s.normal.z,s.d+xe.Dot(s.normal,i))}}class Xr{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get BaseWeightTextureEnabled(){return this._BaseWeightTextureEnabled}static set BaseWeightTextureEnabled(e){this._BaseWeightTextureEnabled!==e&&(this._BaseWeightTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get BaseDiffuseRoughnessTextureEnabled(){return this._BaseDiffuseRoughnessTextureEnabled}static set BaseDiffuseRoughnessTextureEnabled(e){this._BaseDiffuseRoughnessTextureEnabled!==e&&(this._BaseDiffuseRoughnessTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_FresnelDirtyFlag))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get TranslucencyIntensityTextureEnabled(){return this._TranslucencyIntensityTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get TranslucencyColorTextureEnabled(){return this._TranslucencyColorTextureEnabled}static set TranslucencyColorTextureEnabled(e){this._TranslucencyColorTextureEnabled!==e&&(this._TranslucencyColorTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,Ti.MarkAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}}function Kr(e,t,s){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=s.activeCamera;e.mode===dt.ORTHOGRAPHIC_CAMERA&&a.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}Xr._DiffuseTextureEnabled=!0,Xr._BaseWeightTextureEnabled=!0,Xr._BaseDiffuseRoughnessTextureEnabled=!0,Xr._DetailTextureEnabled=!0,Xr._DecalMapEnabled=!0,Xr._AmbientTextureEnabled=!0,Xr._OpacityTextureEnabled=!0,Xr._ReflectionTextureEnabled=!0,Xr._EmissiveTextureEnabled=!0,Xr._SpecularTextureEnabled=!0,Xr._BumpTextureEnabled=!0,Xr._LightmapTextureEnabled=!0,Xr._RefractionTextureEnabled=!0,Xr._ColorGradingTextureEnabled=!0,Xr._FresnelEnabled=!0,Xr._ClearCoatTextureEnabled=!0,Xr._ClearCoatBumpTextureEnabled=!0,Xr._ClearCoatTintTextureEnabled=!0,Xr._SheenTextureEnabled=!0,Xr._AnisotropicTextureEnabled=!0,Xr._ThicknessTextureEnabled=!0,Xr._RefractionIntensityTextureEnabled=!0,Xr._TranslucencyIntensityTextureEnabled=!0,Xr._TranslucencyColorTextureEnabled=!0,Xr._IridescenceTextureEnabled=!0;const Yr={r:0,g:0,b:0},jr={NUM_MORPH_INFLUENCERS:0,NORMAL:!1,TANGENT:!1,UV:!1,UV2:!1,COLOR:!1};function qr(e,t,s,i=!1){s&&e.fogEnabled&&(!t||t.applyFog)&&e.fogMode!==dt.FOGMODE_NONE&&(s.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),i?(e.fogColor.toLinearSpaceToRef(Yr,e.getEngine().useExactSrgbConversions),s.setColor3("vFogColor",Yr)):s.setColor3("vFogColor",e.fogColor))}function $r(e,t,s,i,r,n,a,o,h,l){const c=e.numMaxInfluencers||e.numInfluencers;return c<=0?0:(t.push("#define MORPHTARGETS"),e.hasPositions&&t.push("#define MORPHTARGETTEXTURE_HASPOSITIONS"),e.hasNormals&&t.push("#define MORPHTARGETTEXTURE_HASNORMALS"),e.hasTangents&&t.push("#define MORPHTARGETTEXTURE_HASTANGENTS"),e.hasUVs&&t.push("#define MORPHTARGETTEXTURE_HASUVS"),e.hasUV2s&&t.push("#define MORPHTARGETTEXTURE_HASUV2S"),e.hasColors&&t.push("#define MORPHTARGETTEXTURE_HASCOLORS"),e.supportsPositions&&r&&t.push("#define MORPHTARGETS_POSITION"),e.supportsNormals&&n&&t.push("#define MORPHTARGETS_NORMAL"),e.supportsTangents&&a&&t.push("#define MORPHTARGETS_TANGENT"),e.supportsUVs&&o&&t.push("#define MORPHTARGETS_UV"),e.supportsUV2s&&h&&t.push("#define MORPHTARGETS_UV2"),e.supportsColors&&l&&t.push("#define MORPHTARGETS_COLOR"),t.push("#define NUM_MORPH_INFLUENCERS "+c),e.isUsingTextureForTargets&&t.push("#define MORPHTARGETS_TEXTURE"),jr.NUM_MORPH_INFLUENCERS=c,jr.NORMAL=n,jr.TANGENT=a,jr.UV=o,jr.UV2=h,jr.COLOR=l,Zr(s,i,jr,r),c)}function Zr(e,t,s,i=!0){const r=s.NUM_MORPH_INFLUENCERS;if(r>0&&ee.LastCreatedEngine){const n=ee.LastCreatedEngine.getCaps().maxVertexAttribs,o=t.morphTargetManager;if(o?.isUsingTextureForTargets)return;const h=o&&o.supportsPositions&&i,l=o&&o.supportsNormals&&s.NORMAL,c=o&&o.supportsTangents&&s.TANGENT,u=o&&o.supportsUVs&&s.UV1,d=o&&o.supportsUV2s&&s.UV2,_=o&&o.supportsColors&&s.VERTEXCOLOR;for(let s=0;s<r;s++)h&&e.push(dt.PositionKind+s),l&&e.push(dt.NormalKind+s),c&&e.push(dt.TangentKind+s),u&&e.push(dt.UVKind+"_"+s),d&&e.push(dt.UV2Kind+"_"+s),_&&e.push(dt.ColorKind+s),e.length>n&&a.Error("Cannot add more vertex attributes for mesh "+t.name)}}function Qr(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}function Jr(e,t){const s=e.morphTargetManager;e&&s&&t.setFloatArray("morphTargetInfluences",s.influences)}function en(e,t){t.bindToEffect(e,"Scene")}function tn(e,t,s,i,r=null,n=!1,a=!1,o=!1,h=!1,l=!1,c=!1,u=0){if(e.texturesEnabled&&r&&Xr.ReflectionTextureEnabled){if(s.updateMatrix("reflectionMatrix",r.getReflectionTextureMatrix()),s.updateFloat2("vReflectionInfos",r.level*e.iblIntensity,u),o&&r.boundingBoxSize){const e=r;s.updateVector3("vReflectionPosition",e.boundingBoxPosition),s.updateVector3("vReflectionSize",e.boundingBoxSize)}if(n){const e=r.getSize().width;s.updateFloat2("vReflectionFilteringInfo",e,Math.log2(e))}if(l&&!t.USEIRRADIANCEMAP){const e=r.sphericalPolynomial;if(t.USESPHERICALFROMREFLECTIONMAP&&e)if(t.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;s.updateVector3("vSphericalL00",t.l00),s.updateVector3("vSphericalL1_1",t.l1_1),s.updateVector3("vSphericalL10",t.l10),s.updateVector3("vSphericalL11",t.l11),s.updateVector3("vSphericalL2_2",t.l2_2),s.updateVector3("vSphericalL2_1",t.l2_1),s.updateVector3("vSphericalL20",t.l20),s.updateVector3("vSphericalL21",t.l21),s.updateVector3("vSphericalL22",t.l22)}else s.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),s.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),s.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),s.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),s.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),s.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),s.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),s.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),s.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}else h&&t.USEIRRADIANCEMAP&&t.USE_IRRADIANCE_DOMINANT_DIRECTION&&r.irradianceTexture&&s.updateVector3("vReflectionDominantDirection",r.irradianceTexture._dominantDirection);a&&s.updateFloat3("vReflectionMicrosurfaceInfos",r.getSize().width,r.lodGenerationScale,r.lodGenerationOffset)}c&&s.updateColor3("vReflectionColor",i)}function sn(e,t,s,i=null,r=!1){if(i&&Xr.ReflectionTextureEnabled){t.LODBASEDMICROSFURACE?s.setTexture("reflectionSampler",i):(s.setTexture("reflectionSampler",i._lodTextureMid||i),s.setTexture("reflectionSamplerLow",i._lodTextureLow||i),s.setTexture("reflectionSamplerHigh",i._lodTextureHigh||i)),t.USEIRRADIANCEMAP&&s.setTexture("irradianceSampler",i.irradianceTexture);const n=e.iblCdfGenerator;r&&n&&s.setTexture("icdfSampler",n.getIcdfTexture())}}function rn(e,t,s){t._needUVs=!0,t[s]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[s+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[s+"DIRECTUV"]=0}function nn(e,t,s){const i=e.getTextureMatrix();t.updateMatrix(s+"Matrix",i)}function an(e,t,s){s.BAKED_VERTEX_ANIMATION_TEXTURE&&s.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}function on(e,t,s){var i;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const r=e.skeleton;if(r.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureInfo")>-1){const s=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",s),t.setFloat2("boneTextureInfo",r._textureWidth,r._textureHeight)}else{const n=r.getTransformMatrices(e);n&&(t.setMatrices("mBones",n),s&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(dt.PREPASS_VELOCITY_TEXTURE_TYPE)&&(s.previousBones[e.uniqueId]||(s.previousBones[e.uniqueId]=n.slice()),t.setMatrices("mPreviousBones",s.previousBones[e.uniqueId]),i=n,s.previousBones[e.uniqueId].set(i)))}}}function hn(e,t,s,i,r,n=!0){e._bindLight(t,s,i,r,n)}const ln=new WeakMap;function cn(e,t,s,i,r=4){const n=Math.min(t.lightSources.length,r);for(let r=0;r<n;r++){hn(t.lightSources[r],r,e,s,"boolean"==typeof i?i:i.SPECULARTERM,t.receiveShadows)}}function un(e,t,s,i){s.NUM_BONE_INFLUENCERS>0&&(i.addCPUSkinningFallback(0,t),e.push(dt.MatricesIndicesKind),e.push(dt.MatricesWeightsKind),s.NUM_BONE_INFLUENCERS>4&&(e.push(dt.MatricesIndicesExtraKind),e.push(dt.MatricesWeightsExtraKind)))}function dn(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&Qr(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(dt.ColorInstanceKind)}function _n(e,t,s=4,i=0){let r=0;for(let n=0;n<s&&e["LIGHT"+n];n++)n>0&&(r=i+n,t.addFallback(r,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(i,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(i,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(i,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(i,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(i,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(i,"SHADOWCLOSEESM"+n));return r}function pn(e,t,s,i,r,n,a,o=!1,h=!1,l,c){if(a._areMiscDirty){a.LOGARITHMICDEPTH=s,a.POINTSIZE=i,a.FOG=r&&function(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==dt.FOGMODE_NONE}(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=n,a.DECAL_AFTER_DETAIL=o,a.USE_VERTEX_PULLING=h,a.RIGHT_HANDED=t.useRightHandedSystem;const u=l?.geometry?.getIndexBuffer(),d=!!l&&l.isUnIndexed;a.VERTEX_PULLING_USE_INDEX_BUFFER=!!u&&!d,a.VERTEX_PULLING_INDEX_BUFFER_32BITS=!(!u||d)&&u.is32Bits,a.VERTEXOUTPUT_INVARIANT=!!c}}function fn(e,t,s,i=!1){if(!e.lightsEnabled||i)return!0;const r=t.lightSources,n=Math.min(r.length,s);for(let e=0;e<n;e++)if(!r[e].areLightTexturesReady())return!1;return!0}function gn(e,t,s,i,r=4,n=!1){if(!s._areLightsDirty)return s._needNormals;const o=r;r=function(e,t){const s=e.getEngine().getCaps().maxUniformBuffersPerShaderStage;if(null==s)return t;const i=Math.max(s-4,1);return Math.min(t,i)}(e,r);let h=0;const l={needNormals:s._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n){t.lightSources.length>r&&r<o&&function(e,t,s,i){let r=ln.get(e);r||(r=new Set,ln.set(e,r)),r.has(i)||(r.add(i),a.Warn(`maxSimultaneousLights is ${t} but this engine supports at most ${s} simultaneous lights. Each light declares its own uniform buffer in the vertex shader, so the ${i} lights affecting this mesh plus the scene, mesh, material and leftover buffers would need ${i+4} uniform buffers, over the device limit of ${e.getCaps().maxUniformBuffersPerShaderStage} per shader stage. The light count has been clamped to ${s}, so the extra lights will not contribute to the render. Set maxSimultaneousLights to ${s} or less to silence this warning.`))}(e.getEngine(),o,r,Math.min(t.lightSources.length,o));for(const n of t.lightSources)if(Tn(e,t,n,h,s,i,l),h++,h===r)break}s.SPECULARTERM=l.specularEnabled,s.SHADOWS=l.shadowEnabled;const c=Math.max(r,s.MAXLIGHTCOUNT||0);for(let e=h;e<c;e++)void 0!==s["LIGHT"+e]&&(s["LIGHT"+e]=!1,s["HEMILIGHT"+e]=!1,s["POINTLIGHT"+e]=!1,s["DIRLIGHT"+e]=!1,s["SPOTLIGHT"+e]=!1,s["AREALIGHT"+e]=!1,s["CLUSTLIGHT"+e]=!1,s["SHADOW"+e]=!1,s["SHADOWCSM"+e]=!1,s["SHADOWCSMDEBUG"+e]=!1,s["SHADOWCSMNUM_CASCADES"+e]=!1,s["SHADOWCSMUSESHADOWMAXZ"+e]=!1,s["SHADOWCSMNOBLEND"+e]=!1,s["SHADOWCSM_RIGHTHANDED"+e]=!1,s["SHADOWPCF"+e]=!1,s["SHADOWPCSS"+e]=!1,s["SHADOWPOISSON"+e]=!1,s["SHADOWESM"+e]=!1,s["SHADOWCLOSEESM"+e]=!1,s["SHADOWCUBE"+e]=!1,s["SHADOWLOWQUALITY"+e]=!1,s["SHADOWMEDIUMQUALITY"+e]=!1);s.LIGHTCOUNT=h,s.MAXLIGHTCOUNT=r;const u=e.getEngine().getCaps();return void 0===s.SHADOWFLOAT&&(l.needRebuild=!0),s.SHADOWFLOAT=l.shadowEnabled&&(u.textureFloatRender&&u.textureFloatLinearFiltering||u.textureHalfFloatRender&&u.textureHalfFloatLinearFiltering),s.LIGHTMAPEXCLUDED=l.lightmapMode,l.needRebuild&&s.rebuild(),l.needNormals}function mn(e,t,s,i=!1,r=dt.TEXTURE_FILTERING_QUALITY_LOW,n=!1){if(t&&Xr.ReflectionTextureEnabled){if(!t.isReadyOrNotBlocking())return!1;s._needNormals=!0,s.REFLECTION=!0,s.GAMMAREFLECTION=t.gammaSpace,s.RGBDREFLECTION=t.isRGBD,s.LODINREFLECTIONALPHA=t.lodLevelInAlpha,s.LINEARSPECULARREFLECTION=t.linearSpecularLOD,s.USEIRRADIANCEMAP=!1,s.LODBASEDMICROSFURACE=e.getEngine().getCaps().textureLOD;const a=e.getEngine();switch(i&&r>0?(s.NUM_SAMPLES=""+r,a._features.needTypeSuffixInShaderConstants&&(s.NUM_SAMPLES=s.NUM_SAMPLES+"u"),s.REALTIME_FILTERING=!0,e.iblCdfGenerator&&(s.IBL_CDF_FILTERING=!0)):s.REALTIME_FILTERING=!1,s.INVERTCUBICMAP=t.coordinatesMode===dt.TEXTURE_INVCUBIC_MODE,s.REFLECTIONMAP_3D=t.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&e.useRightHandedSystem?!t.invertZ:t.invertZ,s.REFLECTIONMAP_CUBIC=!1,s.REFLECTIONMAP_EXPLICIT=!1,s.REFLECTIONMAP_PLANAR=!1,s.REFLECTIONMAP_PROJECTION=!1,s.REFLECTIONMAP_SKYBOX=!1,s.REFLECTIONMAP_SPHERICAL=!1,s.REFLECTIONMAP_EQUIRECTANGULAR=!1,s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.coordinatesMode){case dt.TEXTURE_EXPLICIT_MODE:s.REFLECTIONMAP_EXPLICIT=!0;break;case dt.TEXTURE_PLANAR_MODE:s.REFLECTIONMAP_PLANAR=!0;break;case dt.TEXTURE_PROJECTION_MODE:s.REFLECTIONMAP_PROJECTION=!0;break;case dt.TEXTURE_SKYBOX_MODE:s.REFLECTIONMAP_SKYBOX=!0;break;case dt.TEXTURE_SPHERICAL_MODE:s.REFLECTIONMAP_SPHERICAL=!0;break;case dt.TEXTURE_EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case dt.TEXTURE_FIXED_EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case dt.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case dt.TEXTURE_CUBIC_MODE:case dt.TEXTURE_INVCUBIC_MODE:default:s.REFLECTIONMAP_CUBIC=!0,s.USE_LOCAL_REFLECTIONMAP_CUBIC=!!t.boundingBoxSize}t.coordinatesMode!==dt.TEXTURE_SKYBOX_MODE&&(t.irradianceTexture?(s.USEIRRADIANCEMAP=!0,s.USESPHERICALFROMREFLECTIONMAP=!1,s.USESPHERICALINVERTEX=!1,t.irradianceTexture._dominantDirection?s.USE_IRRADIANCE_DOMINANT_DIRECTION=!0:s.USE_IRRADIANCE_DOMINANT_DIRECTION=!1):t.isCube&&(s.USESPHERICALFROMREFLECTIONMAP=!0,s.USEIRRADIANCEMAP=!1,s.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,s.USESPHERICALINVERTEX=n))}else s.REFLECTION=!1,s.REFLECTIONMAP_3D=!1,s.REFLECTIONMAP_SPHERICAL=!1,s.REFLECTIONMAP_PLANAR=!1,s.REFLECTIONMAP_CUBIC=!1,s.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,s.REFLECTIONMAP_PROJECTION=!1,s.REFLECTIONMAP_SKYBOX=!1,s.REFLECTIONMAP_EXPLICIT=!1,s.REFLECTIONMAP_EQUIRECTANGULAR=!1,s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,s.INVERTCUBICMAP=!1,s.USESPHERICALFROMREFLECTIONMAP=!1,s.USEIRRADIANCEMAP=!1,s.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,s.USESPHERICALINVERTEX=!1,s.REFLECTIONMAP_OPPOSITEZ=!1,s.LODINREFLECTIONALPHA=!1,s.GAMMAREFLECTION=!1,s.RGBDREFLECTION=!1,s.LINEARSPECULARREFLECTION=!1;return!0}function Tn(e,t,s,i,r,n,a){switch(a.needNormals=!0,void 0===r["LIGHT"+i]&&(a.needRebuild=!0),r["LIGHT"+i]=!0,r["SPOTLIGHT"+i]=!1,r["HEMILIGHT"+i]=!1,r["POINTLIGHT"+i]=!1,r["DIRLIGHT"+i]=!1,r["AREALIGHT"+i]=!1,r["CLUSTLIGHT"+i]=!1,s.prepareLightSpecificDefines(r,i),r["LIGHT_FALLOFF_PHYSICAL"+i]=!1,r["LIGHT_FALLOFF_GLTF"+i]=!1,r["LIGHT_FALLOFF_STANDARD"+i]=!1,s.falloffType){case Mr.FALLOFF_GLTF:r["LIGHT_FALLOFF_GLTF"+i]=!0;break;case Mr.FALLOFF_PHYSICAL:r["LIGHT_FALLOFF_PHYSICAL"+i]=!0;break;case Mr.FALLOFF_STANDARD:r["LIGHT_FALLOFF_STANDARD"+i]=!0}if(n&&!s.specular.equalsFloats(0,0,0)&&(a.specularEnabled=!0),r["SHADOW"+i]=!1,r["SHADOWCSM"+i]=!1,r["SHADOWCSMDEBUG"+i]=!1,r["SHADOWCSMNUM_CASCADES"+i]=!1,r["SHADOWCSMUSESHADOWMAXZ"+i]=!1,r["SHADOWCSMNOBLEND"+i]=!1,r["SHADOWCSM_RIGHTHANDED"+i]=!1,r["SHADOWPCF"+i]=!1,r["SHADOWPCSS"+i]=!1,r["SHADOWPOISSON"+i]=!1,r["SHADOWESM"+i]=!1,r["SHADOWCLOSEESM"+i]=!1,r["SHADOWCUBE"+i]=!1,r["SHADOWLOWQUALITY"+i]=!1,r["SHADOWMEDIUMQUALITY"+i]=!1,t&&t.receiveShadows&&e.shadowsEnabled&&s.shadowEnabled){const t=s.getShadowGenerator(e.activeCamera)??s.getShadowGenerator();if(t){const e=t.getShadowMap();e&&e.renderList&&e.renderList.length>0&&(a.shadowEnabled=!0,t.prepareDefines(r,i))}}s.lightmapMode!=Mr.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+i]=!0,r["LIGHTMAPNOSPECULAR"+i]=s.lightmapMode==Mr.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+i]=!1,r["LIGHTMAPNOSPECULAR"+i]=!1)}function En(e,t,s,i,r,n=null,a=!1){let o=function(e,t){let s=!1;if(e.activeCamera){const i=t.CAMERA_ORTHOGRAPHIC?1:0,r=t.CAMERA_PERSPECTIVE?1:0,n=e.activeCamera.mode===dt.ORTHOGRAPHIC_CAMERA?1:0,a=e.activeCamera.mode===dt.PERSPECTIVE_CAMERA?1:0;(i^n||r^a)&&(t.CAMERA_ORTHOGRAPHIC=1===n,t.CAMERA_PERSPECTIVE=1===a,s=!0)}return s}(e,i);!1!==n&&(o=function(e,t,s){let i=!1;const r=!!(e.clipPlane??t.clipPlane),n=!!(e.clipPlane2??t.clipPlane2),a=!!(e.clipPlane3??t.clipPlane3),o=!!(e.clipPlane4??t.clipPlane4),h=!!(e.clipPlane5??t.clipPlane5),l=!!(e.clipPlane6??t.clipPlane6);return s.CLIPPLANE!==r&&(s.CLIPPLANE=r,i=!0),s.CLIPPLANE2!==n&&(s.CLIPPLANE2=n,i=!0),s.CLIPPLANE3!==a&&(s.CLIPPLANE3=a,i=!0),s.CLIPPLANE4!==o&&(s.CLIPPLANE4=o,i=!0),s.CLIPPLANE5!==h&&(s.CLIPPLANE5=h,i=!0),s.CLIPPLANE6!==l&&(s.CLIPPLANE6=l,i=!0),i}(s,e,i)),i.DEPTHPREPASS!==!t.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==r&&(i.INSTANCES=r,o=!0),i.THIN_INSTANCES!==a&&(i.THIN_INSTANCES=a,o=!0),o&&i.markAsUnprocessed()}const Rn=new WeakMap,bn=new WeakSet;function An(e,t,s,i,r=!1,n=!0,o=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent(dt.NormalKind),t._needNormals&&e.isVerticesDataPresent(dt.TangentKind)&&(t.TANGENT=!0);for(let s=1;s<=dt.MAX_SUPPORTED_UV_SETS;++s)t["UV"+s]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===s?"":s}`);if(s){const s=e.useVertexColors&&e.isVerticesDataPresent(dt.ColorKind);t.VERTEXCOLOR=s,t.VERTEXALPHA=e.hasVertexAlpha&&s&&n}return e.isVerticesDataPresent(dt.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),i&&function(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const s=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&s)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!s&&void 0;const i=e.getScene(),r=i.prePassRenderer;if(r&&r.enabled){const s=-1===r.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=s}const n=!0===t.MULTIVIEW,o=2*t.BonesPerMesh+(n?1:0);if(Rn.get(e.skeleton)!==o){Rn.set(e.skeleton,o);const s=i.getEngine().getCaps().maxVertexUniformVectors;if(s&&!bn.has(e.skeleton)){const i=4*t.BonesPerMesh,r=n?64:40,o=Math.max(s-r,0);(i>o||n&&3*i>s)&&(bn.add(e.skeleton),a.Warn(`Skeleton "${e.skeleton.name}": ${e.skeleton.bones.length} bones stored as vertex uniforms use ${i} of ~${o} usable uniform vectors${n?" (multiview)":""} on a device reporting ${s}. This can exceed the GPU vertex-uniform limit and make the mesh silently fail to render. Set skeleton.useTextureToStoreBoneMatrices = true to store bone matrices in a texture.`))}}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}(e,t),r&&function(e,t){const s=e.morphTargetManager;s?(t.MORPHTARGETS_UV=s.supportsUVs&&t.UV1,t.MORPHTARGETS_UV2=s.supportsUV2s&&t.UV2,t.MORPHTARGETS_TANGENT=s.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=s.supportsNormals&&t.NORMAL,t.MORPHTARGETS_POSITION=s.supportsPositions,t.MORPHTARGETS_COLOR=s.supportsColors,t.MORPHTARGETTEXTURE_HASUVS=s.hasUVs,t.MORPHTARGETTEXTURE_HASUV2S=s.hasUV2s,t.MORPHTARGETTEXTURE_HASTANGENTS=s.hasTangents,t.MORPHTARGETTEXTURE_HASNORMALS=s.hasNormals,t.MORPHTARGETTEXTURE_HASPOSITIONS=s.hasPositions,t.MORPHTARGETTEXTURE_HASCOLORS=s.hasColors,t.NUM_MORPH_INFLUENCERS=s.numMaxInfluencers||s.numInfluencers,t.MORPHTARGETS=t.NUM_MORPH_INFLUENCERS>0,t.MORPHTARGETS_TEXTURE=s.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_UV2=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS_POSITION=!1,t.MORPHTARGETS_COLOR=!1,t.MORPHTARGETTEXTURE_HASUVS=!1,t.MORPHTARGETTEXTURE_HASUV2S=!1,t.MORPHTARGETTEXTURE_HASTANGENTS=!1,t.MORPHTARGETTEXTURE_HASNORMALS=!1,t.MORPHTARGETTEXTURE_HASPOSITIONS=!1,t.MORPHTARGETTEXTURE_HAS_COLORS=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}(e,t),o&&function(e,t){const s=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!s||!s.isEnabled)}(e,t),!0}function yn(e,t){if(e.activeCamera){const s=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=s&&t.markAsUnprocessed()}}function Mn(e,t,s){const i=t.ORDER_INDEPENDENT_TRANSPARENCY,r=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&s,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,i===t.ORDER_INDEPENDENT_TRANSPARENCY&&r===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}function xn(e,t,s){const i=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{type:dt.PREPASS_POSITION_TEXTURE_TYPE,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:dt.PREPASS_LOCAL_POSITION_TEXTURE_TYPE,define:"PREPASS_LOCAL_POSITION",index:"PREPASS_LOCAL_POSITION_INDEX"},{type:dt.PREPASS_VELOCITY_TEXTURE_TYPE,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:dt.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE,define:"PREPASS_VELOCITY_LINEAR",index:"PREPASS_VELOCITY_LINEAR_INDEX"},{type:dt.PREPASS_REFLECTIVITY_TEXTURE_TYPE,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:dt.PREPASS_IRRADIANCE_LEGACY_TEXTURE_TYPE,define:"PREPASS_IRRADIANCE_LEGACY",index:"PREPASS_IRRADIANCE_LEGACY_INDEX"},{type:dt.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:dt.PREPASS_DEPTH_TEXTURE_TYPE,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:dt.PREPASS_SCREENSPACE_DEPTH_TEXTURE_TYPE,define:"PREPASS_SCREENSPACE_DEPTH",index:"PREPASS_SCREENSPACE_DEPTH_INDEX"},{type:dt.PREPASS_NORMAL_TEXTURE_TYPE,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"},{type:dt.PREPASS_WORLD_NORMAL_TEXTURE_TYPE,define:"PREPASS_WORLD_NORMAL",index:"PREPASS_WORLD_NORMAL_INDEX"},{type:dt.PREPASS_IRRADIANCE_TEXTURE_TYPE,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&s){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace,t.PREPASS_COLOR=!0,t.PREPASS_COLOR_INDEX=0;for(let s=0;s<r.length;s++){const i=e.prePassRenderer.getIndex(r[s].type);-1!==i?(t[r[s].define]=!0,t[r[s].index]=i):t[r[s].define]=!1}}else{t.PREPASS=!1;for(let e=0;e<r.length;e++)t[r[e].define]=!1}t.PREPASS!=i&&(t.markAsUnprocessed(),t.markAsImageProcessingDirty())}function Sn(e,t,s,i,r=null,n=!1,a=!1,o=!1,h=!1,l=!1){r&&r.push("Light"+e),n||(t.push("vLightData"+e,"vLightDiffuse"+e,"vLightSpecular"+e,"vLightDirection"+e,"vLightWidth"+e,"vLightHeight"+e,"vLightFalloff"+e,"vLightGround"+e,"vSliceData"+e,"vSliceRanges"+e,"lightMatrix"+e,"shadowsInfo"+e,"depthValues"+e),s.push("shadowTexture"+e),s.push("depthTexture"+e),t.push("viewFrustumZ"+e,"cascadeBlendFactor"+e,"lightSizeUVCorrection"+e,"depthCorrection"+e,"penumbraDarkness"+e,"frustumLengths"+e),i&&(s.push("projectionLightTexture"+e),t.push("textureProjectionMatrix"+e)),a&&s.push("iesLightTexture"+e),h&&s.push("rectAreaLightEmissionTexture"+e),o&&(s.push("lightDataTexture"+e),l||s.push("tileMaskTexture"+e)))}function vn(e,t,s){const i=["vReflectionMicrosurfaceInfos","vReflectionDominantDirection","reflectionMatrix","vReflectionInfos","vReflectionPosition","vReflectionSize","vReflectionColor","vReflectionFilteringInfo"];s&&i.push("vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22"),e.push(...i);t.push("reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","icdfSampler")}function In(e,t,s,i=4){let r,n,a=null;if(e.uniformsNames){const o=e;r=o.uniformsNames,n=o.uniformBuffersNames,t=o.samplers,s=o.defines,i=o.maxSimultaneousLights||0,a=o.shaderLanguage??null}else r=e,t||(t=[]);for(let e=0;e<i&&s["LIGHT"+e];e++)Sn(e,r,t,s["PROJECTEDLIGHTTEXTURE"+e],n,!1,s["IESLIGHTTEXTURE"+e],s["CLUSTLIGHT"+e],s["RECTAREALIGHTEMISSIONTEXTURE"+e],1===a);s.NUM_MORPH_INFLUENCERS&&(r.push("morphTargetInfluences"),r.push("morphTargetCount")),s.BAKED_VERTEX_ANIMATION_TEXTURE&&(r.push("bakedVertexAnimationSettings"),r.push("bakedVertexAnimationTextureSizeInverted"),r.push("bakedVertexAnimationTime"),t.push("bakedVertexAnimationTexture"))}function Pn(e,t=!1,s=!1,i=!1,r=!1,n=!1){e.addUniform("vReflectionInfos",2),e.addUniform("reflectionMatrix",16),t&&e.addUniform("vReflectionMicrosurfaceInfos",3),s&&(e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3)),i&&(e.addUniform("vReflectionFilteringInfo",2),e.addUniform("vReflectionDominantDirection",3)),n&&e.addUniform("vReflectionColor",3),r&&(e.addUniform("vSphericalL00",3),e.addUniform("vSphericalL1_1",3),e.addUniform("vSphericalL10",3),e.addUniform("vSphericalL11",3),e.addUniform("vSphericalL2_2",3),e.addUniform("vSphericalL2_1",3),e.addUniform("vSphericalL20",3),e.addUniform("vSphericalL21",3),e.addUniform("vSphericalL22",3),e.addUniform("vSphericalX",3),e.addUniform("vSphericalY",3),e.addUniform("vSphericalZ",3),e.addUniform("vSphericalXX_ZZ",3),e.addUniform("vSphericalYY_ZZ",3),e.addUniform("vSphericalZZ",3),e.addUniform("vSphericalXY",3),e.addUniform("vSphericalYZ",3),e.addUniform("vSphericalZX",3))}let Cn=(()=>{var e;let t,s,i,r,n,o,h,l,u,d,_,p,f,g,m,T,E,R,y,M,x,S,v,I,P,C,O,D,w,F=[],N=[],B=[],U=[],k=[],G=[],V=[],H=[],z=[],W=[],X=[],K=[],Y=[],j=[],q=[],$=[],Z=[],Q=[],J=[],te=[],se=[],ie=[],re=[],ne=[],ae=[],oe=[],he=[],le=[],ce=[],ue=[],de=[],_e=[],pe=[],fe=[],ge=[],me=[],Te=[],Ee=[],Re=[],be=[],Ae=[],ye=[],Me=[],xe=[],Se=[],ve=[],Ie=[],Pe=[],Ce=[],Oe=[],De=[];return e=class{get useVertexPulling(){return this._useVertexPulling}set useVertexPulling(t){this._useVertexPulling!==t&&(this._useVertexPulling=t,this.markAsDirty(e.MiscDirtyFlag))}get _supportGlowLayer(){return!1}set _glowModeEnabled(e){}get shaderLanguage(){return this._shaderLanguage}get canRenderToMRT(){return!1}set alpha(t){if(this._alpha===t)return;const s=this._alpha;this._alpha=t,1!==s&&1!==t||this.markAsDirty(e.MiscDirtyFlag+e.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(t){this._backFaceCulling!==t&&(this._backFaceCulling=t,this.markAsDirty(e.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set textureRepetitionMode(t){const s=Math.max(dt.TEXTURE_REPETITION_NONE,Math.min(0|t,dt.TEXTURE_REPETITION_VORONOI_BOMBING));this._textureRepetitionMode!==s&&(this._textureRepetitionMode=s,this.markAsDirty(e.TextureDirtyFlag))}get textureRepetitionMode(){return this._textureRepetitionMode}set cullBackFaces(t){this._cullBackFaces!==t&&(this._cullBackFaces=t,this.markAsDirty(e.TextureDirtyFlag))}get cullBackFaces(){return this._cullBackFaces}get blockDirtyMechanism(){return this._blockDirtyMechanism}set blockDirtyMechanism(e){this._blockDirtyMechanism!==e&&(this._blockDirtyMechanism=e,e||this.markDirty())}atomicMaterialsUpdate(e){this.blockDirtyMechanism=!0;try{e(this)}finally{this.blockDirtyMechanism=!1}}get hasRenderTargetTextures(){return this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._eventInfo.hasRenderTargetTextures}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new c),this._onBindObservable}set onBind(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)}get onUnBindObservable(){return this._onUnBindObservable||(this._onUnBindObservable=new c),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new c),this._onEffectCreatedObservable}set alphaMode(t){this._alphaMode[0]!==t&&(this._alphaMode[0]=t,this.markAsDirty(e.TextureDirtyFlag))}get alphaMode(){return this._alphaMode[0]}get alphaModes(){return this._alphaMode}setAlphaMode(t,s=0){this._alphaMode[s]!==t&&(this._alphaMode[s]=t,this.markAsDirty(e.TextureDirtyFlag))}set needDepthPrePass(e){this._needDepthPrePass!==e&&(this._needDepthPrePass=e,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))}get needDepthPrePass(){return this._needDepthPrePass}get isPrePassCapable(){return!1}set fogEnabled(t){this._fogEnabled!==t&&(this._fogEnabled=t,this.markAsDirty(e.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case e.WireFrameFillMode:case e.LineListDrawMode:case e.LineLoopDrawMode:case e.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(t){this.fillMode=t?e.WireFrameFillMode:e.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case e.PointFillMode:case e.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(t){this.fillMode=t?e.PointFillMode:e.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(t){this._fillMode!==t&&(this._fillMode=t,this.markAsDirty(e.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&a.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._markAllSubMeshesAsMiscDirty()}get isVertexOutputInvariant(){return this._isVertexOutputInvariant}set isVertexOutputInvariant(e){this._isVertexOutputInvariant!==e&&(this._isVertexOutputInvariant=e,this._markAllSubMeshesAsMiscDirty())}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(t,s,i,r=!1){this.customShaderNameResolve=A(this,F),this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this._shaderLanguage=0,this._forceGLSL=!1,this._useVertexPulling=!1,this.id=A(this,N,void 0),this.uniqueId=(A(this,B),A(this,U,void 0)),this._loadedUniqueId=A(this,k),this.name=A(this,G,void 0),this.metadata=(A(this,V),A(this,H,null)),this._internalMetadata=A(this,z),this.reservedDataStore=null,this.checkReadyOnEveryCall=A(this,W,!1),this.checkReadyOnlyOnce=(A(this,X),A(this,K,!1)),this.state=(A(this,Y),A(this,j,"")),this._alpha=(A(this,q),A(this,$,1)),this.inspectableCustomProperties=A(this,Z),this._backFaceCulling=A(this,Q,!0),this._textureRepetitionMode=(A(this,J),A(this,te,dt.TEXTURE_REPETITION_NONE)),this.textureRepetitionHexTilingParams=(A(this,se),A(this,ie,[1,.6,7,.5])),this._cullBackFaces=(A(this,re),A(this,ne,!0)),this._blockDirtyMechanism=(A(this,ae),!1),this.sideOrientation=A(this,oe,null),this.onCompiled=(A(this,he),null),this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new c,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=A(this,le,[dt.ALPHA_COMBINE]),this._needDepthPrePass=(A(this,ce),A(this,ue,!1)),this.disableDepthWrite=(A(this,de),A(this,_e,!1)),this.disableColorWrite=(A(this,pe),A(this,fe,!1)),this.forceDepthWrite=(A(this,ge),A(this,me,!1)),this.depthFunction=(A(this,Te),A(this,Ee,0)),this.separateCullingPass=(A(this,Re),A(this,be,!1)),this._fogEnabled=(A(this,Ae),A(this,ye,!0)),this.pointSize=(A(this,Me),A(this,xe,1)),this.zOffset=(A(this,Se),A(this,ve,0)),this.zOffsetUnits=(A(this,Ie),A(this,Pe,0)),this.clipPlane=A(this,Ce),this.stencil=new yr,this._isVertexOutputInvariant=A(this,Oe,e.ForceVertexOutputInvariant),this._materialContext=A(this,De),this._useUBO=!1,this._fillMode=e.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedColorWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this._parentContainer=null,this._uniformBufferLayoutBuilt=!1,this._eventInfo={},this._callbackPluginEventGeneric=()=>{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._transparencyMode=null,this.name=t;const n=s||ee.LastCreatedScene;n&&(this._scene=n,this._dirtyCallbacks={},this._forceGLSL=r,this._dirtyCallbacks[dt.MATERIAL_TextureDirtyFlag]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[dt.MATERIAL_LightDirtyFlag]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[dt.MATERIAL_FresnelDirtyFlag]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[dt.MATERIAL_AttributesDirtyFlag]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[dt.MATERIAL_MiscDirtyFlag]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[dt.MATERIAL_PrePassDirtyFlag]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[dt.MATERIAL_AllDirtyFlag]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=t||Fs.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new rr(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._uniformBuffer=new dr(this._scene.getEngine(),void 0,void 0,t),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,this._createUniformBuffer(),i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),e.OnEventObservable.notifyObservers(this,1))}_createUniformBuffer(){const e=this.getScene().getEngine();this._uniformBuffer?.dispose(),e.isWebGPU&&!this._forceGLSL?(this._uniformBuffer=new dr(e,void 0,void 0,this.name,!0),this._shaderLanguage=1):this._uniformBuffer=new dr(this._scene.getEngine(),void 0,void 0,this.name),this._uniformBufferLayoutBuilt=!1}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,s){const i=t.materialDefines;return!!i&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=i,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}_getEffectiveOrientation(e){return null!==this.sideOrientation?this.sideOrientation:e.sideOrientation}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _hasTransparencyMode(){return null!=this._transparencyMode}get _transparencyModeIsBlend(){return this._transparencyMode===e.MATERIAL_ALPHABLEND||this._transparencyMode===e.MATERIAL_ALPHATESTANDBLEND}get _transparencyModeIsTest(){return this._transparencyMode===e.MATERIAL_ALPHATEST||this._transparencyMode===e.MATERIAL_ALPHATESTANDBLEND}get _disableAlphaBlending(){return this._transparencyMode===e.MATERIAL_OPAQUE||this._transparencyMode===e.MATERIAL_ALPHATEST}needAlphaBlending(){return this._hasTransparencyMode?this._transparencyModeIsBlend:!this._disableAlphaBlending&&this.alpha<1}needAlphaBlendingForMesh(e){return this._hasTransparencyMode?this._transparencyModeIsBlend:e.visibility<1||!this._disableAlphaBlending&&(e.hasVertexAlpha||this.needAlphaBlending())}needAlphaTesting(){return!!this._hasTransparencyMode&&this._transparencyModeIsTest}needAlphaTestingForMesh(e){return this._hasTransparencyMode?this._transparencyModeIsTest:!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(t=!1){const s=this.getScene().meshes;for(const e of s)if(e.subMeshes)for(const s of e.subMeshes)if(s.getMaterial()===this)for(const e of s._drawWrappers)e&&this._materialContext===e.materialContext&&(e._wasPreviouslyReady=!1,e._wasPreviouslyUsingInstances=null,e._forceRebindOnNextCall=t);t&&this.markAsDirty(e.AllDirtyFlag)}_preBind(t,s=null){const i=this._scene.getEngine(),r=(null==s?this.sideOrientation:s)===e.ClockWiseSideOrientation,n=t||this._getDrawWrapper();return Si(n)&&n.materialContext&&(n.materialContext.useVertexPulling=this.useVertexPulling),i.enableEffect(n),i.setState(this.backFaceCulling,this.zOffset,!1,r,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),r}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(8,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,s){const i=s._drawWrapper;this._eventInfo.subMesh=s,this._callbackPluginEventBindForSubMesh(this._eventInfo),i._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()),e.setMatrix("inverseProjection",this.getScene().getInverseProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,s){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,en(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){const e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){const e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){if(this._scene.getSceneUniformBuffer().unbindEffect(),this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction){this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState)}if(this.disableDepthWrite){this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState)}if(this.disableColorWrite){this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(256,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(512,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(1024,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(t,s){const i={};if(this._serializePlugins(i),e._ParsePlugins(i,t,this._scene,s),this.pluginManager)for(const e of this.pluginManager._plugins){const s=t.pluginManager.getPlugin(e.name);s&&e.copyTo(s)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const s=this.meshMap[t];s&&e.push(s)}return e}return this._scene.meshes.filter(e=>e.material===this)}forceCompilation(e,t,s,i){const r={clipPlane:!1,useInstances:!1,...s},n=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const o=()=>{if(!this._scene||!this._scene.getEngine())return;const s=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new Ys(0,0,0,1)),this._storeEffectOnSubMeshes){let s=!0,n=null;if(e.subMeshes){const t=new nr(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,r.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(s=!1,setTimeout(o,16)))}s&&(this.allowShaderHotSwapping=a,n&&i&&i(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(o,16);r.clipPlane&&(n.clipPlane=s)};o()}async forceCompilationAsync(e,t){return await new Promise((s,i)=>{this.forceCompilation(e,()=>{s()},t,e=>{i(e)})})}markAsDirty(t){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(e._DirtyCallbackArray.length=0,t&e.ImageProcessingDirtyFlag&&e._DirtyCallbackArray.push(e._ImageProcessingDirtyCallBack),t&e.TextureDirtyFlag&&e._DirtyCallbackArray.push(e._TextureDirtyCallBack),t&e.LightDirtyFlag&&e._DirtyCallbackArray.push(e._LightsDirtyCallBack),t&e.FresnelDirtyFlag&&e._DirtyCallbackArray.push(e._FresnelDirtyCallBack),t&e.AttributesDirtyFlag&&e._DirtyCallbackArray.push(e._AttributeDirtyCallBack),t&e.MiscDirtyFlag&&e._DirtyCallbackArray.push(e._MiscDirtyCallBack),t&e.PrePassDirtyFlag&&e._DirtyCallbackArray.push(e._PrePassDirtyCallBack),e._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(e._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const e of t.subMeshes)e.getMaterial()===this&&e.resetDrawCache()}_markAllSubMeshesAsDirty(e){const t=this.getScene();if(t.blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const s=t.meshes;for(const i of s)if(i.subMeshes)for(const s of i.subMeshes){if((s.getMaterial()||(t._hasDefaultMaterial?t.defaultMaterial:null))===this)for(const t of s._drawWrappers)t&&t.defines&&t.defines.markAllAsDirty&&this._materialContext===t.materialContext&&e(t.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(e._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(e._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(e._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(e._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(e._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(e._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(e._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(e._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(e._PrePassDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(e._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(0!==this._scene.performancePriority){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,s){const i=this.getScene();if(i.stopAnimation(this),i.freeProcessedMaterials(),i.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(2,this._eventInfo),this._parentContainer){const e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==s)if(this.meshMap)for(const e in this.meshMap){const t=this.meshMap[e];this._disposeMeshResources(t)}else{const e=i.meshes;for(const t of e)this._disposeMeshResources(t)}this._uniformBuffer.dispose(),this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}_disposeMeshResources(e){if(!e)return;const t=e.geometry,s=e._internalAbstractMeshDataInfo._materialForRenderPass;if(this._storeEffectOnSubMeshes){if(e.subMeshes&&s)for(const i of e.subMeshes){const e=i._drawWrappers;for(let r=0;r<e.length;r++){const n=e[r]?.effect;if(!n)continue;s[r]===this&&(t?._releaseVertexArrayObject(n),i._removeDrawWrapper(r,!0,!0))}}}else t?._releaseVertexArrayObject(this._drawWrapper.effect);e.material!==this||e.sourceMesh||(e.material=null)}serialize(){const e=$e.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(const t of this.pluginManager._plugins)t.doNotSerialize||(e.plugins[t.getClassName()]=t.serialize())}static ParseAlphaMode(e,t){void 0!==e._alphaMode?t._alphaMode=Array.isArray(e._alphaMode)?[...e._alphaMode]:[e._alphaMode]:void 0!==e.alphaMode?t._alphaMode=Array.isArray(e.alphaMode)?[...e.alphaMode]:[e.alphaMode]:t._alphaMode=[dt.ALPHA_COMBINE]}static Parse(t,s,i){if(t.customType){if("BABYLON.PBRMaterial"===t.customType&&t.overloadedAlbedo&&(t.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return a.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else t.customType="BABYLON.StandardMaterial";const r=Fs.Instantiate(t.customType).Parse(t,s,i);return r._loadedUniqueId=t.uniqueId,e.ParseAlphaMode(t,r),r}static _ParsePlugins(e,t,s,i){if(e.plugins)for(const r in e.plugins){const n=e.plugins[r];let a=t.pluginManager?.getPlugin(n.name);if(!a){const e=Fs.Instantiate("BABYLON."+r);e&&(a=new e(t))}a?.parse(n,s,i)}}},(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[L()],s=[L()],i=[L()],r=[L()],n=[L()],o=[L()],h=[L()],l=[L("alpha")],u=[L("backFaceCulling")],d=[L("textureRepetitionMode")],_=[L("textureRepetitionHexTilingParams")],p=[L("cullBackFaces")],f=[L()],g=[L()],m=[L()],T=[L()],E=[L()],R=[L()],y=[L()],M=[L()],x=[L("fogEnabled")],S=[L()],v=[L()],I=[L()],P=[L()],C=[L()],O=[L()],D=[L()],w=[L()],b(e,null,P,{kind:"getter",name:"pointsCloud",static:!1,private:!1,access:{has:e=>"pointsCloud"in e,get:e=>e.pointsCloud},metadata:a},null,F),b(e,null,C,{kind:"getter",name:"fillMode",static:!1,private:!1,access:{has:e=>"fillMode"in e,get:e=>e.fillMode},metadata:a},null,F),b(e,null,O,{kind:"getter",name:"useLogarithmicDepth",static:!1,private:!1,access:{has:e=>"useLogarithmicDepth"in e,get:e=>e.useLogarithmicDepth},metadata:a},null,F),b(e,null,w,{kind:"getter",name:"transparencyMode",static:!1,private:!1,access:{has:e=>"transparencyMode"in e,get:e=>e.transparencyMode},metadata:a},null,F),b(null,null,t,{kind:"field",name:"id",static:!1,private:!1,access:{has:e=>"id"in e,get:e=>e.id,set:(e,t)=>{e.id=t}},metadata:a},N,B),b(null,null,s,{kind:"field",name:"uniqueId",static:!1,private:!1,access:{has:e=>"uniqueId"in e,get:e=>e.uniqueId,set:(e,t)=>{e.uniqueId=t}},metadata:a},U,k),b(null,null,i,{kind:"field",name:"name",static:!1,private:!1,access:{has:e=>"name"in e,get:e=>e.name,set:(e,t)=>{e.name=t}},metadata:a},G,V),b(null,null,r,{kind:"field",name:"metadata",static:!1,private:!1,access:{has:e=>"metadata"in e,get:e=>e.metadata,set:(e,t)=>{e.metadata=t}},metadata:a},H,z),b(null,null,n,{kind:"field",name:"checkReadyOnEveryCall",static:!1,private:!1,access:{has:e=>"checkReadyOnEveryCall"in e,get:e=>e.checkReadyOnEveryCall,set:(e,t)=>{e.checkReadyOnEveryCall=t}},metadata:a},W,X),b(null,null,o,{kind:"field",name:"checkReadyOnlyOnce",static:!1,private:!1,access:{has:e=>"checkReadyOnlyOnce"in e,get:e=>e.checkReadyOnlyOnce,set:(e,t)=>{e.checkReadyOnlyOnce=t}},metadata:a},K,Y),b(null,null,h,{kind:"field",name:"state",static:!1,private:!1,access:{has:e=>"state"in e,get:e=>e.state,set:(e,t)=>{e.state=t}},metadata:a},j,q),b(null,null,l,{kind:"field",name:"_alpha",static:!1,private:!1,access:{has:e=>"_alpha"in e,get:e=>e._alpha,set:(e,t)=>{e._alpha=t}},metadata:a},$,Z),b(null,null,u,{kind:"field",name:"_backFaceCulling",static:!1,private:!1,access:{has:e=>"_backFaceCulling"in e,get:e=>e._backFaceCulling,set:(e,t)=>{e._backFaceCulling=t}},metadata:a},Q,J),b(null,null,d,{kind:"field",name:"_textureRepetitionMode",static:!1,private:!1,access:{has:e=>"_textureRepetitionMode"in e,get:e=>e._textureRepetitionMode,set:(e,t)=>{e._textureRepetitionMode=t}},metadata:a},te,se),b(null,null,_,{kind:"field",name:"textureRepetitionHexTilingParams",static:!1,private:!1,access:{has:e=>"textureRepetitionHexTilingParams"in e,get:e=>e.textureRepetitionHexTilingParams,set:(e,t)=>{e.textureRepetitionHexTilingParams=t}},metadata:a},ie,re),b(null,null,p,{kind:"field",name:"_cullBackFaces",static:!1,private:!1,access:{has:e=>"_cullBackFaces"in e,get:e=>e._cullBackFaces,set:(e,t)=>{e._cullBackFaces=t}},metadata:a},ne,ae),b(null,null,f,{kind:"field",name:"sideOrientation",static:!1,private:!1,access:{has:e=>"sideOrientation"in e,get:e=>e.sideOrientation,set:(e,t)=>{e.sideOrientation=t}},metadata:a},oe,he),b(null,null,g,{kind:"field",name:"_alphaMode",static:!1,private:!1,access:{has:e=>"_alphaMode"in e,get:e=>e._alphaMode,set:(e,t)=>{e._alphaMode=t}},metadata:a},le,ce),b(null,null,m,{kind:"field",name:"_needDepthPrePass",static:!1,private:!1,access:{has:e=>"_needDepthPrePass"in e,get:e=>e._needDepthPrePass,set:(e,t)=>{e._needDepthPrePass=t}},metadata:a},ue,de),b(null,null,T,{kind:"field",name:"disableDepthWrite",static:!1,private:!1,access:{has:e=>"disableDepthWrite"in e,get:e=>e.disableDepthWrite,set:(e,t)=>{e.disableDepthWrite=t}},metadata:a},_e,pe),b(null,null,E,{kind:"field",name:"disableColorWrite",static:!1,private:!1,access:{has:e=>"disableColorWrite"in e,get:e=>e.disableColorWrite,set:(e,t)=>{e.disableColorWrite=t}},metadata:a},fe,ge),b(null,null,R,{kind:"field",name:"forceDepthWrite",static:!1,private:!1,access:{has:e=>"forceDepthWrite"in e,get:e=>e.forceDepthWrite,set:(e,t)=>{e.forceDepthWrite=t}},metadata:a},me,Te),b(null,null,y,{kind:"field",name:"depthFunction",static:!1,private:!1,access:{has:e=>"depthFunction"in e,get:e=>e.depthFunction,set:(e,t)=>{e.depthFunction=t}},metadata:a},Ee,Re),b(null,null,M,{kind:"field",name:"separateCullingPass",static:!1,private:!1,access:{has:e=>"separateCullingPass"in e,get:e=>e.separateCullingPass,set:(e,t)=>{e.separateCullingPass=t}},metadata:a},be,Ae),b(null,null,x,{kind:"field",name:"_fogEnabled",static:!1,private:!1,access:{has:e=>"_fogEnabled"in e,get:e=>e._fogEnabled,set:(e,t)=>{e._fogEnabled=t}},metadata:a},ye,Me),b(null,null,S,{kind:"field",name:"pointSize",static:!1,private:!1,access:{has:e=>"pointSize"in e,get:e=>e.pointSize,set:(e,t)=>{e.pointSize=t}},metadata:a},xe,Se),b(null,null,v,{kind:"field",name:"zOffset",static:!1,private:!1,access:{has:e=>"zOffset"in e,get:e=>e.zOffset,set:(e,t)=>{e.zOffset=t}},metadata:a},ve,Ie),b(null,null,I,{kind:"field",name:"zOffsetUnits",static:!1,private:!1,access:{has:e=>"zOffsetUnits"in e,get:e=>e.zOffsetUnits,set:(e,t)=>{e.zOffsetUnits=t}},metadata:a},Pe,Ce),b(null,null,D,{kind:"field",name:"_isVertexOutputInvariant",static:!1,private:!1,access:{has:e=>"_isVertexOutputInvariant"in e,get:e=>e._isVertexOutputInvariant,set:(e,t)=>{e._isVertexOutputInvariant=t}},metadata:a},Oe,De),a&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),e.TriangleFillMode=dt.MATERIAL_TriangleFillMode,e.WireFrameFillMode=dt.MATERIAL_WireFrameFillMode,e.PointFillMode=dt.MATERIAL_PointFillMode,e.PointListDrawMode=dt.MATERIAL_PointListDrawMode,e.LineListDrawMode=dt.MATERIAL_LineListDrawMode,e.LineLoopDrawMode=dt.MATERIAL_LineLoopDrawMode,e.LineStripDrawMode=dt.MATERIAL_LineStripDrawMode,e.TriangleStripDrawMode=dt.MATERIAL_TriangleStripDrawMode,e.TriangleFanDrawMode=dt.MATERIAL_TriangleFanDrawMode,e.ClockWiseSideOrientation=dt.MATERIAL_ClockWiseSideOrientation,e.CounterClockWiseSideOrientation=dt.MATERIAL_CounterClockWiseSideOrientation,e.ImageProcessingDirtyFlag=dt.MATERIAL_ImageProcessingDirtyFlag,e.TextureDirtyFlag=dt.MATERIAL_TextureDirtyFlag,e.LightDirtyFlag=dt.MATERIAL_LightDirtyFlag,e.FresnelDirtyFlag=dt.MATERIAL_FresnelDirtyFlag,e.AttributesDirtyFlag=dt.MATERIAL_AttributesDirtyFlag,e.MiscDirtyFlag=dt.MATERIAL_MiscDirtyFlag,e.PrePassDirtyFlag=dt.MATERIAL_PrePassDirtyFlag,e.AllDirtyFlag=dt.MATERIAL_AllDirtyFlag,e.MATERIAL_OPAQUE=0,e.MATERIAL_ALPHATEST=1,e.MATERIAL_ALPHABLEND=2,e.MATERIAL_ALPHATESTANDBLEND=3,e.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,e.MATERIAL_NORMALBLENDMETHOD_RNM=1,e.LIGHTFALLOFF_PHYSICAL=0,e.LIGHTFALLOFF_GLTF=1,e.LIGHTFALLOFF_STANDARD=2,e.OnEventObservable=new c,e.ForceVertexOutputInvariant=!1,e._AllDirtyCallBack=e=>e.markAllAsDirty(),e._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),e._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),e._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),e._MiscDirtyCallBack=e=>e.markAsMiscDirty(),e._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),e._LightsDirtyCallBack=e=>e.markAsLightDirty(),e._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),e._FresnelAndMiscDirtyCallBack=t=>{e._FresnelDirtyCallBack(t),e._MiscDirtyCallBack(t)},e._TextureAndMiscDirtyCallBack=t=>{e._TextureDirtyCallBack(t),e._MiscDirtyCallBack(t)},e._DirtyCallbackArray=[],e._RunDirtyCallBacks=t=>{for(const s of e._DirtyCallbackArray)s(t)},e})();Object.getOwnPropertyDescriptor(Cn.prototype,"pluginManager")||Object.defineProperty(Cn.prototype,"pluginManager",Ue(0,"pluginManager"));class On extends Cn{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...s)=>{const i=t.apply(e,s);return this._markAllSubMeshesAsTexturesDirty(),i};const s=e.splice;e.splice=(t,i)=>{const r=s.call(e,t,i??e.length);return this._markAllSubMeshesAsTexturesDirty(),r}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map(e=>e?e.getActiveTextures():[]))}hasTexture(e){if(super.hasTexture(e))return!0;for(let t=0;t<this.subMaterials.length;t++)if(this.subMaterials[t]?.hasTexture(e))return!0;return!1}getClassName(){return"MultiMaterial"}isReadyForSubMesh(e,t,s){for(let i=0;i<this.subMaterials.length;i++){const r=this.subMaterials[i];if(r){if(r._storeEffectOnSubMeshes){if(!r.isReadyForSubMesh(e,t,s))return!1;continue}if(!r.isReady(e))return!1}}return!0}clone(e,t){const s=new On(e,this.getScene());for(let i=0;i<this.subMaterials.length;i++){let r;const n=this.subMaterials[i];r=t&&n?n.clone(e+"-"+n.name):this.subMaterials[i],s.subMaterials.push(r)}return s}serialize(){const e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,Ge&&(e.tags=Ge.GetTags(this)),e.materialsUniqueIds=[],e.materials=[];for(let t=0;t<this.subMaterials.length;t++){const s=this.subMaterials[t];s?(e.materialsUniqueIds.push(s.uniqueId),e.materials.push(s.id)):(e.materialsUniqueIds.push(null),e.materials.push(null))}return e}dispose(e,t,s){const i=this.getScene();if(!i)return;if(s)for(let s=0;s<this.subMaterials.length;s++){const i=this.subMaterials[s];i&&i.dispose(e,t)}const r=i.multiMaterials.indexOf(this);r>=0&&i.multiMaterials.splice(r,1),super.dispose(e,t)}}let Dn=!1;function wn(e,t){const s=new On(e.name,t);if(s.id=e.id,s._loadedUniqueId=e.uniqueId,Ge&&Ge.AddTagsTo(s,e.tags),e.materialsUniqueIds)s._waitingSubMaterialsUniqueIds=e.materialsUniqueIds;else for(const i of e.materials)s.subMaterials.push(t.getLastMaterialById(i));return s}function Ln(){Dn||(Dn=!0,On.ParseMultiMaterial=wn,be("BABYLON.MultiMaterial",On))}class Fn{}Fn.NAME_EFFECTLAYER="EffectLayer",Fn.NAME_LAYER="Layer",Fn.NAME_LENSFLARESYSTEM="LensFlareSystem",Fn.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",Fn.NAME_PARTICLESYSTEM="ParticleSystem",Fn.NAME_GAMEPAD="Gamepad",Fn.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",Fn.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",Fn.NAME_PREPASSRENDERER="PrePassRenderer",Fn.NAME_DEPTHRENDERER="DepthRenderer",Fn.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",Fn.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",Fn.NAME_SPRITE="Sprite",Fn.NAME_SUBSURFACE="SubSurface",Fn.NAME_OUTLINERENDERER="Outline",Fn.NAME_PROCEDURALTEXTURE="ProceduralTexture",Fn.NAME_SHADOWGENERATOR="ShadowGenerator",Fn.NAME_OCTREE="Octree",Fn.NAME_PHYSICSENGINE="PhysicsEngine",Fn.NAME_AUDIO="Audio",Fn.NAME_FLUIDRENDERER="FluidRenderer",Fn.NAME_IBLCDFGENERATOR="iblCDFGenerator",Fn.NAME_CLUSTEREDLIGHTING="ClusteredLighting",Fn.STEP_ISREADYFORMESH_EFFECTLAYER=0,Fn.STEP_ISREADYFORMESH_DEPTHRENDERER=1,Fn.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,Fn.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,Fn.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,Fn.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,Fn.STEP_BEFORECAMERADRAW_PREPASS=0,Fn.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,Fn.STEP_BEFORECAMERADRAW_LAYER=2,Fn.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,Fn.STEP_BEFORERENDERTARGETDRAW_LAYER=1,Fn.STEP_BEFORERENDERINGMESH_PREPASS=0,Fn.STEP_BEFORERENDERINGMESH_OUTLINE=1,Fn.STEP_AFTERRENDERINGMESH_PREPASS=0,Fn.STEP_AFTERRENDERINGMESH_OUTLINE=1,Fn.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,Fn.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,Fn.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,Fn.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,Fn.STEP_BEFORECLEAR_PREPASS=1,Fn.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,Fn.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,Fn.STEP_AFTERRENDERTARGETDRAW_LAYER=1,Fn.STEP_AFTERCAMERADRAW_PREPASS=0,Fn.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,Fn.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,Fn.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,Fn.STEP_AFTERCAMERADRAW_LAYER=4,Fn.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,Fn.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,Fn.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,Fn.STEP_AFTERRENDER_AUDIO=0,Fn.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,Fn.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,Fn.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,Fn.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,Fn.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,Fn.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,Fn.STEP_GATHERACTIVECAMERARENDERTARGETS_CLUSTEREDLIGHTING=2,Fn.STEP_POINTERMOVE_SPRITE=0,Fn.STEP_POINTERDOWN_SPRITE=0,Fn.STEP_POINTERUP_SPRITE=0;class Nn extends Array{constructor(e){super(...e)}static Create(){return Object.create(Nn.prototype)}registerStep(e,t,s){let i,r=0;for(;r<this.length;r++){if(i=this[r].index,e<i)break}this.splice(r,0,{index:e,component:t,action:s.bind(t)})}clear(){this.length=0}}class Bn{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class Un{}class kn{constructor(){this.batchCache=new Vn(this),this.batchCacheReplacementModeInFrozenMode=new Vn(this),this.instancesBufferSize=2048}}class Gn{constructor(){this.renderPasses={}}}class Vn{constructor(e){this.parent=e,this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class Hn{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class zn{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}const Wn={source:null,parent:null,doNotCloneChildren:!1,clonePhysicsImpostor:!0,cloneThinInstances:!1};class Xn extends Ar{static _GetDefaultSideOrientation(e){return e||Xn.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(Gi.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(Gi.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new c),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new c),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new c),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new c),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new c),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get sideOrientation(){return this._internalMeshDataInfo._sideOrientation}set sideOrientation(e){this._internalMeshDataInfo._sideOrientation=e,this._internalAbstractMeshDataInfo._sideOrientationHint=this._scene.useRightHandedSystem&&e===dt.MATERIAL_CounterClockWiseSideOrientation||!this._scene.useRightHandedSystem&&e===dt.MATERIAL_ClockWiseSideOrientation}get _effectiveSideOrientation(){return this._internalMeshDataInfo._effectiveSideOrientation}get overrideMaterialSideOrientation(){return this.sideOrientation}set overrideMaterialSideOrientation(e){this.sideOrientation=e,this.material&&(this.material.sideOrientation=null)}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){e&&(this.material&&null===this.material.sideOrientation||this._internalAbstractMeshDataInfo._sideOrientationHint)&&(e.sideOrientation=null),this._setMaterial(e)}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){const e=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._instanceDataStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];return e?e.instancesData:void 0}get previousWorldMatrixInstancedBuffer(){const e=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._instanceDataStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];return e?e.instancesPreviousData:void 0}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}_copySource(e,t,s=!0,i=!1){const r=this.getScene();if(e._geometry&&e._geometry.applyToMesh(this),rt.DeepCopy(e,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=e,r.useClonedMeshMap&&(e._internalMeshDataInfo.meshMap||(e._internalMeshDataInfo.meshMap={}),e._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=e._originalBuilderSideOrientation,this._creationDataStorage=e._creationDataStorage,e._ranges){const t=e._ranges;for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&t[e]&&this.createAnimationRange(e,t[e].from,t[e].to)}if(e.metadata&&e.metadata.clone?this.metadata=e.metadata.clone():this.metadata=e.metadata,this._internalMetadata=e._internalMetadata,Ge&&Ge.HasTags(e)&&Ge.AddTagsTo(this,Ge.GetTags(e,!0)),this.setEnabled(e.isEnabled(!1)),this.parent=e.parent,this.setPivotMatrix(e.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=this.name+"."+e.id,this.material=e.material,!t){const r=e.getDescendants(!0);for(let e=0;e<r.length;e++){const n=r[e];n._isMesh?(Wn.parent=this,Wn.doNotCloneChildren=t,Wn.clonePhysicsImpostor=s,Wn.cloneThinInstances=i,n.clone(this.name+"."+n.name,Wn)):n.clone&&n.clone(this.name+"."+n.name,this)}}if(e.morphTargetManager&&(this.morphTargetManager=e.morphTargetManager),Be(r.getPhysicsEngine)){const t=r.getPhysicsEngine();if(s&&t)if(1===t.getPluginVersion()){const s=t.getImpostorForPhysicsObject(e);s&&(this.physicsImpostor=s.clone(this))}else 2===t.getPluginVersion()&&e.physicsBody&&e.physicsBody.clone(this)}for(let t=0;t<r.particleSystems.length;t++){const s=r.particleSystems[t];s.emitter===e&&s.clone(s.name,this)}if(this.skeleton=e.skeleton,i&&(e._thinInstanceDataStorage.matrixData?(this.thinInstanceSetBuffer("matrix",new Float32Array(e._thinInstanceDataStorage.matrixData),16,!e._thinInstanceDataStorage.matrixBuffer.isUpdatable()),this._thinInstanceDataStorage.matrixBufferSize=e._thinInstanceDataStorage.matrixBufferSize,this._thinInstanceDataStorage.instancesCount=e._thinInstanceDataStorage.instancesCount):this._thinInstanceDataStorage.matrixBufferSize=e._thinInstanceDataStorage.matrixBufferSize,e._userThinInstanceBuffersStorage)){const t=e._userThinInstanceBuffersStorage;for(const e in t.data)this.thinInstanceSetBuffer(e,new Float32Array(t.data[e]),t.strides[e],!t.vertexBuffers?.[e]?.isUpdatable()),this._userThinInstanceBuffersStorage.sizes[e]=t.sizes[e]}this.refreshBoundingInfo(!0,!0),this.computeWorldMatrix(!0)}constructor(e,t=null,s=null,i=null,r,n=!0){let a;super(e,t),this._internalMeshDataInfo=new zn,this.delayLoadState=dt.DELAYLOADSTATE_NONE,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._thinInstanceDataStorage=new Hn,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=Xn.DEFAULTSIDE,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._instanceDataStorage=new Gn,this._instanceDataStorage.engine=t.getEngine(),this._instanceDataStorage.useMonoDataStorageRenderPass=!this._instanceDataStorage.engine.isWebGPU,this._instanceDataStorage.useMonoDataStorageRenderPass&&(this._instanceDataStorage.dataStorageRenderPass=new kn),this._scene.useRightHandedSystem?this.sideOrientation=dt.MATERIAL_ClockWiseSideOrientation:this.sideOrientation=dt.MATERIAL_CounterClockWiseSideOrientation,this._onBeforeDraw=(e,t,s)=>{e&&s&&(this._uniformBuffer?this.transferToEffect(t):s.bindOnlyWorldMatrix(t))};let o=!1;if(s&&void 0===s._addToSceneRootNodes){const e=s;a=e.parent??null,i=e.source??null,r=e.doNotCloneChildren??!1,n=e.clonePhysicsImpostor??!0,o=e.cloneThinInstances??!1}else a=s;i&&this._copySource(i,r,n,o),null!==a&&(this.parent=a),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=e=>{e.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add(()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))}))},this.onMeshReadyObservable=new c(this._internalMeshDataInfo._onMeshReadyObserverAdded),i&&i.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,s){const i=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));i.parent=e||this.parent,i.position=this.position.clone(),i.scaling=this.scaling.clone(),this.rotationQuaternion?i.rotationQuaternion=this.rotationQuaternion.clone():i.rotation=this.rotation.clone(),s&&s(this,i);for(const e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===i.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(i,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:i},s):e.instantiateHierarchy(i,t,s);return i}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let s=0;s<this.animations.length;s++)t+=", animation[0]: "+this.animations[s].toString(e);if(e)if(this._geometry){const e=this.getIndices(),s=this.getVerticesData(Gi.PositionKind);s&&e&&(t+=", flat shading: "+(s.length/3===e.length?"YES":"NO"))}else t+=", flat shading: UNKNOWN";return t}_unBindEffect(){super._unBindEffect();for(const e of this.instances)e._unBindEffect()}get hasLODLevels(){return this._internalMeshDataInfo._LODLevels.length>0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,s)=>t.distanceOrScreenCoverage<s.distanceOrScreenCoverage?e:t.distanceOrScreenCoverage>s.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return a.Warn("You cannot use a mesh as LOD level twice"),this;const s=new Bn(e,t);return this._internalMeshDataInfo._LODLevels.push(s),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let s=0;s<t._LODLevels.length;s++){const i=t._LODLevels[s];if(i.distanceOrScreenCoverage===e)return i.mesh}return null}removeLODLevel(e){const t=this._internalMeshDataInfo;for(let s=0;s<t._LODLevels.length;s++)t._LODLevels[s].mesh===e&&(t._LODLevels.splice(s,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this}getLOD(e,t){const s=this._internalMeshDataInfo;if(!s._LODLevels||0===s._LODLevels.length)return this;const i=t||this.getBoundingInfo().boundingSphere,r=e.mode===bi.ORTHOGRAPHIC_CAMERA?e.minZ:i.centerWorld.subtract(e.globalPosition).length();let n=r,a=1;if(s._useLODScreenCoverage){const t=e.screenArea;let s=i.radiusWorld*e.minZ/r;s=s*s*Math.PI,n=s/t,a=-1}if(a*s._LODLevels[s._LODLevels.length-1].distanceOrScreenCoverage>a*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let e=0;e<s._LODLevels.length;e++){const t=s._LODLevels[e];if(a*t.distanceOrScreenCoverage<a*n){if(t.mesh){if(t.mesh.delayLoadState===dt.DELAYLOADSTATE_NOTLOADED)return t.mesh._checkDelayState(),this;if(t.mesh.delayLoadState===dt.DELAYLOADSTATE_LOADING)return this;t.mesh._preActivate(),t.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)}return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,t.mesh),t.mesh}}return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this}get geometry(){return this._geometry}getTotalVertices(){return null===this._geometry||void 0===this._geometry?0:this._geometry.getTotalVertices()}getVerticesData(e,t,s,i){if(!this._geometry)return null;let r=i?void 0:this._userInstancedBuffersStorage?.vertexBuffers[e]?.getFloatData(this.instances.length+1,s||t&&1!==this._geometry.meshes.length);return r||(r=this._geometry.getVerticesData(e,t,s)),r}copyVerticesData(e,t){this._geometry&&this._geometry.copyVerticesData(e,t)}getVertexBuffer(e,t){return this._geometry?(t?void 0:this._userInstancedBuffersStorage?.vertexBuffers[e])??this._geometry.getVertexBuffer(e):null}isVerticesDataPresent(e,t){return this._geometry?!t&&void 0!==this._userInstancedBuffersStorage?.vertexBuffers[e]||this._geometry.isVerticesDataPresent(e):!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)}isVertexBufferUpdatable(e,t){if(!this._geometry)return!!this._delayInfo&&-1!==this._delayInfo.indexOf(e);if(!t){const t=this._userInstancedBuffersStorage?.vertexBuffers[e];if(t)return t.isUpdatable()}return this._geometry.isVertexBufferUpdatable(e)}getVerticesDataKinds(e){if(!this._geometry){const e=[];if(this._delayInfo)for(const t of this._delayInfo)e.push(t);return e}const t=this._geometry.getVerticesDataKinds();if(!e&&this._userInstancedBuffersStorage)for(const e in this._userInstancedBuffersStorage.vertexBuffers)-1===t.indexOf(e)&&t.push(e);return t}getTotalIndices(){return this._geometry?this._geometry.getTotalIndices():0}getIndices(e,t){return this._geometry?this._geometry.getIndices(e,t):[]}get isBlocked(){return null!==this._masterMesh&&void 0!==this._masterMesh}isReady(e=!1,t=!1){if(this.delayLoadState===dt.DELAYLOADSTATE_LOADING)return!1;if(!super.isReady(e))return!1;if(!this.subMeshes||0===this.subMeshes.length)return!0;if(!e)return!0;const s=this.getEngine(),i=this.getScene(),r=t||s.getCaps().instancedArrays&&(this.instances.length>0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||i.defaultMaterial;if(n)if(n._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,r))return!1}else if(!t.isReady(this,r))return!1}else if(!n.isReady(this,r))return!1;const a=s.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const i=t.values();for(let e=i.next();!0!==e.done;e=i.next()){const t=e.value;if(t&&(!t.getShadowMap()?.renderList||t.getShadowMap()?.renderList&&-1!==t.getShadowMap()?.renderList?.indexOf(this))){const e=t.getShadowMap().renderPassIds??[s.currentRenderPassId];for(let i=0;i<e.length;++i){s.currentRenderPassId=e[i];for(const e of this.subMeshes)if(!t.isReady(e,r,e.getMaterial()?.needAlphaBlendingForMesh(this)??!1))return s.currentRenderPassId=a,!1}s.currentRenderPassId=a}}}for(const e of this._internalMeshDataInfo._LODLevels)if(e.mesh&&!e.mesh.isReady(r))return!1;return!0}get areNormalsFrozen(){return this._internalMeshDataInfo._areNormalsFrozen}freezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!0,this}unfreezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!1,this}set overridenInstanceCount(e){this._instanceDataStorage.overridenInstanceCount=e}_getInstanceDataStorage(){if(this._instanceDataStorage.useMonoDataStorageRenderPass)return this._instanceDataStorage.dataStorageRenderPass;const e=this._instanceDataStorage.engine.currentRenderPassId;let t=this._instanceDataStorage.renderPasses[e];return t||(t=new kn,this._instanceDataStorage.renderPasses[e]=t),t}_preActivate(){const e=this._internalMeshDataInfo,t=this.getScene().getRenderId();return e._preActivateId===t||(e._preActivateId=t,this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass.visibleInstances=null:this._getInstanceDataStorage().visibleInstances=null),this}_preActivateForIntermediateRendering(e){const t=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._getInstanceDataStorage();return t.visibleInstances&&(t.visibleInstances.intermediateDefaultRenderId=e),this}_registerInstanceForRenderId(e,t){const s=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._getInstanceDataStorage();return s.visibleInstances||(s.visibleInstances={defaultRenderId:t,selfDefaultRenderId:this._renderId,intermediateDefaultRenderId:-1}),s.visibleInstances[t]||(void 0===s.previousRenderId||this._instanceDataStorage.useMonoDataStorageRenderPass&&!this._instanceDataStorage.isFrozen||delete s.visibleInstances[s.previousRenderId],s.previousRenderId=t,s.visibleInstances[t]=new Array),s.visibleInstances[t].push(e),this}_afterComputeWorldMatrix(){super._afterComputeWorldMatrix(),this.hasThinInstances&&(this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1))}_postActivate(){this.edgesShareWithInstances&&this.edgesRenderer&&this.edgesRenderer.isEnabled&&this._renderingGroup&&(this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer),this.edgesRenderer.customInstances.push(this.getWorldMatrix()))}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let s;s="object"==typeof e?e:{applySkeleton:e,applyMorph:t};const i=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getData(s,null,Gi.PositionKind),i),this}_createGlobalSubMesh(e){const t=this.getTotalVertices();if(!t||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){const s=this.getIndices();if(!s)return null;const i=s.length;let r=!1;if(e)r=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>i){r=!0;break}if(e.verticesStart+e.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new nr(0,0,t,0,this.getTotalIndices()||(this.isUnIndexed?t:0),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let s=t/e|0,i=0;for(;s%3!=0;)s++;this.releaseSubMeshes();for(let r=0;r<e&&!(i>=t);r++)nr.CreateFromIndices(0,i,i+s>=t?t-i:s,this,void 0,!1),i+=s;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,s=!1,i){if(this._geometry)this._geometry.setVerticesData(e,t,s,i);else{const i=new or;i.set(t,e);const r=this.getScene();new lr(lr.RandomId(),r,i,s,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const s=this.getVertexBuffer(e);s&&s.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0,s=null){return this._geometry||(this._geometry=lr.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,s,t),this}updateVerticesData(e,t,s,i){return this._geometry?(i?(this.makeGeometryUnique(),this.updateVerticesData(e,t,s,!1)):this._geometry.updateVerticesData(e,t,s),this):this}updateMeshPositions(e,t=!0){const s=this.getVerticesData(Gi.PositionKind);if(!s)return this;if(e(s),this.updateVerticesData(Gi.PositionKind,s,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(Gi.NormalKind);if(!t)return this;or.ComputeNormals(s,e,t),this.updateVerticesData(Gi.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(1===this._geometry.meshes.length)return this;const e=this._geometry,t=this._geometry.copy(lr.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,s,i=null){let r=this._geometry;r||(r=new lr(lr.RandomId(),this.getScene(),void 0,void 0,this)),r.setIndexBuffer(e,t,s,i)}setIndices(e,t=null,s=!1,i=!1){if(this._geometry)this._geometry.setIndices(e,t,s,i);else{const i=new or;i.indices=e;const r=this.getScene();new lr(lr.RandomId(),r,i,s,this,t)}return this}updateIndices(e,t,s=!1){return this._geometry?(this._geometry.updateIndices(e,t,s),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,s,i=!0){if(!this._geometry)return this;const r=this.getScene().getEngine();let n;if(this._unIndexed)if(this._getRenderingFillMode(s)===Cn.WireFrameFillMode)n=e._getLinesIndexBuffer(this.getIndices(),r);else n=null;else switch(this._getRenderingFillMode(s)){case Cn.PointFillMode:n=null;break;case Cn.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case Cn.TriangleFillMode:n=this._geometry.getIndexBuffer()}return this._bindDirect(t,n,i)}_bindDirect(e,t,s=!0){if(!this._geometry)return this;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(e),s&&this._userInstancedBuffersStorage&&!this.hasThinInstances){if(!this._instanceDataStorage.useMonoDataStorageRenderPass&&this._userInstancedBuffersStorage.renderPasses&&this._userInstancedBuffersStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId]){const e=this._userInstancedBuffersStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];for(const t in e)this._userInstancedBuffersStorage.vertexBuffers[t]=e[t]}this._geometry._bind(e,t,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects)}else this._geometry._bind(e,t);return this}_draw(e,t,s){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const i=this.getScene().getEngine(),r=i._currentMaterialContext,n=r&&r.useVertexPulling;return this._unIndexed&&t!==Cn.WireFrameFillMode||t==Cn.PointFillMode?i.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||s):t==Cn.WireFrameFillMode?i.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||s):n?i.drawArraysType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||s):i.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||s),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){const s=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._getInstanceDataStorage();if(this._instanceDataStorage.isFrozen){if(t)return s.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,s.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,s.batchCacheReplacementModeInFrozenMode;if(s.previousBatch)return s.previousBatch}const i=this.getScene(),r=i._isInIntermediateRendering(),n=r?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,a=s.batchCache;if(a.mustReturn=!1,a.renderSelf[e]=t||!n&&this.isEnabled()&&this.isVisible,a.visibleInstances[e]=null,s.visibleInstances&&!t){const t=s.visibleInstances,n=i.getRenderId(),o=r?t.intermediateDefaultRenderId:t.defaultRenderId;a.visibleInstances[e]=t[n],!a.visibleInstances[e]&&o&&(a.visibleInstances[e]=t[o])}return a.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==a.visibleInstances[e]&&void 0!==a.visibleInstances[e],s.previousBatch=a,a}_updateInstancedBuffers(e,t,s,i,r,n){const a=t.visibleInstances[e._id],o=a?a.length:0,h=t.parent,l=this._instanceDataStorage;let c=h.instancesBuffer,u=h.instancesPreviousBuffer,d=0,_=0;const p=t.renderSelf[e._id],f=this._scene.floatingOriginOffset,g=!c||s!==h.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!h.instancesPreviousBuffer;if(this._instanceDataStorage.manualUpdate||l.isFrozen&&!g)_=(p?1:0)+o;else{const t=this.getWorldMatrix();if(p){this._scene.needsPreviousWorldMatrices&&(l.masterMeshPreviousWorldMatrix?(l.masterMeshPreviousWorldMatrix.copyToArray(h.instancesPreviousData,d),l.masterMeshPreviousWorldMatrix.copyFrom(t)):(l.masterMeshPreviousWorldMatrix=t.clone(),l.masterMeshPreviousWorldMatrix.copyToArray(h.instancesPreviousData,d))),t.copyToArray(h.instancesData,d);const e=t.asArray();h.instancesData[d+12]=e[12]-f.x,h.instancesData[d+13]=e[13]-f.y,h.instancesData[d+14]=e[14]-f.z,d+=16,_++}if(a){if(Xn.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&e.getMaterial()?.needAlphaBlendingForMesh(e.getRenderingMesh())){const e=this._scene.activeCamera.globalPosition;for(let t=0;t<a.length;t++){const s=a[t];s._distanceToCamera=xe.Distance(s.getBoundingInfo().boundingSphere.centerWorld,e)}a.sort((e,t)=>e._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera<t._distanceToCamera?1:0)}for(let e=0;e<a.length;e++){const t=a[e],s=t.getWorldMatrix();s.copyToArray(h.instancesData,d),this._scene.needsPreviousWorldMatrices&&(t._previousWorldMatrix?(t._previousWorldMatrix.copyToArray(h.instancesPreviousData,d),t._previousWorldMatrix.copyFrom(s)):(t._previousWorldMatrix=s.clone(),t._previousWorldMatrix.copyToArray(h.instancesPreviousData,d)));const i=s.asArray();h.instancesData[d+12]=i[12]-f.x,h.instancesData[d+13]=i[13]-f.y,h.instancesData[d+14]=i[14]-f.z,d+=16,_++}}}if(g){let e;if(c&&c.dispose(),u&&u.dispose(),c=new ki(i,h.instancesData,!0,16,!1,!0),h.instancesBuffer=c,this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this._instanceDataStorage.useMonoDataStorageRenderPass)e=this._userInstancedBuffersStorage.vertexBuffers;else{this._userInstancedBuffersStorage.renderPasses||(this._userInstancedBuffersStorage.renderPasses={});const t=this._instanceDataStorage.engine.currentRenderPassId;e=this._userInstancedBuffersStorage.renderPasses[t],e||(this._userInstancedBuffersStorage.renderPasses[t]=e={})}e.world0=c.createVertexBuffer("world0",0,4),e.world1=c.createVertexBuffer("world1",4,4),e.world2=c.createVertexBuffer("world2",8,4),e.world3=c.createVertexBuffer("world3",12,4),this._scene.needsPreviousWorldMatrices&&(u=new ki(i,h.instancesPreviousData,!0,16,!1,!0),h.instancesPreviousBuffer=u,e.previousWorld0=u.createVertexBuffer("previousWorld0",0,4),e.previousWorld1=u.createVertexBuffer("previousWorld1",4,4),e.previousWorld2=u.createVertexBuffer("previousWorld2",8,4),e.previousWorld3=u.createVertexBuffer("previousWorld3",12,4)),this._invalidateInstanceVertexArrayObject()}else this._instanceDataStorage.isFrozen&&!this._instanceDataStorage.forceMatrixUpdates||(c.updateDirectly(h.instancesData,0,_),!this._scene.needsPreviousWorldMatrices||this._instanceDataStorage.manualUpdate&&!this._instanceDataStorage.previousManualUpdate||u.updateDirectly(h.instancesPreviousData,0,_));this._processInstancedBuffers(a,p),n&&void 0!==r&&(this.getScene()._activeIndices.addCount(e.indexCount*_,!1),i._currentDrawContext&&(i._currentDrawContext.useInstancing=!0),this._bind(e,n,r),this._draw(e,r,_)),!this._scene.needsPreviousWorldMatrices||g||!this._instanceDataStorage.manualUpdate||this._instanceDataStorage.isFrozen&&!this._instanceDataStorage.forceMatrixUpdates||this._instanceDataStorage.previousManualUpdate||u.updateDirectly(h.instancesData,0,_)}_renderWithInstances(e,t,s,i,r){const n=s.visibleInstances[e._id],a=n?n.length:0,o=s.parent,h=o.instancesBufferSize,l=16*(a+1)*4;for(;o.instancesBufferSize<l;)o.instancesBufferSize*=2;return o.instancesData&&h==o.instancesBufferSize||(o.instancesData=new Float32Array(o.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!o.instancesPreviousData||h!=o.instancesBufferSize)&&(o.instancesPreviousData=new Float32Array(o.instancesBufferSize/4)),this._updateInstancedBuffers(e,s,h,r,t,i),r.unbindInstanceAttributes(),this}_renderWithThinInstances(e,t,s,i){const r=this._thinInstanceDataStorage?.instancesCount??0;this.getScene()._activeIndices.addCount(e.indexCount*r,!1),i._currentDrawContext&&(i._currentDrawContext.useInstancing=!0),this._bind(e,s,t),this._draw(e,t,r),this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&this._thinInstanceDataStorage.matrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,r):this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.matrixData,!1)),i.unbindInstanceAttributes()}_processInstancedBuffers(e,t){}_processRendering(e,t,s,i,r,n,a,o){const h=this.getScene(),l=h.getEngine();if(i=this._getRenderingFillMode(i),n&&t.getRenderingMesh().hasThinInstances)return this._renderWithThinInstances(t,i,s,l),this;if(n)this._renderWithInstances(t,i,r,s,l);else{l._currentDrawContext&&(l._currentDrawContext.useInstancing=!1);let s=0;r.renderSelf[t._id]&&(a&&a(!1,e.getWorldMatrix(),o),s++,this._draw(t,i,this._instanceDataStorage.overridenInstanceCount));const n=r.visibleInstances[t._id];if(n){const e=n.length;s+=e;for(let s=0;s<e;s++){const e=n[s].getWorldMatrix();a&&a(!0,e,o),this._draw(t,i)}}h._activeIndices.addCount(t.indexCount*s,!1)}return this}_disposeInstanceDataStorageRenderPass(e,t=!1){e?.instancesBuffer&&(t&&e.instancesBuffer.dispose(),e.instancesBuffer=null),e?.instancesPreviousBuffer&&(t&&e.instancesPreviousBuffer.dispose(),e.instancesPreviousBuffer=null)}_rebuild(e=!1){for(const t in this._instanceDataStorage.renderPasses){const s=this._instanceDataStorage.renderPasses[t];this._disposeInstanceDataStorageRenderPass(s,e)}if(this._disposeInstanceDataStorageRenderPass(this._instanceDataStorage.dataStorageRenderPass,e),this._userInstancedBuffersStorage){for(const t in this._userInstancedBuffersStorage.vertexBuffers){const s=this._userInstancedBuffersStorage.vertexBuffers[t];s&&(e&&s.dispose(),this._userInstancedBuffersStorage.vertexBuffers[t]=null)}this._userInstancedBuffersStorage.vertexArrayObjects&&(this._userInstancedBuffersStorage.vertexArrayObjects={})}this._internalMeshDataInfo._effectiveMaterial=null,super._rebuild(e)}_releaseRenderPassId(e){const t=this._instanceDataStorage.renderPasses[e];if(t&&(this._disposeInstanceDataStorageRenderPass(t,!0),delete this._instanceDataStorage.renderPasses[e]),this._userInstancedBuffersStorage?.renderPasses){const t=this._userInstancedBuffersStorage.renderPasses[e];if(t)for(const e in t)t[e]?.dispose();delete this._userInstancedBuffersStorage.renderPasses[e]}}_freeze(){if(this.subMeshes){for(let e=0;e<this.subMeshes.length;e++)this._getInstancesRenderList(e);this._internalMeshDataInfo._effectiveMaterial=null,this._instanceDataStorage.isFrozen=!0}}_unFreeze(){this._instanceDataStorage.isFrozen=!1;for(const e in this._instanceDataStorage.renderPasses){this._instanceDataStorage.renderPasses[e].previousBatch=null}this._instanceDataStorage.dataStorageRenderPass&&(this._instanceDataStorage.dataStorageRenderPass.previousBatch=null)}renderWithRenderPassId(e,t,s,i,r=!0){const n=this._scene.getEngine(),a=n.currentRenderPassId;if(void 0!==e&&(n.currentRenderPassId=e),i)(!r||r&&i.isInFrustum(this._scene._frustumPlanes))&&this.render(i,!!t,s);else for(let e=0;e<this.subMeshes.length;e++){const i=this.subMeshes[e];(!r||r&&i.isInFrustum(this._scene._frustumPlanes))&&this.render(i,!!t,s)}return void 0!==e&&(n.currentRenderPassId=a),this}directRender(){if(!this.subMeshes)return this;for(const e of this.subMeshes)this.render(e,!1);return this}render(e,t,s){const i=this.getScene(),r=i.getEngine();this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!1;const n=i.activeCameras?.length??0,a=n>1&&i.activeCamera===i.activeCameras[0]||n<=1,o=this._occlusionDataStorage&&-1!==this._occlusionDataStorage.occlusionForRenderPassId&&this._occlusionDataStorage.occlusionForRenderPassId!==r.currentRenderPassId;if(a&&this._checkOcclusionQuery(o)&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const h=this._getInstancesRenderList(e._id,!!s);if(h.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let l=0,c=null;this.ignoreCameraMaxZ&&i.activeCamera&&!i._isInIntermediateRendering()&&(l=i.activeCamera.maxZ,c=i.activeCamera,i.activeCamera.maxZ=0,i.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const u=e.getRenderingMesh(),d=h.hardwareInstancedRendering[e._id]||u.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,_=this._instanceDataStorage,p=e.getMaterial();if(!p)return c&&(c.maxZ=l,i.updateTransformMatrix(!0)),this;if(_.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===p){if(p._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!p._storeEffectOnSubMeshes&&!p._getDrawWrapper()._wasPreviouslyReady)return c&&(c.maxZ=l,i.updateTransformMatrix(!0)),this}else{if(p._storeEffectOnSubMeshes){if(!p.isReadyForSubMesh(this,e,d))return c&&(c.maxZ=l,i.updateTransformMatrix(!0)),this}else if(!p.isReady(this,d))return c&&(c.maxZ=l,i.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=p}if(t){const e=this._internalMeshDataInfo._effectiveMaterial;if(1===e.alphaModes.length)r.setAlphaMode(e.alphaMode);else for(let t=0;t<e.alphaModes.length;t++){const s=e.alphaModes[t];r.setAlphaMode(void 0!==s?s:dt.ALPHA_COMBINE,!1,t)}}let f;f=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const g=f?.effect??null;for(const t of i._beforeRenderingMeshStage)t.action(this,e,h,g);if(!f||!g)return c&&(c.maxZ=l,i.updateTransformMatrix(!0)),this;const m=s||this;let T;if(!_.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||null!==this._internalMeshDataInfo._effectiveMaterial.sideOrientation||this._internalMeshDataInfo._effectiveMaterial._twoSidedLighting)){const e=m._getWorldMatrixDeterminant();T=this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this),e<0&&(T=T===Cn.ClockWiseSideOrientation?Cn.CounterClockWiseSideOrientation:Cn.ClockWiseSideOrientation),this._internalMeshDataInfo._effectiveSideOrientation=T}const E=this._internalMeshDataInfo._effectiveMaterial._preBind(f,this._internalMeshDataInfo._effectiveSideOrientation);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&r.setDepthWrite(!0);const R=this._internalMeshDataInfo._effectiveMaterial,b=R.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),d||this._bind(e,g,b,!1);const A=m.getWorldMatrix();R._storeEffectOnSubMeshes?R.bindForSubMesh(A,this,e):R.bind(A,this),!R.backFaceCulling&&R.separateCullingPass&&(r.setState(!0,R.zOffset,!1,!E,R.cullBackFaces,R.stencil,R.zOffsetUnits),this._processRendering(this,e,g,b,h,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),r.setState(!0,R.zOffset,!1,E,R.cullBackFaces,R.stencil,R.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,g,b,h,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of i._afterRenderingMeshStage)t.action(this,e,h,g);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),c&&(c.maxZ=l,i.updateTransformMatrix(!0)),2!==i.performancePriority||_.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(Gi.MatricesWeightsKind)&&(this.isVerticesDataPresent(Gi.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(Gi.MatricesWeightsKind),t=e.length;for(let s=0;s<t;s+=4){const t=e[s]+e[s+1]+e[s+2]+e[s+3];if(0===t)e[s]=1;else{const i=1/t;e[s]*=i,e[s+1]*=i,e[s+2]*=i,e[s+3]*=i}}this.setVerticesData(Gi.MatricesWeightsKind,e)}_normalizeSkinWeightsAndExtra(){const e=this.getVerticesData(Gi.MatricesWeightsExtraKind),t=this.getVerticesData(Gi.MatricesWeightsKind),s=t.length;for(let i=0;i<s;i+=4){let s=t[i]+t[i+1]+t[i+2]+t[i+3];if(s+=e[i]+e[i+1]+e[i+2]+e[i+3],0===s)t[i]=1;else{const r=1/s;t[i]*=r,t[i+1]*=r,t[i+2]*=r,t[i+3]*=r,e[i]*=r,e[i+1]*=r,e[i+2]*=r,e[i+3]*=r}}this.setVerticesData(Gi.MatricesWeightsKind,t),this.setVerticesData(Gi.MatricesWeightsKind,e)}validateSkinning(){const e=this.getVerticesData(Gi.MatricesWeightsExtraKind),t=this.getVerticesData(Gi.MatricesWeightsKind);if(null===t||null==this.skeleton)return{skinned:!1,valid:!0,report:"not skinned"};const s=t.length;let i=0,r=0,n=0,a=0;const o=null===e?4:8,h=[];for(let e=0;e<=o;e++)h[e]=0;for(let l=0;l<s;l+=4){let s=t[l],c=s,u=0===c?0:1;for(let r=1;r<o;r++){const n=r<4?t[l+r]:e[l+r-4];n>s&&i++,0!==n&&u++,c+=n,s=n}if(h[u]++,u>n&&(n=u),0===c)r++;else{const s=1/c;let i=0;for(let r=0;r<o;r++)i+=r<4?Math.abs(t[l+r]-t[l+r]*s):Math.abs(e[l+r-4]-e[l+r-4]*s);i>.001&&a++}}const l=this.skeleton.bones.length,c=this.getVerticesData(Gi.MatricesIndicesKind),u=this.getVerticesData(Gi.MatricesIndicesExtraKind);let d=0;for(let e=0;e<s;e+=4)for(let t=0;t<o;t++){const s=t<4?c[e+t]:u[e+t-4];(s>=l||s<0)&&d++}return{skinned:!0,valid:0===r&&0===a&&0===d,report:"Number of Weights = "+s/4+"\nMaximum influences = "+n+"\nMissing Weights = "+r+"\nNot Sorted = "+i+"\nNot Normalized = "+a+"\nWeightCounts = ["+h+"]\nNumber of bones = "+l+"\nBad Bone Indices = "+d}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===dt.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=dt.DELAYLOADSTATE_LOADING,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return(async()=>{try{const s=await e._loadDelayedFileAsync(this.delayLoadingFile,t,!0);s instanceof ArrayBuffer?this._delayLoadingFunction(s,this):this._delayLoadingFunction(JSON.parse(s),this);for(const e of this.instances)e.refreshBoundingInfo(),e._syncSubMeshes();this.delayLoadState=dt.DELAYLOADSTATE_LOADED,e.removePendingData(this)}catch(t){e.removePendingData(this),e.isDisposed||a.Error(`Unable to delay load geometry data for mesh "${this.name}" from "${this.delayLoadingFile}": ${t}`)}})(),this}isInFrustum(e){return this.delayLoadState!==dt.DELAYLOADSTATE_LOADING&&(!!super.isInFrustum(e)&&(this._checkDelayState(),!0))}setMaterialById(e){const t=this.getScene().materials;let s;for(s=t.length-1;s>-1;s--)if(t[s].id===e)return this.material=t[s],this;const i=this.getScene().multiMaterials;for(s=i.length-1;s>-1;s--)if(i[s].id===e)return this.material=i[s],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(Gi.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let s=this.getVerticesData(Gi.PositionKind);const i=xe.Zero();let r;for(r=0;r<s.length;r+=3)xe.TransformCoordinatesFromFloatsToRef(s[r],s[r+1],s[r+2],e,i).toArray(s,r);if(this.setVerticesData(Gi.PositionKind,s,this.getVertexBuffer(Gi.PositionKind).isUpdatable()),this.isVerticesDataPresent(Gi.NormalKind)){for(s=this.getVerticesData(Gi.NormalKind),r=0;r<s.length;r+=3)xe.TransformNormalFromFloatsToRef(s[r],s[r+1],s[r+2],e,i).normalize().toArray(s,r);this.setVerticesData(Gi.NormalKind,s,this.getVertexBuffer(Gi.NormalKind).isUpdatable())}if(this.isVerticesDataPresent(Gi.TangentKind)){for(s=this.getVerticesData(Gi.TangentKind),r=0;r<s.length;r+=4)xe.TransformNormalFromFloatsToRef(s[r],s[r+1],s[r+2],e,i).normalize().toArray(s,r);this.setVerticesData(Gi.TangentKind,s,this.getVertexBuffer(Gi.TangentKind).isUpdatable())}return e.determinant()<0&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=t,this}bakeCurrentTransformIntoVertices(e=!0,t=!1){return t&&this.makeGeometryUnique(),this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this}get _positions(){return this._internalAbstractMeshDataInfo._positions||this._geometry&&this._geometry._positions||null}_resetPointsArrayCache(){return this._geometry&&this._geometry._resetPointsArrayCache(),this}_generatePointsArray(){return!!this._geometry&&this._geometry._generatePointsArray()}clone(e="",t=null,s,i=!0){if(t&&void 0===t._addToSceneRootNodes){const s=t;return Wn.source=this,Wn.doNotCloneChildren=s.doNotCloneChildren,Wn.clonePhysicsImpostor=s.clonePhysicsImpostor,Wn.cloneThinInstances=s.cloneThinInstances,new Xn(e,this.getScene(),Wn)}return new Xn(e,this.getScene(),t,this,s,i)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);const s=this._internalMeshDataInfo;if(s._onBeforeDrawObservable&&s._onBeforeDrawObservable.clear(),s._onBeforeBindObservable&&s._onBeforeBindObservable.clear(),s._onBeforeRenderObservable&&s._onBeforeRenderObservable.clear(),s._onAfterRenderObservable&&s._onAfterRenderObservable.clear(),s._onBetweenPassObservable&&s._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(s.meshMap)for(const e in s.meshMap){const t=s.meshMap[e];t&&(t._internalMeshDataInfo._source=null,s.meshMap[e]=void 0)}s._source&&s._source._internalMeshDataInfo.meshMap&&(s._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else{const e=this.getScene().meshes;for(const t of e){const e=t;e._internalMeshDataInfo&&e._internalMeshDataInfo._source&&e._internalMeshDataInfo._source===this&&(e._internalMeshDataInfo._source=null)}}s._source=null,this._disposeInstanceSpecificData(),this._disposeThinInstanceSpecificData(),this._internalMeshDataInfo._checkReadinessObserver&&this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),super.dispose(e,t)}_disposeInstanceSpecificData(){}_disposeThinInstanceSpecificData(){}_invalidateInstanceVertexArrayObject(){}applyDisplacementMap(e,t,s,i,r,n,a=!1,o){const h=this.getScene();return _s(e,e=>{const o=e.width,h=e.height,l=this.getEngine().createCanvas(o,h).getContext("2d");l.drawImage(e,0,0);const c=l.getImageData(0,0,o,h).data;this.applyDisplacementMapFromBuffer(c,o,h,t,s,r,n,a),i&&i(this)},o||(()=>{}),h.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,s,i,r,n,o,h=!1){if(!this.isVerticesDataPresent(Gi.PositionKind)||!this.isVerticesDataPresent(Gi.NormalKind)||!this.isVerticesDataPresent(Gi.UVKind))return a.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(Gi.PositionKind,!0,!0),c=this.getVerticesData(Gi.NormalKind),u=this.getVerticesData(Gi.UVKind);let d=xe.Zero();const _=xe.Zero(),p=Me.Zero();n=n||Me.Zero(),o=o||new Me(1,1);for(let a=0;a<l.length;a+=3){xe.FromArrayToRef(l,a,d),xe.FromArrayToRef(c,a,_),Me.FromArrayToRef(u,a/3*2,p);const h=4*((Math.abs(p.x*o.x+n.x%1)*(t-1)%t|0)+(Math.abs(p.y*o.y+n.y%1)*(s-1)%s|0)*t),f=.3*(e[h]/255)+.59*(e[h+1]/255)+.11*(e[h+2]/255);_.normalize(),_.scaleInPlace(i+(r-i)*f),d=d.add(_),d.toArray(l,a)}return or.ComputeNormals(l,this.getIndices(),c),h?(this.setVerticesData(Gi.PositionKind,l),this.setVerticesData(Gi.NormalKind,c),this.setVerticesData(Gi.UVKind,u)):(this.updateVerticesData(Gi.PositionKind,l),this.updateVerticesData(Gi.NormalKind,c)),this}_getFlattenedNormals(e,t){const s=new Float32Array(3*e.length);let i=0;const r=this.sideOrientation===(this._scene.useRightHandedSystem?dt.MATERIAL_CounterClockWiseSideOrientation:dt.MATERIAL_ClockWiseSideOrientation);for(let n=0;n<e.length;n+=3){const a=xe.FromArray(t,3*e[n]),o=xe.FromArray(t,3*e[n+1]),h=xe.FromArray(t,3*e[n+2]),l=a.subtract(o),c=h.subtract(o),u=xe.Normalize(xe.Cross(l,c));r&&u.scaleInPlace(-1);for(let e=0;e<3;e++)s[i++]=u.x,s[i++]=u.y,s[i++]=u.z}return s}_convertToUnIndexedMesh(e=!1){const t=this.getVerticesDataKinds().filter(e=>!this.getVertexBuffer(e)?.getIsInstanced()),s=this.getIndices(!1,!0),i={},r=(e,t)=>{const i=new Float32Array(s.length*t);let r=0;for(let n=0;n<s.length;n++)for(let a=0;a<t;a++)i[r++]=e[s[n]*t+a];return i},n=this.getBoundingInfo(),a=this.geometry?this.subMeshes.slice(0):[];for(const e of t)i[e]=this.getVerticesData(e);for(const n of t){const t=this.getVertexBuffer(n),a=t.getSize();if(e&&n===Gi.NormalKind){const e=this._getFlattenedNormals(s,i[Gi.PositionKind]);this.setVerticesData(Gi.NormalKind,e,t.isUpdatable(),a)}else this.setVerticesData(n,r(i[n],a),t.isUpdatable(),a)}if(this.morphTargetManager){for(let t=0;t<this.morphTargetManager.numTargets;t++){const i=this.morphTargetManager.getTarget(t),n=i.getPositions();i.setPositions(r(n,3));const a=i.getNormals();a&&i.setNormals(e?this._getFlattenedNormals(s,n):r(a,3));const o=i.getTangents();o&&i.setTangents(r(o,3));const h=i.getUVs();h&&i.setUVs(r(h,2));const l=i.getColors();l&&i.setColors(r(l,4))}this.morphTargetManager.synchronize()}for(let e=0;e<s.length;e++)s[e]=e;this.setIndices(s),this._unIndexed=!0,this.releaseSubMeshes();for(const e of a){const t=e.getBoundingInfo();nr.AddToMesh(e.materialIndex,e.indexStart,e.indexCount,e.indexStart,e.indexCount,this).setBoundingInfo(t)}return this.setBoundingInfo(n),this.synchronizeInstances(),this}convertToFlatShadedMesh(){return this._convertToUnIndexedMesh(!0)}convertToUnIndexedMesh(){return this._convertToUnIndexedMesh()}flipFaces(e=!1){const t=or.ExtractFromMesh(this);let s;if(e&&this.isVerticesDataPresent(Gi.NormalKind)&&t.normals){for(s=0;s<t.normals.length;s++)t.normals[s]*=-1;this.setVerticesData(Gi.NormalKind,t.normals,this.isVertexBufferUpdatable(Gi.NormalKind))}if(t.indices){let e;for(s=0;s<t.indices.length;s+=3)e=t.indices[s+1],t.indices[s+1]=t.indices[s+2],t.indices[s+2]=e;this.setIndices(t.indices,null,this.isVertexBufferUpdatable(Gi.PositionKind),!0)}return this}increaseVertices(e=1){const t=or.ExtractFromMesh(this),s=t.indices&&!Array.isArray(t.indices)&&Array.from?Array.from(t.indices):t.indices,i=t.positions&&!Array.isArray(t.positions)&&Array.from?Array.from(t.positions):t.positions,r=t.uvs&&!Array.isArray(t.uvs)&&Array.from?Array.from(t.uvs):t.uvs,n=t.normals&&!Array.isArray(t.normals)&&Array.from?Array.from(t.normals):t.normals;if(s&&i){t.indices=s,t.positions=i,r&&(t.uvs=r),n&&(t.normals=n);const a=e+1,o=[];for(let e=0;e<a+1;e++)o[e]=[];let h,l;const c=new xe(0,0,0),u=new xe(0,0,0),d=new Me(0,0),_=[],p=[],f=[];let g,m,T,E=i.length;r&&(m=r.length),n&&(T=n.length);for(let e=0;e<s.length;e+=3){p[0]=s[e],p[1]=s[e+1],p[2]=s[e+2];for(let e=0;e<3;e++)if(h=p[e],l=p[(e+1)%3],void 0===f[h]&&void 0===f[l]?(f[h]=[],f[l]=[]):(void 0===f[h]&&(f[h]=[]),void 0===f[l]&&(f[l]=[])),void 0===f[h][l]&&void 0===f[l][h]){f[h][l]=[],c.x=(i[3*l]-i[3*h])/a,c.y=(i[3*l+1]-i[3*h+1])/a,c.z=(i[3*l+2]-i[3*h+2])/a,n&&(u.x=(n[3*l]-n[3*h])/a,u.y=(n[3*l+1]-n[3*h+1])/a,u.z=(n[3*l+2]-n[3*h+2])/a),r&&(d.x=(r[2*l]-r[2*h])/a,d.y=(r[2*l+1]-r[2*h+1])/a),f[h][l].push(h);for(let e=1;e<a;e++)f[h][l].push(i.length/3),i[E++]=i[3*h]+e*c.x,i[E++]=i[3*h+1]+e*c.y,i[E++]=i[3*h+2]+e*c.z,n&&(n[T++]=n[3*h]+e*u.x,n[T++]=n[3*h+1]+e*u.y,n[T++]=n[3*h+2]+e*u.z),r&&(r[m++]=r[2*h]+e*d.x,r[m++]=r[2*h+1]+e*d.y);f[h][l].push(l),f[l][h]=[],g=f[h][l].length;for(let e=0;e<g;e++)f[l][h][e]=f[h][l][g-1-e]}o[0][0]=s[e],o[1][0]=f[s[e]][s[e+1]][1],o[1][1]=f[s[e]][s[e+2]][1];for(let t=2;t<a;t++){o[t][0]=f[s[e]][s[e+1]][t],o[t][t]=f[s[e]][s[e+2]][t],c.x=(i[3*o[t][t]]-i[3*o[t][0]])/t,c.y=(i[3*o[t][t]+1]-i[3*o[t][0]+1])/t,c.z=(i[3*o[t][t]+2]-i[3*o[t][0]+2])/t,n&&(u.x=(n[3*o[t][t]]-n[3*o[t][0]])/t,u.y=(n[3*o[t][t]+1]-n[3*o[t][0]+1])/t,u.z=(n[3*o[t][t]+2]-n[3*o[t][0]+2])/t),r&&(d.x=(r[2*o[t][t]]-r[2*o[t][0]])/t,d.y=(r[2*o[t][t]+1]-r[2*o[t][0]+1])/t);for(let e=1;e<t;e++)o[t][e]=i.length/3,i[E++]=i[3*o[t][0]]+e*c.x,i[E++]=i[3*o[t][0]+1]+e*c.y,i[E++]=i[3*o[t][0]+2]+e*c.z,n&&(n[T++]=n[3*o[t][0]]+e*u.x,n[T++]=n[3*o[t][0]+1]+e*u.y,n[T++]=n[3*o[t][0]+2]+e*u.z),r&&(r[m++]=r[2*o[t][0]]+e*d.x,r[m++]=r[2*o[t][0]+1]+e*d.y)}o[a]=f[s[e+1]][s[e+2]],_.push(o[0][0],o[1][0],o[1][1]);for(let e=1;e<a;e++){let t;for(t=0;t<e;t++)_.push(o[e][t],o[e+1][t],o[e+1][t+1]),_.push(o[e][t],o[e+1][t+1],o[e][t+1]);_.push(o[e][t],o[e+1][t],o[e+1][t+1])}}t.indices=_,t.applyToMesh(this,this.isVertexBufferUpdatable(Gi.PositionKind))}else a.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions")}forceSharedVertices(){const e=or.ExtractFromMesh(this),t=e.uvs,s=e.indices,i=e.positions,r=e.colors,n=e.matricesIndices,o=e.matricesWeights,h=e.matricesIndicesExtra,l=e.matricesWeightsExtra;if(void 0===s||void 0===i||null===s||null===i)a.Warn("VertexData contains empty entries");else{const a=[],c=[],u=[],d=[],_=[],p=[],f=[],g=[];let m,T=0;const E={};let R,b;for(let e=0;e<s.length;e+=3){b=[s[e],s[e+1],s[e+2]],m=[];for(let e=0;e<3;e++){m[e]="";for(let t=0;t<3;t++)Math.abs(i[3*b[e]+t])<1e-8&&(i[3*b[e]+t]=0),m[e]+=i[3*b[e]+t]+"|"}if(m[0]!=m[1]&&m[0]!=m[2]&&m[1]!=m[2])for(let e=0;e<3;e++){if(R=E[m[e]],void 0===R){E[m[e]]=T,R=T++;for(let t=0;t<3;t++)a.push(i[3*b[e]+t]);if(null!=r)for(let t=0;t<4;t++)d.push(r[4*b[e]+t]);if(null!=t)for(let s=0;s<2;s++)u.push(t[2*b[e]+s]);if(null!=n)for(let t=0;t<4;t++)_.push(n[4*b[e]+t]);if(null!=o)for(let t=0;t<4;t++)p.push(o[4*b[e]+t]);if(null!=h)for(let t=0;t<4;t++)f.push(h[4*b[e]+t]);if(null!=l)for(let t=0;t<4;t++)g.push(l[4*b[e]+t])}c.push(R)}}const A=[];or.ComputeNormals(a,c,A),e.positions=a,e.indices=c,e.normals=A,null!=t&&(e.uvs=u),null!=r&&(e.colors=d),null!=n&&(e.matricesIndices=_),null!=o&&(e.matricesWeights=p),null!=h&&(e.matricesIndicesExtra=f),null!=o&&(e.matricesWeightsExtra=g),e.applyToMesh(this,this.isVertexBufferUpdatable(Gi.PositionKind))}}static _instancedMeshFactory(e,t){throw Le("InstancedMesh")}static _PhysicsImpostorParser(e,t,s){throw Le("PhysicsImpostor")}createInstance(e){const t=Xn._instancedMeshFactory(e,this);return t.parent=this.parent,t}synchronizeInstances(){for(let e=0;e<this.instances.length;e++){this.instances[e]._syncSubMeshes()}return this}optimizeIndices(e){const t=this.getIndices(),s=this.getVerticesData(Gi.PositionKind);if(!s||!t)return this;const i=[];for(let e=0;e<s.length;e+=3)i.push(xe.FromArray(s,e));const r=[];return Ns.SyncAsyncForLoop(i.length,40,e=>{const t=i.length-1-e,s=i[t];for(let e=0;e<t;++e){const n=i[e];if(s.equals(n)){r[t]=e;break}}},()=>{for(let e=0;e<t.length;++e)t[e]=r[t[e]]||t[e];const s=this.subMeshes.slice(0);this.setIndices(t),this.subMeshes=s,e&&e(this)}),this}serialize(e={}){e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,e.type=this.getClassName(),Ge&&Ge.HasTags(this)&&(e.tags=Ge.GetTags(this)),e.position=this.position.asArray(),this.rotationQuaternion?e.rotationQuaternion=this.rotationQuaternion.asArray():this.rotation&&(e.rotation=this.rotation.asArray()),e.scaling=this.scaling.asArray(),this._postMultiplyPivotMatrix?e.pivotMatrix=this.getPivotMatrix().asArray():e.localMatrix=this.getPivotMatrix().asArray(),e.isEnabled=this.isEnabled(!1),e.isVisible=this.isVisible,e.infiniteDistance=this.infiniteDistance,e.pickable=this.isPickable,e.receiveShadows=this.receiveShadows,e.billboardMode=this.billboardMode,e.visibility=this.visibility,e.alwaysSelectAsActiveMesh=this.alwaysSelectAsActiveMesh,e.checkCollisions=this.checkCollisions,e.ellipsoid=this.ellipsoid.asArray(),e.ellipsoidOffset=this.ellipsoidOffset.asArray(),e.doNotSyncBoundingInfo=this.doNotSyncBoundingInfo,e.isBlocker=this.isBlocker,e.sideOrientation=this.sideOrientation,this._isWorldMatrixFrozen&&(e.freezeWorldMatrix=!0),this.parent&&this.parent._serializeAsParent(e),e.isUnIndexed=this.isUnIndexed;const t=this._geometry;if(t&&this.subMeshes){e.geometryUniqueId=t.uniqueId,e.geometryId=t.id,e.subMeshes=[];for(let t=0;t<this.subMeshes.length;t++){const s=this.subMeshes[t];e.subMeshes.push({materialIndex:s.materialIndex,verticesStart:s.verticesStart,verticesCount:s.verticesCount,indexStart:s.indexStart,indexCount:s.indexCount})}}if(this.material?this.material.doNotSerialize||(e.materialUniqueId=this.material.uniqueId,e.materialId=this.material.id):(this.material=null,e.materialUniqueId=this._scene.defaultMaterial.uniqueId,e.materialId=this._scene.defaultMaterial.id),this.morphTargetManager&&(e.morphTargetManagerId=this.morphTargetManager.uniqueId),this.skeleton&&(e.skeletonId=this.skeleton.id,e.skeletonUniqueId=this.skeleton.uniqueId,e.numBoneInfluencers=this.numBoneInfluencers),this.getScene()._getComponent(Fn.NAME_PHYSICSENGINE)){const t=this.getPhysicsImpostor?.();t&&(e.physicsMass=t.getParam("mass"),e.physicsFriction=t.getParam("friction"),e.physicsRestitution=t.getParam("mass"),e.physicsImpostor=t.type)}this.metadata&&(e.metadata=this.metadata),e.instances=[];for(let t=0;t<this.instances.length;t++){const s=this.instances[t];if(s.doNotSerialize)continue;const i={name:s.name,id:s.id,isEnabled:s.isEnabled(!1),isVisible:s.isVisible,isPickable:s.isPickable,checkCollisions:s.checkCollisions,position:s.position.asArray(),scaling:s.scaling.asArray()};if(s.parent&&s.parent._serializeAsParent(i),s.rotationQuaternion?i.rotationQuaternion=s.rotationQuaternion.asArray():s.rotation&&(i.rotation=s.rotation.asArray()),this.getScene()._getComponent(Fn.NAME_PHYSICSENGINE)){const e=s.getPhysicsImpostor?.();e&&(i.physicsMass=e.getParam("mass"),i.physicsFriction=e.getParam("friction"),i.physicsRestitution=e.getParam("mass"),i.physicsImpostor=e.type)}s.metadata&&(i.metadata=s.metadata),s.actionManager&&(i.actions=s.actionManager.serialize(s.name)),e.instances.push(i),$e.AppendSerializedAnimations(s,i),i.ranges=s.serializeAnimationRanges()}if(this._thinInstanceDataStorage.instancesCount&&this._thinInstanceDataStorage.matrixData&&(e.thinInstances={instancesCount:this._thinInstanceDataStorage.instancesCount,matrixData:Array.from(this._thinInstanceDataStorage.matrixData),matrixBufferSize:this._thinInstanceDataStorage.matrixBufferSize,enablePicking:this.thinInstanceEnablePicking},this._userThinInstanceBuffersStorage)){const t={data:{},sizes:{},strides:{}};for(const e in this._userThinInstanceBuffersStorage.data)t.data[e]=Array.from(this._userThinInstanceBuffersStorage.data[e]),t.sizes[e]=this._userThinInstanceBuffersStorage.sizes[e],t.strides[e]=this._userThinInstanceBuffersStorage.strides[e];e.thinInstances.userThinInstance=t}return $e.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.layerMask=this.layerMask,e.alphaIndex=this.alphaIndex,e.hasVertexAlpha=this.hasVertexAlpha,e.overlayAlpha=this.overlayAlpha,e.overlayColor=this.overlayColor.asArray(),e.renderOverlay=this.renderOverlay,e.applyFog=this.applyFog,this.actionManager&&(e.actions=this.actionManager.serialize(this.name)),e}_syncGeometryWithMorphTargetManager(){if(!this.geometry)return;this._markSubMeshesAsAttributesDirty();const e=this._internalAbstractMeshDataInfo._morphTargetManager;if(e&&e.vertexCount){if(e.vertexCount!==this.getTotalVertices())return a.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."),void(this.morphTargetManager=null);if(e.isUsingTextureForTargets)return;for(let t=0;t<e.numInfluencers;t++){const s=e.getActiveTarget(t),i=s.getPositions();if(!i)return void a.Error("Invalid morph target. Target must have positions.");this.geometry.setVerticesData(Gi.PositionKind+t,i,!1,3);const r=s.getNormals();r&&this.geometry.setVerticesData(Gi.NormalKind+t,r,!1,3);const n=s.getTangents();n&&this.geometry.setVerticesData(Gi.TangentKind+t,n,!1,3);const o=s.getUVs();o&&this.geometry.setVerticesData(Gi.UVKind+"_"+t,o,!1,2);const h=s.getUV2s();h&&this.geometry.setVerticesData(Gi.UV2Kind+"_"+t,h,!1,2);const l=s.getColors();l&&this.geometry.setVerticesData(Gi.ColorKind+t,l,!1,4)}}else{let e=0;for(;this.geometry.isVerticesDataPresent(Gi.PositionKind+e);)this.geometry.removeVerticesData(Gi.PositionKind+e),this.geometry.isVerticesDataPresent(Gi.NormalKind+e)&&this.geometry.removeVerticesData(Gi.NormalKind+e),this.geometry.isVerticesDataPresent(Gi.TangentKind+e)&&this.geometry.removeVerticesData(Gi.TangentKind+e),this.geometry.isVerticesDataPresent(Gi.UVKind+"_"+e)&&this.geometry.removeVerticesData(Gi.UVKind+"_"+e),this.geometry.isVerticesDataPresent(Gi.UV2Kind+"_"+e)&&this.geometry.removeVerticesData(Gi.UV2Kind+"_"+e),this.geometry.isVerticesDataPresent(Gi.ColorKind+e)&&this.geometry.removeVerticesData(Gi.ColorKind+e),e++}}static Parse(e,t,s){let i,r=!1;if(e.type&&"LinesMesh"===e.type?i=Xn._LinesMeshParser(e,t):e.type&&"GroundMesh"===e.type?i=Xn._GroundMeshParser(e,t):e.type&&"GoldbergMesh"===e.type?i=Xn._GoldbergMeshParser(e,t):e.type&&"GreasedLineMesh"===e.type?i=Xn._GreasedLineMeshParser(e,t):e.type&&"TrailMesh"===e.type?i=Xn._TrailMeshParser(e,t):e.type&&"GaussianSplattingMesh"===e.type?(i=e._isCompound?Xn._GaussianSplattingCompoundMeshParser(e,t):Xn._GaussianSplattingMeshParser(e,t),r=!0):e.type&&"GaussianSplattingPartProxyMesh"===e.type?(i=Xn._GaussianSplattingPartProxyMeshParser(e,t),r=!0):i=new Xn(e.name,t),i.id=e.id,i._waitingParsedUniqueId=e.uniqueId,Ge&&Ge.AddTagsTo(i,e.tags),i.position=xe.FromArray(e.position),void 0!==e.metadata&&(i.metadata=e.metadata),e.rotationQuaternion?i.rotationQuaternion=ve.FromArray(e.rotationQuaternion):e.rotation&&(i.rotation=xe.FromArray(e.rotation)),i.scaling=xe.FromArray(e.scaling),e.localMatrix?i.setPreTransformMatrix(Ie.FromArray(e.localMatrix)):e.pivotMatrix&&i.setPivotMatrix(Ie.FromArray(e.pivotMatrix)),i.setEnabled(e.isEnabled),i.isVisible=e.isVisible,i.infiniteDistance=e.infiniteDistance,i.alwaysSelectAsActiveMesh=!!e.alwaysSelectAsActiveMesh,i.showBoundingBox=e.showBoundingBox,i.showSubMeshesBoundingBox=e.showSubMeshesBoundingBox,void 0!==e.applyFog&&(i.applyFog=e.applyFog),void 0!==e.pickable&&(i.isPickable=e.pickable),void 0!==e.alphaIndex&&(i.alphaIndex=e.alphaIndex),i.receiveShadows=e.receiveShadows,void 0!==e.billboardMode&&(i.billboardMode=e.billboardMode),void 0!==e.visibility&&(i.visibility=e.visibility),i.checkCollisions=e.checkCollisions,i.doNotSyncBoundingInfo=!!e.doNotSyncBoundingInfo,e.ellipsoid&&(i.ellipsoid=xe.FromArray(e.ellipsoid)),e.ellipsoidOffset&&(i.ellipsoidOffset=xe.FromArray(e.ellipsoidOffset)),null!=e.overrideMaterialSideOrientation&&(i.sideOrientation=e.overrideMaterialSideOrientation),void 0!==e.sideOrientation&&(i.sideOrientation=e.sideOrientation),void 0!==e.isBlocker&&(i.isBlocker=e.isBlocker),i._shouldGenerateFlatShading=e.useFlatShading,e.freezeWorldMatrix&&(i._waitingData.freezeWorldMatrix=e.freezeWorldMatrix),void 0!==e.parentId&&(i._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(i._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.actions&&(i._waitingData.actions=e.actions),void 0!==e.overlayAlpha&&(i.overlayAlpha=e.overlayAlpha),void 0!==e.overlayColor&&(i.overlayColor=Xe.FromArray(e.overlayColor)),void 0!==e.renderOverlay&&(i.renderOverlay=e.renderOverlay),i.isUnIndexed=!!e.isUnIndexed,i.hasVertexAlpha=e.hasVertexAlpha,e.delayLoadingFile?(i.delayLoadState=dt.DELAYLOADSTATE_NOTLOADED,i.delayLoadingFile=s+e.delayLoadingFile,i.buildBoundingInfo(xe.FromArray(e.boundingBoxMinimum),xe.FromArray(e.boundingBoxMaximum)),e._binaryInfo&&(i._binaryInfo=e._binaryInfo),i._delayInfo=[],e.hasUVs&&i._delayInfo.push(Gi.UVKind),e.hasUVs2&&i._delayInfo.push(Gi.UV2Kind),e.hasUVs3&&i._delayInfo.push(Gi.UV3Kind),e.hasUVs4&&i._delayInfo.push(Gi.UV4Kind),e.hasUVs5&&i._delayInfo.push(Gi.UV5Kind),e.hasUVs6&&i._delayInfo.push(Gi.UV6Kind),e.hasColors&&i._delayInfo.push(Gi.ColorKind),e.hasMatricesIndices&&i._delayInfo.push(Gi.MatricesIndicesKind),e.hasMatricesWeights&&i._delayInfo.push(Gi.MatricesWeightsKind),i._delayLoadingFunction=lr._ImportGeometry,hr.ForceFullSceneLoadingForIncremental&&i._checkDelayState()):r||lr._ImportGeometry(e,i),e.materialUniqueId?i._waitingMaterialId=e.materialUniqueId:e.materialId&&(i._waitingMaterialId=e.materialId),e.morphTargetManagerId>-1&&(i._waitingMorphTargetManagerId=e.morphTargetManagerId),void 0!==e.skeletonId&&null!==e.skeletonId&&(i.skeleton=t.getLastSkeletonById(e.skeletonId),i._waitingSkeletonId=e.skeletonId,e.numBoneInfluencers&&(i.numBoneInfluencers=e.numBoneInfluencers)),void 0!==e.skeletonUniqueId&&null!==e.skeletonUniqueId&&(i._waitingSkeletonUniqueId=e.skeletonUniqueId),e.animations){for(let t=0;t<e.animations.length;t++){const s=e.animations[t],r=Ae("BABYLON.Animation");r&&i.animations.push(r.Parse(s))}Qe.ParseAnimationRanges(i,e,t)}if(e.autoAnimate&&t.beginAnimation(i,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.layerMask&&!isNaN(e.layerMask)?i.layerMask=Math.abs(parseInt(e.layerMask)):i.layerMask=268435455,e.physicsImpostor&&(i.physicsImpostor=Xn._PhysicsImpostorParser(t,i,e)),e.lodMeshIds&&(i._waitingData.lods={ids:e.lodMeshIds,distances:e.lodDistances?e.lodDistances:null,coverages:e.lodCoverages?e.lodCoverages:null}),e.instances)for(let s=0;s<e.instances.length;s++){const r=e.instances[s],n=i.createInstance(r.name);if(r.id&&(n.id=r.id),Ge&&(r.tags?Ge.AddTagsTo(n,r.tags):Ge.AddTagsTo(n,e.tags)),n.position=xe.FromArray(r.position),void 0!==r.metadata&&(n.metadata=r.metadata),void 0!==r.parentId&&(n._waitingParentId=r.parentId),void 0!==r.parentInstanceIndex&&(n._waitingParentInstanceIndex=r.parentInstanceIndex),void 0!==r.isEnabled&&null!==r.isEnabled&&n.setEnabled(r.isEnabled),void 0!==r.isVisible&&null!==r.isVisible&&(n.isVisible=r.isVisible),void 0!==r.isPickable&&null!==r.isPickable&&(n.isPickable=r.isPickable),r.rotationQuaternion?n.rotationQuaternion=ve.FromArray(r.rotationQuaternion):r.rotation&&(n.rotation=xe.FromArray(r.rotation)),n.scaling=xe.FromArray(r.scaling),null!=r.checkCollisions&&null!=r.checkCollisions&&(n.checkCollisions=r.checkCollisions),null!=r.pickable&&null!=r.pickable&&(n.isPickable=r.pickable),null!=r.showBoundingBox&&null!=r.showBoundingBox&&(n.showBoundingBox=r.showBoundingBox),null!=r.showSubMeshesBoundingBox&&null!=r.showSubMeshesBoundingBox&&(n.showSubMeshesBoundingBox=r.showSubMeshesBoundingBox),null!=r.alphaIndex&&null!=r.showSubMeshesBoundingBox&&(n.alphaIndex=r.alphaIndex),r.physicsImpostor&&(n.physicsImpostor=Xn._PhysicsImpostorParser(t,n,r)),void 0!==r.actions&&(n._waitingData.actions=r.actions),r.animations){for(let e=0;e<r.animations.length;e++){const t=r.animations[e],s=Ae("BABYLON.Animation");s&&n.animations.push(s.Parse(t))}Qe.ParseAnimationRanges(n,r,t),r.autoAnimate&&t.beginAnimation(n,r.autoAnimateFrom,r.autoAnimateTo,r.autoAnimateLoop,r.autoAnimateSpeed||1)}}if(e.thinInstances){const t=e.thinInstances;if(i.thinInstanceEnablePicking=!!t.enablePicking,t.matrixData?(i.thinInstanceSetBuffer("matrix",new Float32Array(t.matrixData),16,!1),i._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,i._thinInstanceDataStorage.instancesCount=t.instancesCount):i._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,e.thinInstances.userThinInstance){const t=e.thinInstances.userThinInstance;for(const e in t.data)i.thinInstanceSetBuffer(e,new Float32Array(t.data[e]),t.strides[e],!1),i._userThinInstanceBuffersStorage.sizes[e]=t.sizes[e]}}return i}setPositionsForCPUSkinning(){const e=this._internalMeshDataInfo;if(!e._sourcePositions){const t=this.getVerticesData(Gi.PositionKind);if(!t)return e._sourcePositions;e._sourcePositions=new Float32Array(t),this.isVertexBufferUpdatable(Gi.PositionKind)||this.setVerticesData(Gi.PositionKind,t,!0)}return e._sourcePositions}setNormalsForCPUSkinning(){const e=this._internalMeshDataInfo;if(!e._sourceNormals){const t=this.getVerticesData(Gi.NormalKind);if(!t)return e._sourceNormals;e._sourceNormals=new Float32Array(t),this.isVertexBufferUpdatable(Gi.NormalKind)||this.setVerticesData(Gi.NormalKind,t,!0)}return e._sourceNormals}applySkeleton(e){if(!this.geometry)return this;if(this.geometry._softwareSkinningFrameId==this.getScene().getFrameId())return this;if(this.geometry._softwareSkinningFrameId=this.getScene().getFrameId(),!this.isVerticesDataPresent(Gi.PositionKind))return this;if(!this.isVerticesDataPresent(Gi.MatricesIndicesKind))return this;if(!this.isVerticesDataPresent(Gi.MatricesWeightsKind))return this;const t=this.isVerticesDataPresent(Gi.NormalKind),s=this._internalMeshDataInfo;if(!s._sourcePositions){const e=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=e}t&&!s._sourceNormals&&this.setNormalsForCPUSkinning();let i=this.getVerticesData(Gi.PositionKind);if(!i)return this;i instanceof Float32Array||(i=new Float32Array(i));let r=this.getVerticesData(Gi.NormalKind);if(t){if(!r)return this;r instanceof Float32Array||(r=new Float32Array(r))}const n=this.getVerticesData(Gi.MatricesIndicesKind),a=this.getVerticesData(Gi.MatricesWeightsKind);if(!a||!n)return this;const o=this.numBoneInfluencers>4,h=o?this.getVerticesData(Gi.MatricesIndicesExtraKind):null,l=o?this.getVerticesData(Gi.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),u=xe.Zero(),d=new Ie,_=new Ie;let p,f=0;for(let e=0;e<i.length;e+=3,f+=4){let g;for(p=0;p<4;p++)g=a[f+p],g>0&&(Ie.FromFloat32ArrayToRefScaled(c,Math.floor(16*n[f+p]),g,_),d.addToSelf(_));if(o)for(p=0;p<4;p++)g=l[f+p],g>0&&(Ie.FromFloat32ArrayToRefScaled(c,Math.floor(16*h[f+p]),g,_),d.addToSelf(_));xe.TransformCoordinatesFromFloatsToRef(s._sourcePositions[e],s._sourcePositions[e+1],s._sourcePositions[e+2],d,u),u.toArray(i,e),t&&(xe.TransformNormalFromFloatsToRef(s._sourceNormals[e],s._sourceNormals[e+1],s._sourceNormals[e+2],d,u),u.toArray(r,e)),d.reset()}return this.updateVerticesData(Gi.PositionKind,i),t&&this.updateVerticesData(Gi.NormalKind,r),this}static MinMax(e){let t=null,s=null;for(const i of e){const e=i.getBoundingInfo().boundingBox;t&&s?(t.minimizeInPlace(e.minimumWorld),s.maximizeInPlace(e.maximumWorld)):(t=e.minimumWorld.clone(),s=e.maximumWorld.clone())}return t&&s?{min:t,max:s}:{min:xe.Zero(),max:xe.Zero()}}static Center(e){const t=e instanceof Array?Xn.MinMax(e):e;return xe.Center(t.min,t.max)}static MergeMeshes(e,t=!0,s,i,r,n){return Hs(Xn._MergeMeshesCoroutine(e,t,s,i,r,n,!1))}static async MergeMeshesAsync(e,t=!0,s,i,r,n){return await zs(Xn._MergeMeshesCoroutine(e,t,s,i,r,n,!0),Gs())}static*_MergeMeshesCoroutine(e,t=!0,s,i,r,n,o){if(0===(e=e.filter(Boolean)).length)return null;let h;if(!s){let t=0;for(h=0;h<e.length;h++)if(t+=e[h].getTotalVertices(),t>=65536)return a.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}const l=e[0];n&&(r=!1,e.sort((e,t)=>(e.material?.uniqueId??-1)-(t.material?.uniqueId??-1)));const c=new Array,u=new Array,d=new Array,_=e[0].sideOrientation;for(h=0;h<e.length;h++){const t=e[h];if(t.isAnInstance)return a.Warn("Cannot merge instance meshes."),null;if(_!==t.sideOrientation)return a.Warn("Cannot merge meshes with different sideOrientation values."),null;if(r||n){const e=d.reduce((e,t)=>Math.max(e,t.start+t.count),0);if(n)if(t.material){const s=t.material;if(s instanceof On){for(let e=0;e<s.subMaterials.length;e++)c.indexOf(s.subMaterials[e])<0&&c.push(s.subMaterials[e]);for(let i=0;i<t.subMeshes.length;i++)u.push(c.indexOf(s.subMaterials[t.subMeshes[i].materialIndex])),d.push({start:e+t.subMeshes[i].indexStart,count:t.subMeshes[i].indexCount})}else{c.indexOf(s)<0&&c.push(s);for(let i=0;i<t.subMeshes.length;i++)u.push(c.indexOf(s)),d.push({start:e+t.subMeshes[i].indexStart,count:t.subMeshes[i].indexCount})}}else for(let s=0;s<t.subMeshes.length;s++)u.push(0),d.push({start:e+t.subMeshes[s].indexStart,count:t.subMeshes[s].indexCount});else d.push({start:e,count:t.getTotalIndices()})}}if(n&&d.length>1){let e=0;for(let t=1;t<d.length;t++){const s=d[e],i=d[t];u[t]===u[e]&&s.start+s.count===i.start?s.count+=i.count:(e++,d[e]=i,u[e]=u[t])}d.length=e+1,u.length=e+1}const p=e=>{const t=e.computeWorldMatrix(!0);return{vertexData:or.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:f,transform:g}=p(e[0]);o&&(yield);const m=new Array(e.length-1);for(let t=1;t<e.length;t++)m[t-1]=p(e[t]),o&&(yield);const T=f._mergeCoroutine(g,m,s,o,!t);let E=T.next();for(;!E.done;)o&&(yield),E=T.next();const R=E.value;i||(i=new Xn(l.name+"_merged",l.getScene()));const b=R._applyToCoroutine(i,void 0,o);let A=b.next();for(;!A.done;)o&&(yield),A=b.next();if(i.checkCollisions=l.checkCollisions,i.sideOrientation=l.sideOrientation,t)for(h=0;h<e.length;h++)e[h].dispose();if(r||n){for(i.releaseSubMeshes(),h=0;h<d.length;)nr.CreateFromIndices(0,d[h].start,d[h].count,i,void 0,!1),h++;for(const e of i.subMeshes)e.refreshBoundingInfo();i.computeWorldMatrix(!0)}if(n){const e=new On(l.name+"_merged",l.getScene());e.subMaterials=c;for(let e=0;e<i.subMeshes.length;e++)i.subMeshes[e].materialIndex=u[e];i.material=e}else i.material=l.material;return i}addInstance(e){e._indexInSourceMeshInstanceArray=this.instances.length,this.instances.push(e)}removeInstance(e){const t=e._indexInSourceMeshInstanceArray;if(-1!=t){if(t!==this.instances.length-1){const e=this.instances[this.instances.length-1];this.instances[t]=e,e._indexInSourceMeshInstanceArray=t}e._indexInSourceMeshInstanceArray=-1,this.instances.pop()}}_shouldConvertRHS(){return this._scene.useRightHandedSystem&&this.sideOrientation===Cn.CounterClockWiseSideOrientation}_getRenderingFillMode(e){const t=this.getScene();return t.forcePointsCloud?Cn.PointFillMode:t.forceWireframe?Cn.WireFrameFillMode:this.overrideRenderingFillMode??e}setMaterialByID(e){return this.setMaterialById(e)}static CreateRibbon(e,t,s,i,r,n,a,o,h){throw new Error("Import MeshBuilder to populate this function")}static CreateDisc(e,t,s,i,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateBox(e,t,s,i,r){throw new Error("Import MeshBuilder to populate this function")}static CreateSphere(e,t,s,i,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateHemisphere(e,t,s,i){throw new Error("Import MeshBuilder to populate this function")}static CreateCylinder(e,t,s,i,r,n,a,o,h){throw new Error("Import MeshBuilder to populate this function")}static CreateTorus(e,t,s,i,r,n,a){throw new Error("Import MeshBuilder to populate this function")}static CreateTorusKnot(e,t,s,i,r,n,a,o,h,l){throw new Error("Import MeshBuilder to populate this function")}static CreateLines(e,t,s,i,r){throw new Error("Import MeshBuilder to populate this function")}static CreateDashedLines(e,t,s,i,r,n,a,o){throw new Error("Import MeshBuilder to populate this function")}static CreatePolygon(e,t,s,i,r,n,a){throw new Error("Import MeshBuilder to populate this function")}static ExtrudePolygon(e,t,s,i,r,n,a,o){throw new Error("Import MeshBuilder to populate this function")}static ExtrudeShape(e,t,s,i,r,n,a,o,h,l){throw new Error("Import MeshBuilder to populate this function")}static ExtrudeShapeCustom(e,t,s,i,r,n,a,o,h,l,c,u){throw new Error("Import MeshBuilder to populate this function")}static CreateLathe(e,t,s,i,r,n,a){throw new Error("Import MeshBuilder to populate this function")}static CreatePlane(e,t,s,i,r){throw new Error("Import MeshBuilder to populate this function")}static CreateGround(e,t,s,i,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateTiledGround(e,t,s,i,r,n,a,o,h){throw new Error("Import MeshBuilder to populate this function")}static CreateGroundFromHeightMap(e,t,s,i,r,n,a,o,h,l,c){throw new Error("Import MeshBuilder to populate this function")}static CreateTube(e,t,s,i,r,n,a,o,h,l){throw new Error("Import MeshBuilder to populate this function")}static CreatePolyhedron(e,t,s){throw new Error("Import MeshBuilder to populate this function")}static CreateIcoSphere(e,t,s){throw new Error("Import MeshBuilder to populate this function")}static CreateDecal(e,t,s,i,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateCapsule(e,t,s){throw new Error("Import MeshBuilder to populate this function")}static ExtendToGoldberg(e){throw new Error("Import MeshBuilder to populate this function")}}Xn.FRONTSIDE=or.FRONTSIDE,Xn.BACKSIDE=or.BACKSIDE,Xn.DOUBLESIDE=or.DOUBLESIDE,Xn.DEFAULTSIDE=or.DEFAULTSIDE,Xn.NO_CAP=0,Xn.CAP_START=1,Xn.CAP_END=2,Xn.CAP_ALL=3,Xn.NO_FLIP=0,Xn.FLIP_TILE=1,Xn.ROTATE_TILE=2,Xn.FLIP_ROW=3,Xn.ROTATE_ROW=4,Xn.FLIP_N_ROTATE_TILE=5,Xn.FLIP_N_ROTATE_ROW=6,Xn.CENTER=0,Xn.LEFT=1,Xn.RIGHT=2,Xn.TOP=3,Xn.BOTTOM=4,Xn.INSTANCEDMESH_SORT_TRANSPARENT=!1,Xn._GroundMeshParser=(e,t)=>{throw Le("GroundMesh")},Xn._GoldbergMeshParser=(e,t)=>{throw Le("GoldbergMesh")},Xn._LinesMeshParser=(e,t)=>{throw Le("LinesMesh")},Xn._GreasedLineMeshParser=(e,t)=>{throw Le("GreasedLineMesh")},Xn._GreasedLineRibbonMeshParser=(e,t)=>{throw Le("GreasedLineRibbonMesh")},Xn._TrailMeshParser=(e,t)=>{throw Le("TrailMesh")},Xn._GaussianSplattingMeshParser=(e,t)=>{throw Le("GaussianSplattingMesh")},Xn._GaussianSplattingPartProxyMeshParser=(e,t)=>{throw Le("GaussianSplattingPartProxyMesh")},Xn._GaussianSplattingCompoundMeshParser=(e,t)=>{throw Le("GaussianSplattingCompoundMesh")};let Kn=!1;Xn.prototype.registerInstancedBuffer??=Ne("Mesh","registerInstancedBuffer"),Xn.prototype.simplify??=Ne("Mesh","simplify"),Xn.prototype.thinInstanceAdd??=Ne("Mesh","thinInstanceAdd"),Xn.prototype.thinInstanceAddSelf??=Ne("Mesh","thinInstanceAddSelf"),Xn.prototype.thinInstanceRegisterAttribute??=Ne("Mesh","thinInstanceRegisterAttribute"),Xn.prototype.thinInstanceSetMatrixAt??=Ne("Mesh","thinInstanceSetMatrixAt"),Xn.prototype.thinInstanceSetAttributeAt??=Ne("Mesh","thinInstanceSetAttributeAt"),Xn.prototype.thinInstanceSetBuffer??=Ne("Mesh","thinInstanceSetBuffer"),Xn.prototype.thinInstanceGetWorldMatrices??=Ne("Mesh","thinInstanceGetWorldMatrices"),Xn.prototype.thinInstanceBufferUpdated??=Ne("Mesh","thinInstanceBufferUpdated"),Xn.prototype.thinInstancePartialBufferUpdate??=Ne("Mesh","thinInstancePartialBufferUpdate"),Xn.prototype.thinInstanceRefreshBoundingInfo??=Ne("Mesh","thinInstanceRefreshBoundingInfo"),Xn.prototype.getEmittedParticleSystems??=Ne("Mesh","getEmittedParticleSystems"),Xn.prototype.getHierarchyEmittedParticleSystems??=Ne("Mesh","getHierarchyEmittedParticleSystems"),Object.getOwnPropertyDescriptor(Xn.prototype,"edgesShareWithInstances")||Object.defineProperty(Xn.prototype,"edgesShareWithInstances",Ue(0,"edgesShareWithInstances")),Object.getOwnPropertyDescriptor(Xn.prototype,"thinInstanceEnablePicking")||Object.defineProperty(Xn.prototype,"thinInstanceEnablePicking",Ue(0,"thinInstanceEnablePicking")),Object.getOwnPropertyDescriptor(Xn.prototype,"thinInstanceAllowAutomaticStaticBufferRecreation")||Object.defineProperty(Xn.prototype,"thinInstanceAllowAutomaticStaticBufferRecreation",Ue(0,"thinInstanceAllowAutomaticStaticBufferRecreation")),Object.getOwnPropertyDescriptor(Xn.prototype,"thinInstanceCount")||Object.defineProperty(Xn.prototype,"thinInstanceCount",Ue(0,"thinInstanceCount"));class Yn{}Yn.POINTERDOWN=1,Yn.POINTERUP=2,Yn.POINTERMOVE=4,Yn.POINTERWHEEL=8,Yn.POINTERPICK=16,Yn.POINTERTAP=32,Yn.POINTERDOUBLETAP=64;class jn{constructor(e,t){this.type=e,this.event=t}}class qn extends jn{constructor(e,t,s,i){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new Me(s,i)}}class $n extends jn{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,s,i=null){super(e,t),this._pickInfo=s,this._inputManager=i}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}class Zn{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._attachedCamera=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}get attachedNode(){return this._attachedCamera}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{e.type!==Yn.POINTERDOWN?e.type===Yn.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;const e=nt.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const s=e-this._lastInteractionTime-this._idleRotationWaitTime,i=Math.max(Math.min(s/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*i,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))})}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null,this._lastFrameTime=null}resetLastInteractionTime(e){this._lastInteractionTime=e??nt.Now}_reachTargetAlpha(){return!(!this._attachedCamera||null===this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha)<j}_userIsZooming(){return!!this._attachedCamera&&0!==this._attachedCamera.inertialRadiusOffset}_shouldAnimationStopForInteraction(){if(!this._attachedCamera)return!1;let e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&0!==this._attachedCamera.inertialRadiusOffset&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()}_applyUserInteraction(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=nt.Now)}_userIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}var Qn;!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(Qn||(Qn={}));class Jn{static Interpolate(e,t,s,i,r){if(0===e)return 0;const n=1-3*i+3*t,a=3*i-6*t,o=3*t;let h=e;for(let t=0;t<5;t++){const t=h*h;h-=(n*(t*h)+a*t+o*h-e)*(1/(3*n*t+2*a*h+o)),h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*s+3*(1-h)*Math.pow(h,2)*r+Math.pow(h,3)}}class ea{constructor(){this._easingMode=ea.EASINGMODE_EASEIN}setEasingMode(e){const t=Math.min(Math.max(e,0),2);this._easingMode=t}getEasingMode(){return this._easingMode}easeInCore(e){throw new Error("You must implement this method")}ease(e){switch(this._easingMode){case ea.EASINGMODE_EASEIN:return this.easeInCore(e);case ea.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-e)}return e>=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}ea.EASINGMODE_EASEIN=0,ea.EASINGMODE_EASEOUT=1,ea.EASINGMODE_EASEINOUT=2;class ta extends ea{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class sa extends ea{constructor(e=1){super(),this.amplitude=e}easeInCore(e){const t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}}class ia extends ea{constructor(e=3,t=2){super(),this.bounces=e,this.bounciness=t}easeInCore(e){const t=Math.max(0,this.bounces);let s=this.bounciness;s<=1&&(s=1.001);const i=Math.pow(s,t),r=1-s,n=(1-i)/r+.5*i,a=e*n,o=Math.log(-a*(1-s)+1)/Math.log(s),h=Math.floor(o),l=h+1,c=(1-Math.pow(s,h))/(r*n),u=.5*(c+(1-Math.pow(s,l))/(r*n)),d=e-u,_=u-c;return-Math.pow(1/s,t-h)/(_*_)*(d-_)*(d+_)}}class ra extends ea{easeInCore(e){return e*e*e}}class na extends ea{constructor(e=3,t=3){super(),this.oscillations=e,this.springiness=t}easeInCore(e){let t;const s=Math.max(0,this.oscillations),i=Math.max(0,this.springiness);return t=0===i?e:(Math.exp(i*e)-1)/(Math.exp(i)-1),t*Math.sin((6.283185307179586*s+1.5707963267948966)*e)}}class aa extends ea{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}}class oa extends ea{constructor(e=0,t=0,s=1,i=1){super(),this.x1=e,this.y1=t,this.x2=s,this.y2=i}easeInCore(e){return Jn.Interpolate(e,this.x1,this.y1,this.x2,this.y2)}}class ha{constructor(e,t,s){this.name=e,this.from=t,this.to=s}clone(){return new ha(this.name,this.from,this.to)}}class la{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=0|this.width;return e=397*e^this.height,e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new la(this.width*e,this.height*t)}clone(){return new la(this.width,this.height)}equals(e){return!!e&&(this.width===e.width&&this.height===e.height)}get surface(){return this.width*this.height}static Zero(){return new la(0,0)}add(e){return new la(this.width+e.width,this.height+e.height)}subtract(e){return new la(this.width-e.width,this.height-e.height)}scale(e){return new la(this.width*e,this.height*e)}static Lerp(e,t,s){const i=e.width+(t.width-e.width)*s,r=e.height+(t.height-e.height)*s;return new la(i,r)}}const ca=Object.freeze(new ve(0,0,0,0)),ua=Object.freeze(xe.Zero()),da=Object.freeze(Me.Zero()),_a=Object.freeze(la.Zero()),pa=Object.freeze(Xe.Black()),fa=Object.freeze(new Ke(0,0,0,0)),ga={key:0,repeatCount:0,loopMode:2};class ma{static _PrepareAnimation(e,t,s,i,r,n,a,o){let h;if(!isNaN(parseFloat(r))&&isFinite(r)?h=ma.ANIMATIONTYPE_FLOAT:r instanceof ve?h=ma.ANIMATIONTYPE_QUATERNION:r instanceof xe?h=ma.ANIMATIONTYPE_VECTOR3:r instanceof Me?h=ma.ANIMATIONTYPE_VECTOR2:r instanceof Xe?h=ma.ANIMATIONTYPE_COLOR3:r instanceof Ke?h=ma.ANIMATIONTYPE_COLOR4:r instanceof la&&(h=ma.ANIMATIONTYPE_SIZE),null==h)return null;const l=new ma(e,t,s,h,a),c=[{frame:0,value:r},{frame:i,value:n}];return l.setKeys(c),void 0!==o&&l.setEasingFunction(o),l}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,s,i,r,n){this.name=e,this.targetProperty=t,this.framePerSecond=s,this.dataType=i,this.loopMode=r,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this._coreAnimation=null,this.targetPropertyPath=t.split("."),this.dataType=i,this.loopMode=void 0===r?ma.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=ma._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(const s in this._ranges)e||(t+=", "),e=!1,t+=s;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort((e,t)=>e.frame-t.frame)}removeEvents(e){for(let t=0;t<this._events.length;t++)this._events[t].frame===e&&(this._events.splice(t,1),t--)}getEvents(){return this._events}createRange(e,t,s){this._ranges[e]||(this._ranges[e]=new ha(e,t,s))}deleteRange(e,t=!0){const s=this._ranges[e];if(s){if(t){const e=s.from,t=s.to;for(let s=this._keys.length-1;s>=0;s--)this._keys[s].frame>=e&&this._keys[s].frame<=t&&this._keys.splice(s,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,s=this._keys.length;t<s;t++)e<this._keys[t].frame&&(e=this._keys[t].frame);return e}getEasingFunction(){return this._easingFunction}setEasingFunction(e){this._easingFunction=e}floatInterpolateFunction(e,t,s){return ie(e,t,s)}floatInterpolateFunctionWithTangents(e,t,s,i,r){return re(e,t,s,i,r)}quaternionInterpolateFunction(e,t,s){return ve.Slerp(e,t,s)}quaternionInterpolateFunctionWithTangents(e,t,s,i,r){return ve.Hermite(e,t,s,i,r).normalize()}vector3InterpolateFunction(e,t,s){return xe.Lerp(e,t,s)}vector3InterpolateFunctionWithTangents(e,t,s,i,r){return xe.Hermite(e,t,s,i,r)}vector2InterpolateFunction(e,t,s){return Me.Lerp(e,t,s)}vector2InterpolateFunctionWithTangents(e,t,s,i,r){return Me.Hermite(e,t,s,i,r)}sizeInterpolateFunction(e,t,s){return la.Lerp(e,t,s)}color3InterpolateFunction(e,t,s){return Xe.Lerp(e,t,s)}color3InterpolateFunctionWithTangents(e,t,s,i,r){return Xe.Hermite(e,t,s,i,r)}color4InterpolateFunction(e,t,s){return Ke.Lerp(e,t,s)}color4InterpolateFunctionWithTangents(e,t,s,i,r){return Ke.Hermite(e,t,s,i,r)}_getKeyValue(e){return"function"==typeof e?e():e}evaluate(e){return ga.key=0,this._interpolate(e,ga)}_interpolate(e,t,s=!1){if(t.loopMode===ma.ANIMATIONLOOPMODE_CONSTANT&&t.repeatCount>0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const i=this._keys;let r;if(this._coreAnimation)r=this._coreAnimation._key;else{const n=i.length;for(r=t.key;r>=0&&e<i[r].frame;)--r;for(;r+1<=n-1&&e>=i[r+1].frame;)++r;if(t.key=r,r<0)return s?void 0:this._getKeyValue(i[0].value);if(r+1>n-1)return s?void 0:this._getKeyValue(i[n-1].value);this._key=r}const n=i[r],a=i[r+1];if(s&&(e===n.frame||e===a.frame))return;const o=this._getKeyValue(n.value),h=this._getKeyValue(a.value);if(1===n.interpolation)return a.frame>e?o:h;const l=void 0!==n.outTangent&&void 0!==a.inTangent,c=a.frame-n.frame;let u=(e-n.frame)/c;const d=n.easingFunction||this.getEasingFunction();switch(d&&(u=d.ease(u)),this.dataType){case ma.ANIMATIONTYPE_FLOAT:{const e=l?this.floatInterpolateFunctionWithTangents(o,n.outTangent*c,h,a.inTangent*c,u):this.floatInterpolateFunction(o,h,u);switch(t.loopMode){case ma.ANIMATIONLOOPMODE_CYCLE:case ma.ANIMATIONLOOPMODE_CONSTANT:case ma.ANIMATIONLOOPMODE_YOYO:return e;case ma.ANIMATIONLOOPMODE_RELATIVE:case ma.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+e}break}case ma.ANIMATIONTYPE_QUATERNION:{const e=l?this.quaternionInterpolateFunctionWithTangents(o,n.outTangent.scale(c),h,a.inTangent.scale(c),u):this.quaternionInterpolateFunction(o,h,u);switch(t.loopMode){case ma.ANIMATIONLOOPMODE_CYCLE:case ma.ANIMATIONLOOPMODE_CONSTANT:case ma.ANIMATIONLOOPMODE_YOYO:return e;case ma.ANIMATIONLOOPMODE_RELATIVE:case ma.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||ca).scale(t.repeatCount))}return e}case ma.ANIMATIONTYPE_VECTOR3:{const e=l?this.vector3InterpolateFunctionWithTangents(o,n.outTangent.scale(c),h,a.inTangent.scale(c),u):this.vector3InterpolateFunction(o,h,u);switch(t.loopMode){case ma.ANIMATIONLOOPMODE_CYCLE:case ma.ANIMATIONLOOPMODE_CONSTANT:case ma.ANIMATIONLOOPMODE_YOYO:return e;case ma.ANIMATIONLOOPMODE_RELATIVE:case ma.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||ua).scale(t.repeatCount))}break}case ma.ANIMATIONTYPE_VECTOR2:{const e=l?this.vector2InterpolateFunctionWithTangents(o,n.outTangent.scale(c),h,a.inTangent.scale(c),u):this.vector2InterpolateFunction(o,h,u);switch(t.loopMode){case ma.ANIMATIONLOOPMODE_CYCLE:case ma.ANIMATIONLOOPMODE_CONSTANT:case ma.ANIMATIONLOOPMODE_YOYO:return e;case ma.ANIMATIONLOOPMODE_RELATIVE:case ma.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||da).scale(t.repeatCount))}break}case ma.ANIMATIONTYPE_SIZE:switch(t.loopMode){case ma.ANIMATIONLOOPMODE_CYCLE:case ma.ANIMATIONLOOPMODE_CONSTANT:case ma.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(o,h,u);case ma.ANIMATIONLOOPMODE_RELATIVE:case ma.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(o,h,u).add((t.offsetValue||_a).scale(t.repeatCount))}break;case ma.ANIMATIONTYPE_COLOR3:{const e=l?this.color3InterpolateFunctionWithTangents(o,n.outTangent.scale(c),h,a.inTangent.scale(c),u):this.color3InterpolateFunction(o,h,u);switch(t.loopMode){case ma.ANIMATIONLOOPMODE_CYCLE:case ma.ANIMATIONLOOPMODE_CONSTANT:case ma.ANIMATIONLOOPMODE_YOYO:return e;case ma.ANIMATIONLOOPMODE_RELATIVE:case ma.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||pa).scale(t.repeatCount))}break}case ma.ANIMATIONTYPE_COLOR4:{const e=l?this.color4InterpolateFunctionWithTangents(o,n.outTangent.scale(c),h,a.inTangent.scale(c),u):this.color4InterpolateFunction(o,h,u);switch(t.loopMode){case ma.ANIMATIONLOOPMODE_CYCLE:case ma.ANIMATIONLOOPMODE_CONSTANT:case ma.ANIMATIONLOOPMODE_YOYO:return e;case ma.ANIMATIONLOOPMODE_RELATIVE:case ma.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||fa).scale(t.repeatCount))}break}case ma.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case ma.ANIMATIONLOOPMODE_CYCLE:case ma.ANIMATIONLOOPMODE_CONSTANT:case ma.ANIMATIONLOOPMODE_YOYO:return ma.AllowMatricesInterpolation?this.matrixInterpolateFunction(o,h,u,t.workValue):o;case ma.ANIMATIONLOOPMODE_RELATIVE:case ma.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return o}}return 0}matrixInterpolateFunction(e,t,s,i){return ma.AllowMatrixDecomposeForInterpolation?i?(Ie.DecomposeLerpToRef(e,t,s,i),i):Ie.DecomposeLerp(e,t,s):i?(Ie.LerpToRef(e,t,s,i),i):Ie.Lerp(e,t,s)}clone(e=!1){const t=new ma(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(t.enableBlending=this.enableBlending,t.blendingSpeed=this.blendingSpeed,this._keys&&t.setKeys(this._keys,!1,e),this._ranges){t._ranges={};for(const e in this._ranges){const s=this._ranges[e];s&&(t._ranges[e]=s.clone())}}return t}setKeys(e,t=!1,s=!1){if(t)this._keys=e;else if(this._keys=e.slice(0),s)for(let e=0;e<this._keys.length;e++){const t=this._keys[e];this._keys[e]={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent&&t.inTangent.clone?t.inTangent.clone():t.inTangent,outTangent:t.outTangent&&t.outTangent.clone?t.outTangent.clone():t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent,easingFunction:t.easingFunction}}}createKeyForFrame(e){ga.key=0;const t=this._interpolate(e,ga,!0);if(!t)return this._keys[ga.key].frame===e?ga.key:ga.key+1;const s={frame:e,value:t.clone?t.clone():t};return this._keys.splice(ga.key+1,0,s),ga.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const s=this.getKeys();for(let i=0;i<s.length;i++){const r=s[i],n={};switch(n.frame=r.frame,t){case ma.ANIMATIONTYPE_FLOAT:n.values=[r.value],void 0!==r.inTangent&&n.values.push(r.inTangent),void 0!==r.outTangent&&(void 0===r.inTangent&&n.values.push(void 0),n.values.push(r.outTangent)),void 0!==r.interpolation&&(void 0===r.inTangent&&n.values.push(void 0),void 0===r.outTangent&&n.values.push(void 0),n.values.push(r.interpolation));break;case ma.ANIMATIONTYPE_QUATERNION:case ma.ANIMATIONTYPE_MATRIX:case ma.ANIMATIONTYPE_VECTOR3:case ma.ANIMATIONTYPE_COLOR3:case ma.ANIMATIONTYPE_COLOR4:n.values=r.value.asArray(),null!=r.inTangent&&n.values.push(r.inTangent.asArray()),null!=r.outTangent&&(void 0===r.inTangent&&n.values.push(void 0),n.values.push(r.outTangent.asArray())),void 0!==r.interpolation&&(void 0===r.inTangent&&n.values.push(void 0),void 0===r.outTangent&&n.values.push(void 0),n.values.push(r.interpolation))}e.keys.push(n)}e.ranges=[];for(const t in this._ranges){const s=this._ranges[t];if(!s)continue;const i={};i.name=t,i.from=s.from,i.to=s.to,e.ranges.push(i)}return e}static _UniversalLerp(e,t,s){const i=e.constructor;return i.Lerp?i.Lerp(e,t,s):i.Slerp?i.Slerp(e,t,s):e.toFixed?e*(1-s)+s*t:t}}function Ta(e,t,s,i=!1,r){let n;n="object"==typeof t?t:{referenceFrame:t??0,range:s,cloneOriginalAnimation:i,clonedAnimationName:r};let a=e;n.cloneOriginalAnimation&&(a=e.clone(),a.name=n.clonedAnimationName||a.name);const o=a.getKeys();if(!o.length)return a;const h=n.referenceFrame&&n.referenceFrame>=0?n.referenceFrame:0;let l=0;const c=o[0];let u=o.length-1;const d=o[u],_={referenceValue:c.value,referencePosition:Ce.Vector3[0],referenceQuaternion:Ce.Quaternion[0],referenceScaling:Ce.Vector3[1],keyPosition:Ce.Vector3[2],keyQuaternion:Ce.Quaternion[1],keyScaling:Ce.Vector3[3]};let p=c.frame,f=d.frame;if(n.range){const e=a.getRange(n.range);e&&(p=e.from,f=e.to)}else p=n.fromFrame??p,f=n.toFrame??f;p!==c.frame&&(l=a.createKeyForFrame(p)),f!==d.frame&&(u=a.createKeyForFrame(f));const g=a.getKeys();if(1===g.length){const e=a._getKeyValue(g[0].value);_.referenceValue=e.clone?e.clone():e}else if(h<=c.frame){const e=a._getKeyValue(c.value);_.referenceValue=e.clone?e.clone():e}else if(h>=d.frame){const e=a._getKeyValue(d.value);_.referenceValue=e.clone?e.clone():e}else{ga.key=0;const e=a._interpolate(h,ga);_.referenceValue=e.clone?e.clone():e}a.dataType===ma.ANIMATIONTYPE_QUATERNION?_.referenceValue.normalize().conjugateInPlace():a.dataType===ma.ANIMATIONTYPE_MATRIX&&(_.referenceValue.decompose(_.referenceScaling,_.referenceQuaternion,_.referencePosition),_.referenceQuaternion.normalize().conjugateInPlace());let m=Number.MAX_VALUE;const T=n.clipKeys?[]:null;for(let e=l;e<=u;e++){let t=g[e];if((T||n.cloneOriginalAnimation)&&(t={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent,outTangent:t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent,easingFunction:t.easingFunction},T&&(m===Number.MAX_VALUE&&(m=t.frame),t.frame-=m,T.push(t))),!e||a.dataType===ma.ANIMATIONTYPE_FLOAT||t.value!==c.value)switch(a.dataType){case ma.ANIMATIONTYPE_MATRIX:t.value.decompose(_.keyScaling,_.keyQuaternion,_.keyPosition),_.keyPosition.subtractInPlace(_.referencePosition),_.keyScaling.divideInPlace(_.referenceScaling),_.referenceQuaternion.multiplyToRef(_.keyQuaternion,_.keyQuaternion),Ie.ComposeToRef(_.keyScaling,_.keyQuaternion,_.keyPosition,t.value);break;case ma.ANIMATIONTYPE_QUATERNION:_.referenceValue.multiplyToRef(t.value,t.value);break;case ma.ANIMATIONTYPE_VECTOR2:case ma.ANIMATIONTYPE_VECTOR3:case ma.ANIMATIONTYPE_COLOR3:case ma.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(_.referenceValue,t.value);break;case ma.ANIMATIONTYPE_SIZE:t.value.width-=_.referenceValue.width,t.value.height-=_.referenceValue.height;break;default:t.value-=_.referenceValue}}return T&&a.setKeys(T,!0),a}function Ea(e,t,s,i){const r=new ma(e+"Animation",e,s,t,ma.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(i),r}function Ra(e,t,s,i,r,n,a,o,h,l,c){const u=ma._PrepareAnimation(e,s,i,r,n,a,o,h);return u?(t.getScene&&(c=t.getScene()),c?c.beginDirectAnimation(t,[u],0,r,u.loopMode!==ma.ANIMATIONLOOPMODE_CONSTANT,1,l):null):null}function ba(e,t,s,i,r,n,a,o,h,l,c){const u=ma._PrepareAnimation(e,i,r,n,a,o,h,l);if(!u)return null;return t.getScene().beginDirectHierarchyAnimation(t,s,[u],0,n,1===u.loopMode,1,c)}function Aa(e,t,s,i,r,n,a,o,h,l){const c=ma._PrepareAnimation(e,s,i,r,n,a,o,h);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,r,1===c.loopMode,1,l)):null}function ya(e,t,s,i,r,n,a,o=null,h=!0,l){if(a<=0)return s[e]=t,o&&o(),null;const c=r*(a/1e3);n.setKeys(l??[{frame:0,value:s[e].clone?s[e].clone():s[e]},{frame:c,value:t}]),s.animations||(s.animations=[]),s.animations.push(n);return i.beginAnimation(s,0,c,!1,1,o??void 0,void 0,h)}function Ma(e,t){$e.AppendSerializedAnimations(e,t)}function xa(e){const t=new ma(e.name,e.property,e.framePerSecond,e.dataType,e.loopBehavior),s=e.dataType,i=[];let r,n;for(e.enableBlending&&(t.enableBlending=e.enableBlending),e.blendingSpeed&&(t.blendingSpeed=e.blendingSpeed),n=0;n<e.keys.length;n++){const t=e.keys[n];let a,o,h;switch(s){case ma.ANIMATIONTYPE_FLOAT:r=t.values[0],t.values.length>=2&&(a=t.values[1]),t.values.length>=3&&(o=t.values[2]),t.values.length>=4&&(h=t.values[3]);break;case ma.ANIMATIONTYPE_QUATERNION:if(r=ve.FromArray(t.values),t.values.length>=8){const e=ve.FromArray(t.values.slice(4,8));e.equals(ve.Zero())||(a=e)}if(t.values.length>=12){const e=ve.FromArray(t.values.slice(8,12));e.equals(ve.Zero())||(o=e)}t.values.length>=13&&(h=t.values[12]);break;case ma.ANIMATIONTYPE_MATRIX:r=Ie.FromArray(t.values),t.values.length>=17&&(h=t.values[16]);break;case ma.ANIMATIONTYPE_COLOR3:r=Xe.FromArray(t.values),t.values[3]&&(a=Xe.FromArray(t.values[3])),t.values[4]&&(o=Xe.FromArray(t.values[4])),t.values[5]&&(h=t.values[5]);break;case ma.ANIMATIONTYPE_COLOR4:r=Ke.FromArray(t.values),t.values[4]&&(a=Ke.FromArray(t.values[4])),t.values[5]&&(o=Ke.FromArray(t.values[5])),t.values[6]&&(h=t.values[6]);break;case ma.ANIMATIONTYPE_VECTOR3:default:r=xe.FromArray(t.values),t.values[3]&&(a=xe.FromArray(t.values[3])),t.values[4]&&(o=xe.FromArray(t.values[4])),t.values[5]&&(h=t.values[5])}const l={};l.frame=t.frame,l.value=r,null!=a&&(l.inTangent=a),null!=o&&(l.outTangent=o),null!=h&&(l.interpolation=h),i.push(l)}if(t.setKeys(i),e.ranges)for(n=0;n<e.ranges.length;n++)r=e.ranges[n],t.createRange(r.name,r.from,r.to);return t}async function Sa(e,t){return await new Promise((s,i)=>{const r=new at;r.addEventListener("readystatechange",()=>{if(4==r.readyState)if(200==r.status){let t=JSON.parse(r.responseText);if(t.animations&&(t=t.animations),t.length){const e=[];for(const s of t)e.push(xa(s));s(e)}else{const i=xa(t);e&&(i.name=e),s(i)}}else i("Unable to load the animation")}),r.open("GET",t),r.send()})}async function va(e){const t=this?.SnippetUrl??ma.SnippetUrl;return await new Promise((s,i)=>{const r=new at;r.addEventListener("readystatechange",()=>{if(4==r.readyState)if(200==r.status){const t=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(t.animations){const i=JSON.parse(t.animations),r=[];for(const t of i.animations){const s=xa(t);s.snippetId=e,r.push(s)}s(r)}else{const i=xa(JSON.parse(t.animation));i.snippetId=e,s(i)}}else i("Unable to load the snippet "+e)}),r.open("GET",t+"/"+e.replace(/#/g,"/")),r.send()})}ma._UniqueIdGenerator=0,ma.AllowMatricesInterpolation=!1,ma.AllowMatrixDecomposeForInterpolation=!0,ma.InheritOriginalValueFromActiveAnimations=!1,ma.SnippetUrl=dt.SnippetUrl,ma.ANIMATIONTYPE_FLOAT=dt.ANIMATIONTYPE_FLOAT,ma.ANIMATIONTYPE_VECTOR3=dt.ANIMATIONTYPE_VECTOR3,ma.ANIMATIONTYPE_QUATERNION=dt.ANIMATIONTYPE_QUATERNION,ma.ANIMATIONTYPE_MATRIX=dt.ANIMATIONTYPE_MATRIX,ma.ANIMATIONTYPE_COLOR3=dt.ANIMATIONTYPE_COLOR3,ma.ANIMATIONTYPE_COLOR4=dt.ANIMATIONTYPE_COLOR4,ma.ANIMATIONTYPE_VECTOR2=dt.ANIMATIONTYPE_VECTOR2,ma.ANIMATIONTYPE_SIZE=dt.ANIMATIONTYPE_SIZE,ma.ANIMATIONLOOPMODE_RELATIVE=0,ma.ANIMATIONLOOPMODE_CYCLE=1,ma.ANIMATIONLOOPMODE_CONSTANT=2,ma.ANIMATIONLOOPMODE_YOYO=4,ma.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5;const Ia=va;let Pa=!1;function Ca(){Pa||(Pa=!0,ma.Parse=xa,ma.ParseFromFileAsync=Sa,ma.ParseFromSnippetAsync=va,ma.CreateFromSnippetAsync=Ia,ma.CreateAnimation=Ea,ma.CreateAndStartAnimation=Ra,ma.CreateAndStartHierarchyAnimation=ba,ma.CreateMergeAndStartAnimation=Aa,ma.MakeAnimationAdditive=Ta,ma.TransitionTo=ya,ma.AppendSerializedAnimations=Ma,be("BABYLON.Animation",ma),Qe._AnimationRangeFactory=(e,t,s)=>new ha(e,t,s))}class Oa{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._attachedCamera=null,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;const t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add(e=>{if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){const t=e.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=.05*t,this.upperRadiusTransitionRange=.05*t}}):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}get attachedNode(){return this._attachedCamera}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))})}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return!!this._attachedCamera&&(this._attachedCamera.radius===e&&!this._radiusIsAnimating)}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(Oa.EasingFunction.setEasingMode(Oa.EasingMode),this._radiusBounceTransition=ma.CreateAnimation("radius",ma.ANIMATIONTYPE_FLOAT,60,Oa.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=ma.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,()=>this._clearAnimationLocks());t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}}Oa.EasingFunction=new sa(.3),Oa.EasingMode=ea.EASINGMODE_EASEOUT;class Da{constructor(){this.onTargetFramingAnimationEndObservable=new c,this._mode=Da.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._attachedCamera=null,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}get attachedNode(){return this._attachedCamera}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();Da.EasingFunction.setEasingMode(Da.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{e.type!==Yn.POINTERDOWN?e.type===Yn.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0}),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add(e=>{e&&e.getBoundingInfo&&this.zoomOnMesh(e,void 0,()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()})}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()})}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,s=null){e.computeWorldMatrix(!0);const i=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(i.minimumWorld,i.maximumWorld,t,s)}zoomOnMeshHierarchy(e,t=!1,s=null){e.computeWorldMatrix(!0);const i=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(i.min,i.max,t,s)}zoomOnMeshesHierarchy(e,t=!1,s=null){const i=new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new xe(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t<e.length;t++){const s=e[t].getHierarchyBoundingVectors(!0);xe.CheckExtends(s.min,i,r),xe.CheckExtends(s.max,i,r)}this.zoomOnBoundingInfo(i,r,t,s)}zoomOnBoundingInfo(e,t,s=!1,i=null){let r;if(!this._attachedCamera)return!1;const n=e.y,a=n+(t.y-n)*this._positionScale,o=t.subtract(e).scale(.5);if(!isFinite(a))return!1;if(s)r=new xe(0,a,0);else{const t=e.add(o);r=new xe(t.x,a,t.z)}this._vectorTransition||(this._vectorTransition=ma.CreateAnimation("target",ma.ANIMATIONTYPE_VECTOR3,60,Da.EasingFunction)),this._betaIsAnimating=!0;let h=ma.TransitionTo("target",r,this._attachedCamera,this._attachedCamera.getScene(),60,this._vectorTransition,this._framingTime);h&&this._animatables.push(h);let l=0;if(this._mode===Da.FitFrustumSidesMode){const s=this._calculateLowerRadiusFromModelBoundingSphere(e,t);this.autoCorrectCameraLimitsAndSensibility&&(this._attachedCamera.lowerRadiusLimit=o.length()+this._attachedCamera.minZ),l=s}else this._mode===Da.IgnoreBoundsSizeMode&&(l=this._calculateLowerRadiusFromModelBoundingSphere(e,t),this.autoCorrectCameraLimitsAndSensibility&&null===this._attachedCamera.lowerRadiusLimit&&(this._attachedCamera.lowerRadiusLimit=this._attachedCamera.minZ));if(this.autoCorrectCameraLimitsAndSensibility){const s=t.subtract(e).length();this._attachedCamera.panningSensibility=5e3/s,this._attachedCamera.wheelPrecision=100/l}return this._radiusTransition||(this._radiusTransition=ma.CreateAnimation("radius",ma.ANIMATIONTYPE_FLOAT,60,Da.EasingFunction)),h=ma.TransitionTo("radius",l,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusTransition,this._framingTime,()=>{this.stopAllAnimations(),i&&i(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}),h&&this._animatables.push(h),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const s=this._attachedCamera;if(!s)return 0;let i=s._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return s.lowerRadiusLimit&&this._mode===Da.IgnoreBoundsSizeMode&&(i=i<s.lowerRadiusLimit?s.lowerRadiusLimit:i),s.upperRadiusLimit&&(i=i>s.upperRadiusLimit?s.upperRadiusLimit:i),i}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=nt.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,s=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>s&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=ma.CreateAnimation("beta",ma.ANIMATIONTYPE_FLOAT,60,Da.EasingFunction));const e=ma.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});e&&this._animatables.push(e)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=nt.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}Da.EasingFunction=new aa,Da.EasingMode=ea.EASINGMODE_EASEINOUT,Da.IgnoreBoundsSizeMode=0,Da.FitFrustumSidesMode=1;class wa{constructor(e,t,s){this._cameraPosition=t,this._behavior=s,this.activeInput=!1,this.speed=1,this.zoomSpeed=1,this.panSpeed=1,this.rotationXSpeed=1,this.rotationYSpeed=1,this._zoomSpeedMultiplier=1,this._panSpeedMultiplier=1,this.zoomInertia=.9,this.panInertia=.9,this.rotationInertia=.9,this.zoomAccumulatedPixels=0,this.panAccumulatedPixels=new xe,this.rotationAccumulatedPixels=new xe,this.zoomDeltaCurrentFrame=0,this.panDeltaCurrentFrame=xe.Zero(),this.rotationDeltaCurrentFrame=xe.Zero(),this._zoomVelocity=0,this._panVelocity=new xe,this.referenceFrameRate=60,this._rotationVelocity=new xe,this._prevFrameTimeMs=0,this._scene=e}computeCurrentFrameDeltas(){const e=this._scene.getEngine().getDeltaTime(),t=this._getEffectiveDeltaMs(e);if(0===this._zoomVelocity&&0===this.zoomAccumulatedPixels&&0===this._panVelocity.x&&0===this._panVelocity.y&&0===this._panVelocity.z&&0===this.panAccumulatedPixels.x&&0===this.panAccumulatedPixels.y&&0===this.panAccumulatedPixels.z&&0===this._rotationVelocity.x&&0===this._rotationVelocity.y&&0===this._rotationVelocity.z&&0===this.rotationAccumulatedPixels.x&&0===this.rotationAccumulatedPixels.y&&0===this.rotationAccumulatedPixels.z&&!this.activeInput)return this.panDeltaCurrentFrame.setAll(0),this.rotationDeltaCurrentFrame.setAll(0),this.zoomDeltaCurrentFrame=0,void(e>0&&(this._prevFrameTimeMs=e));this.panDeltaCurrentFrame.setAll(0),this.rotationDeltaCurrentFrame.setAll(0),this.zoomDeltaCurrentFrame=0;(this.panAccumulatedPixels.lengthSquared()>0||this.rotationAccumulatedPixels.lengthSquared()>0||0!==this.zoomAccumulatedPixels)&&this._behavior?.isInterpolating&&this._behavior.stopAllAnimations(),this._panVelocity.copyFromFloats(this._calculateCurrentVelocity(this._panVelocity.x,this.panAccumulatedPixels.x,this.panInertia),this._calculateCurrentVelocity(this._panVelocity.y,this.panAccumulatedPixels.y,this.panInertia),this._calculateCurrentVelocity(this._panVelocity.z,this.panAccumulatedPixels.z,this.panInertia)),this._panVelocity.scaleToRef(this.speed*this.panSpeed*this._panSpeedMultiplier*t,this.panDeltaCurrentFrame),this._rotationVelocity.copyFromFloats(this._calculateCurrentVelocity(this._rotationVelocity.x,this.rotationAccumulatedPixels.x,this.rotationInertia),this._calculateCurrentVelocity(this._rotationVelocity.y,this.rotationAccumulatedPixels.y,this.rotationInertia),this._calculateCurrentVelocity(this._rotationVelocity.z,this.rotationAccumulatedPixels.z,this.rotationInertia)),this.rotationDeltaCurrentFrame.copyFromFloats(this._rotationVelocity.x*this.speed*this.rotationXSpeed*t,this._rotationVelocity.y*this.speed*this.rotationYSpeed*t,0),this._zoomVelocity=this._calculateCurrentVelocity(this._zoomVelocity,this.zoomAccumulatedPixels,this.zoomInertia),this.zoomDeltaCurrentFrame=this._zoomVelocity*(this.speed*this.zoomSpeed*this._zoomSpeedMultiplier)*t,e>0&&(this._prevFrameTimeMs=e),this.zoomAccumulatedPixels=0,this.panAccumulatedPixels.setAll(0),this.rotationAccumulatedPixels.setAll(0),this.activeInput=!1}resetRotationVelocity(){this._rotationVelocity.setAll(0),this.rotationAccumulatedPixels.setAll(0)}resetPanVelocity(){this._panVelocity.setAll(0),this.panAccumulatedPixels.setAll(0)}resetZoomVelocity(){this._zoomVelocity=0,this.zoomAccumulatedPixels=0}get isInterpolating(){return!!this._behavior?.isInterpolating}getFrameIndependentDecay(e){const t=this._scene.getEngine().getDeltaTime(),s=this._getEffectiveDeltaMs(t),i=1e3/this.referenceFrameRate;return Math.pow(e,s/i)}getFrameIndependentInputScale(e){const t=1-e;if(t<=0)return 1;return(1-this.getFrameIndependentDecay(e))/t}_getEffectiveDeltaMs(e){return e>0?e:this._prevFrameTimeMs>0?this._prevFrameTimeMs:1e3/this.referenceFrameRate}_calculateCurrentVelocity(e,t,s){let i=e;const r=this._scene.getEngine().getDeltaTime(),n=this._getEffectiveDeltaMs(r);if(0===n)return i;const a=this.getFrameIndependentDecay(s);if(i*=a,0!==t||this.activeInput){const e=1-s;i+=t/n*(e>0?(1-a)/e:1)}else Math.abs(i)<1e-6&&(i=0);return i}}class La{constructor(e,t){this.inputMap=[],this.handlers=e,this._createDefaultEntries=t,this.resetInputMap()}resolveInteraction(e,t){for(const s of this.inputMap)if(s.source===e&&this._entryMatches(s,t))return s;return null}resetInputMap(){this.inputMap=this._createDefaultEntries?.()??[]}getEntry(e,t,s){const i=this.inputMap;for(let r=0;r<i.length;r++){const n=i[r];if(n.source===e&&n.interaction===t&&this._entryConditionsMatch(n,s))return n}}getEntries(e,t,s){const i=[],r=this.inputMap;for(let n=0;n<r.length;n++){const a=r[n];a.source===e&&a.interaction===t&&this._entryConditionsMatch(a,s)&&i.push(a)}return i}addEntry(e){const t=this._entrySpecificity(e);let s=this.inputMap.length;for(let e=0;e<this.inputMap.length;e++)if(this._entrySpecificity(this.inputMap[e])<t){s=e;break}this.inputMap.splice(s,0,e)}setInteraction(e,t,s){const i=this.resolveInteraction(e,t);return i&&this._entryCoversAllConditionsOf(i,t)?(i.interaction=s,!0):(this.addEntry({source:e,...t??{},interaction:s}),!0)}_entryCoversAllConditionsOf(e,t){if(!t)return!0;const s=e;for(const e of Object.keys(t)){const i=t[e];if(void 0!==i)if("modifiers"===e){const e=s.modifiers??{};for(const t of Object.keys(i))if(void 0!==i[t]&&void 0===e[t])return!1}else if(void 0===s[e])return!1}return!0}setInteractions(e,t,s){let i=0;const r=this.inputMap;for(let n=0;n<r.length;n++){const a=r[n];a.source===e&&this._entryMatches(a,t)&&(a.interaction=s,i++)}return i}_entryMatches(e,t){switch(e.source){case"pointer":return(void 0===e.button||e.button===t?.button)&&this._matchModifiers(e.modifiers,t?.modifiers);case"wheel":return this._matchModifiers(e.modifiers,t?.modifiers);case"touch":return void 0===e.touchCount||e.touchCount===t?.touchCount;case"keyboard":return(void 0===e.key||(Array.isArray(e.key)?-1!==e.key.indexOf(t?.key??-1):e.key===t?.key))&&this._matchModifiers(e.modifiers,t?.modifiers)}}_entryConditionsMatch(e,t){if(!t)return!0;switch(e.source){case"pointer":return(!("button"in t)||e.button===t.button)&&(!("modifiers"in t)||this._entryModifiersMatch(e.modifiers,t.modifiers));case"wheel":return!("modifiers"in t)||this._entryModifiersMatch(e.modifiers,t.modifiers);case"touch":return!("touchCount"in t)||e.touchCount===t.touchCount;case"keyboard":if("key"in t){if(void 0===e.key)return void 0===t.key;if(void 0===t.key||(Array.isArray(e.key)?-1===e.key.indexOf(t.key):e.key!==t.key))return!1}return!("modifiers"in t)||this._entryModifiersMatch(e.modifiers,t.modifiers)}}_entrySpecificity(e){let t=0;return"button"in e&&void 0!==e.button&&t++,"key"in e&&void 0!==e.key&&t++,"touchCount"in e&&void 0!==e.touchCount&&t++,"modifiers"in e&&e.modifiers&&t++,t}_matchModifiers(e,t){return!e||(void 0===e.ctrl||e.ctrl===(t?.ctrl??!1))&&((void 0===e.shift||e.shift===(t?.shift??!1))&&(void 0===e.alt||e.alt===(t?.alt??!1)))}_entryModifiersMatch(e,t){if(!t)return!e;return void 0!==t.ctrl||void 0!==t.shift||void 0!==t.alt?(void 0===t.ctrl||e?.ctrl===t.ctrl)&&((void 0===t.shift||e?.shift===t.shift)&&(void 0===t.alt||e?.alt===t.alt)):!e||void 0===e.ctrl&&void 0===e.shift&&void 0===e.alt}}class Fa extends wa{constructor(e,t,s){super(e,t,s),this.input=new La({translate:(e,t,s)=>{this.panAccumulatedPixels.x+=e,this.panAccumulatedPixels.y+=t,this.panAccumulatedPixels.z+=s},rotate:(e,t)=>{this.rotationAccumulatedPixels.x+=e,this.rotationAccumulatedPixels.y+=t}},()=>this._createDefaultInputMap())}_createDefaultInputMap(){return[{source:"pointer",interaction:"rotate"},{source:"keyboard",interaction:"translate"},{source:"keyboard",interaction:"rotate"},{source:"touch",interaction:"rotate"},{source:"touch",interaction:"translate"}]}}const Na=Ie.Zero(),Ba=ve.Identity();let Ua=(()=>{var e;let t,s,i,r,n=bi,a=[],o=[],h=[],l=[],c=[],u=[],d=[],_=[];return e=class extends n{get inertia(){return this._targetInertia}set inertia(e){this._targetInertia=e,this.movement&&(this.movement.panInertia=e,this.movement.rotationInertia=e)}constructor(e,t,s,i=!0){super(e,t,s,i),this.cameraDirection=new xe(0,0,0),this.cameraRotation=new Me(0,0),this._targetInertia=.9,this.updateUpVectorFromRotation=A(this,a,!1),this.rotation=(A(this,o),A(this,h,void 0)),this.rotationQuaternion=A(this,l),this.speed=A(this,c,2),this.noRotationConstraint=(A(this,u),!1),this.invertRotation=!1,this.inverseRotationSpeed=.2,this._panningEpsilon=j,this._rotationEpsilon=j,this.lockedTarget=A(this,d,null),this._currentTarget=(A(this,_),xe.Zero()),this._initialFocalDistance=1,this._viewMatrix=Ie.Zero(),this._cameraTransformMatrix=Ie.Zero(),this._cameraRotationMatrix=Ie.Zero(),this._transformedReferencePoint=xe.Zero(),this._deferredPositionUpdate=new xe,this._deferredRotationQuaternionUpdate=new ve,this._deferredRotationUpdate=new xe,this._deferredUpdated=!1,this._deferOnly=!1,this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0,this._referencePoint=xe.Forward(this.getScene().useRightHandedSystem),this.rotation=new xe(0,this.getScene().useRightHandedSystem?Math.PI:0,0),this.movement=new Fa(this.getScene(),this.position),this.movement.panInertia=this.inertia,this.movement.rotationInertia=this.inertia}getFrontPosition(e){this.getWorldMatrix();const t=Ce.Vector3[0],s=Ce.Vector3[1];return s.set(0,0,this._scene.useRightHandedSystem?-1:1),this.getDirectionToRef(s,t),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){const e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&this._storedRotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)}_initCache(){super._initCache(),this._cache.lockedTarget=new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new ve(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();const t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;const e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){const e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=j),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),this.getScene().useRightHandedSystem?Ie.LookAtRHToRef(this.position,e,xe.UpReadOnly,Na):Ie.LookAtLHToRef(this.position,e,xe.UpReadOnly,Na),Na.invert();const t=this.rotationQuaternion||Ba;ve.FromRotationMatrixToRef(Na,t),t.toEulerAnglesToRef(this.rotation),this.rotation.z=0}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(Ce.Matrix[0]),xe.TransformNormalToRef(this.cameraDirection,Ce.Matrix[0],Ce.Vector3[0]),this._deferredPositionUpdate.addInPlace(Ce.Vector3[0]),void(this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate));this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){const e=this.movement,t=0!==this.cameraDirection.x||0!==this.cameraDirection.y||0!==this.cameraDirection.z;e.panAccumulatedPixels.addInPlace(this.cameraDirection),e.rotationAccumulatedPixels.x+=this.cameraRotation.x,e.rotationAccumulatedPixels.y+=this.cameraRotation.y,e.computeCurrentFrameDeltas(),this.cameraDirection.copyFrom(e.panDeltaCurrentFrame),this.cameraRotation.set(e.rotationDeltaCurrentFrame.x,e.rotationDeltaCurrentFrame.y);const s=this.speed*this._panningEpsilon;!t&&Math.abs(this.cameraDirection.x)<s&&Math.abs(this.cameraDirection.y)<s&&Math.abs(this.cameraDirection.z)<s&&(this.cameraDirection.setAll(0),e.resetPanVelocity());const i=this.invertRotation?-this.inverseRotationSpeed:1,r=this._decideIfNeedsToMove(),n=!(!this.cameraRotation.x&&!this.cameraRotation.y);if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),r&&this._updatePosition(),n){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*i,this._deferredRotationUpdate.y+=this.cameraRotation.y*i,!this.noRotationConstraint){const e=1.570796;this._deferredRotationUpdate.x>e&&(this._deferredRotationUpdate.x=e),this._deferredRotationUpdate.x<-e&&(this._deferredRotationUpdate.x=-e)}if(this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion){this._deferredRotationUpdate.lengthSquared()&&(ve.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))}}this.cameraDirection.setAll(0),this.cameraRotation.set(0,0),super._checkInputs()}_updateCameraRotationMatrix(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):Ie.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)}_rotateUpVectorWithCameraRotationMatrix(){return xe.TransformNormalToRef(xe.UpReadOnly,this._cameraRotationMatrix,this.upVector),this}_getViewMatrix(){return this.lockedTarget&&this.setTarget(this._getLockedTargetPosition()),this._updateCameraRotationMatrix(),this.rotationQuaternion&&this._cachedQuaternionRotationZ!=this.rotationQuaternion.z?(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedQuaternionRotationZ=this.rotationQuaternion.z):this._cachedRotationZ!==this.rotation.z&&(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedRotationZ=this.rotation.z),xe.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?gr.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(ve.FromEulerVectorToRef(this.rotation,Ba),gr.Y.rotateByQuaternionToRef(Ba,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix}_computeViewMatrix(e,t,s){if(this.getScene().useRightHandedSystem?Ie.LookAtRHToRef(e,t,s,this._viewMatrix):Ie.LookAtLHToRef(e,t,s,this._viewMatrix),this.parent){const e=this.parent.getWorldMatrix();this._viewMatrix.invert(),this._viewMatrix.multiplyToRef(e,this._viewMatrix),this._viewMatrix.invert(),this._markSyncedWithParent()}}createRigCamera(t,s){if(this.cameraRigMode!==bi.RIG_MODE_NONE){const s=new e(t,this.position.clone(),this.getScene());return s.isRigCamera=!0,s.rigParent=this,this.cameraRigMode===bi.RIG_MODE_VR&&(this.rotationQuaternion||(this.rotationQuaternion=new ve),s._cameraRigParams={},s.rotationQuaternion=new ve),s.mode=this.mode,s.orthoLeft=this.orthoLeft,s.orthoRight=this.orthoRight,s.orthoTop=this.orthoTop,s.orthoBottom=this.orthoBottom,s}return null}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case bi.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case bi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case bi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case bi.RIG_MODE_STEREOSCOPIC_OVERUNDER:case bi.RIG_MODE_STEREOSCOPIC_INTERLACED:{const s=this.cameraRigMode===bi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,i=this.cameraRigMode===bi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*s,e),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*i,t);break}case bi.RIG_MODE_VR:e.rotationQuaternion&&t.rotationQuaternion&&this.rotationQuaternion?(e.rotationQuaternion.copyFrom(this.rotationQuaternion),t.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.rotation.copyFrom(this.rotation),t.rotation.copyFrom(this.rotation)),e.position.copyFrom(this.position),t.position.copyFrom(this.position)}super._updateRigCameras()}_getRigCamPositionAndTarget(t,s){this.getTarget().subtractToRef(this.position,e._TargetFocalPoint),e._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);const i=e._TargetFocalPoint.addInPlace(this.position);Ie.TranslationToRef(-i.x,-i.y,-i.z,e._TargetTransformMatrix),e._TargetTransformMatrix.multiplyToRef(Ie.RotationAxis(s.upVector,t),e._RigCamTransformMatrix),Ie.TranslationToRef(i.x,i.y,i.z,e._TargetTransformMatrix),e._RigCamTransformMatrix.multiplyToRef(e._TargetTransformMatrix,e._RigCamTransformMatrix),xe.TransformCoordinatesToRef(this.position,e._RigCamTransformMatrix,s.position),s.setTarget(i)}getClassName(){return"TargetCamera"}},(()=>{const p="function"==typeof Symbol&&Symbol.metadata?Object.create(n[Symbol.metadata]??null):void 0;t=[L()],s=[k()],i=[L()],r=[G("lockedTargetId")],b(null,null,t,{kind:"field",name:"updateUpVectorFromRotation",static:!1,private:!1,access:{has:e=>"updateUpVectorFromRotation"in e,get:e=>e.updateUpVectorFromRotation,set:(e,t)=>{e.updateUpVectorFromRotation=t}},metadata:p},a,o),b(null,null,s,{kind:"field",name:"rotation",static:!1,private:!1,access:{has:e=>"rotation"in e,get:e=>e.rotation,set:(e,t)=>{e.rotation=t}},metadata:p},h,l),b(null,null,i,{kind:"field",name:"speed",static:!1,private:!1,access:{has:e=>"speed"in e,get:e=>e.speed,set:(e,t)=>{e.speed=t}},metadata:p},c,u),b(null,null,r,{kind:"field",name:"lockedTarget",static:!1,private:!1,access:{has:e=>"lockedTarget"in e,get:e=>e.lockedTarget,set:(e,t)=>{e.lockedTarget=t}},metadata:p},d,_),p&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:p})})(),e._RigCamTransformMatrix=new Ie,e._TargetTransformMatrix=new Ie,e._TargetFocalPoint=new xe,e})();var ka={};class Ga{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?a.Warn("camera input of type "+t+" already exists on camera"):(this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault))}remove(e){for(const t in this.attached){const s=this.attached[t];if(s===e)return s.detachControl(),s.camera=null,delete this.attached[t],void this.rebuildInputCheck()}}removeByType(e){for(const t in this.attached){const s=this.attached[t];s.getClassName()===e&&(s.detachControl(),s.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){const t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=!bi.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e;for(const t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(const t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(const e in this.attached){const t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){const t={};for(const e in this.attached){const s=this.attached[e],i=$e.Serialize(s);t[s.getClassName()]=i}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const s=ka[e];if(s){const i=t[e],r=$e.Parse(()=>new s,i,null);this.add(r)}}}else for(const t in this.attached){const s=ka[this.attached[t].getClassName()];if(s){const i=$e.Parse(()=>new s,e,null);this.remove(this.attached[t]),this.add(i)}}}}let Va=(()=>{var e;let t,s=[],i=[];return e=class{constructor(){this._currentMousePointerIdDown=-1,this.buttons=A(this,s,[0,1,2]),this._pointerInput=A(this,i)}attachControl(e){e=Fs.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),s=t.getInputElement();let i=0,r=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=n=>{const a=n.event,o="touch"===a.pointerType;if(n.type!==Yn.POINTERMOVE&&-1===this.buttons.indexOf(a.button))return;const h=a.target;if(this._altKey=a.altKey,this._ctrlKey=a.ctrlKey,this._metaKey=a.metaKey,this._shiftKey=a.shiftKey,this._buttonsPressed=a.buttons,t.isPointerLock){const e=a.movementX,t=a.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(n.type!==Yn.POINTERDOWN&&n.type!==Yn.POINTERDOUBLETAP&&o&&this._pointA?.pointerId!==a.pointerId&&this._pointB?.pointerId!==a.pointerId)return;if(n.type!==Yn.POINTERDOWN||-1!==this._currentMousePointerIdDown&&!o)if(n.type===Yn.POINTERDOUBLETAP)this.onDoubleTap(a.pointerType,a);else if(n.type!==Yn.POINTERUP||this._currentMousePointerIdDown!==a.pointerId&&!o){if(n.type===Yn.POINTERMOVE)if(e||a.preventDefault(),this._pointA&&null===this._pointB){const e=a.clientX-this._pointA.x,t=a.clientY-this._pointA.y;this._pointA.x=a.clientX,this._pointA.y=a.clientY,this.onTouch(this._pointA,e,t)}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===a.pointerId?this._pointA:this._pointB;e.x=a.clientX,e.y=a.clientY;const t=this._pointA.x-this._pointB.x,s=this._pointA.y-this._pointB.y,o=t*t+s*s,h={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:a.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,i,o,r,h),r=h,i=o}}else{try{h?.releasePointerCapture(a.pointerId)}catch(e){}o||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==a.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==a.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==i||r)&&(this.onMultiTouch(this._pointA,this._pointB,i,0,r,null),i=0,r=null),this._currentMousePointerIdDown=-1,this.onButtonUp(a),e||a.preventDefault()}else{try{h?.setPointerCapture(a.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:a.clientX,y:a.clientY,pointerId:a.pointerId,type:a.pointerType,button:a.button};else{if(null!==this._pointB)return;this._pointB={x:a.clientX,y:a.clientY,pointerId:a.pointerId,type:a.pointerType,button:a.button}}-1!==this._currentMousePointerIdDown||o||(this._currentMousePointerIdDown=a.pointerId),this.onButtonDown(a),e||(a.preventDefault(),s&&s.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Yn.POINTERDOWN|Yn.POINTERUP|Yn.POINTERMOVE|Yn.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,i=0,r=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),s&&s.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&Fs.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Fs.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentMousePointerIdDown=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e,t){}onTouch(e,t,s){}onMultiTouch(e,t,s,i,r,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}},(()=>{const r="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[L()],b(null,null,t,{kind:"field",name:"buttons",static:!1,private:!1,access:{has:e=>"buttons"in e,get:e=>e.buttons,set:(e,t)=>{e.buttons=t}},metadata:r},s,i),r&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:r})})(),e})(),Ha=(()=>{var e;let t,s,i,r=Va,n=[],a=[],o=[],h=[],l=[],c=[];return e=class extends r{constructor(){super(...arguments),this.pinchZoom=A(this,n,!0),this.multiTouchPanning=(A(this,a),A(this,o,!0)),this.multiTouchPanAndZoom=(A(this,h),A(this,l,!0)),this._isPinching=(A(this,c),!1),this._twoFingerActivityCount=0,this._shouldStartPinchZoom=!1}_computePinchZoom(e,t){}_computeMultiTouchPanning(e,t){}onMultiTouch(e,t,s,i,r,n){0===s&&null===r||0===i&&null===n||(this.multiTouchPanAndZoom?(this._computePinchZoom(s,i),this._computeMultiTouchPanning(r,n)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._shouldStartPinchZoom?(this._computePinchZoom(s,i),this._isPinching=!0):this._computeMultiTouchPanning(r,n)):this.multiTouchPanning?this._computeMultiTouchPanning(r,n):this.pinchZoom&&this._computePinchZoom(s,i))}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._twoFingerActivityCount=0,this._isPinching=!1}},(()=>{const u="function"==typeof Symbol&&Symbol.metadata?Object.create(r[Symbol.metadata]??null):void 0;t=[L()],s=[L()],i=[L()],b(null,null,t,{kind:"field",name:"pinchZoom",static:!1,private:!1,access:{has:e=>"pinchZoom"in e,get:e=>e.pinchZoom,set:(e,t)=>{e.pinchZoom=t}},metadata:u},n,a),b(null,null,s,{kind:"field",name:"multiTouchPanning",static:!1,private:!1,access:{has:e=>"multiTouchPanning"in e,get:e=>e.multiTouchPanning,set:(e,t)=>{e.multiTouchPanning=t}},metadata:u},o,h),b(null,null,i,{kind:"field",name:"multiTouchPanAndZoom",static:!1,private:!1,access:{has:e=>"multiTouchPanAndZoom"in e,get:e=>e.multiTouchPanAndZoom,set:(e,t)=>{e.multiTouchPanAndZoom=t}},metadata:u},l,c),u&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:u})})(),e})(),za=(()=>{var e;let t,s,i,r,n,a,o,h=Ha,l=[],c=[],u=[],d=[],_=[],p=[],f=[],g=[],m=[],T=[],E=[],R=[],y=[],M=[];return e=class extends h{constructor(){super(...arguments),this.buttons=A(this,l,[0,1,2]),this.angularSensibilityX=(A(this,c),A(this,u,1e3)),this.angularSensibilityY=(A(this,d),A(this,_,1e3)),this.pinchPrecision=(A(this,p),A(this,f,12)),this.pinchDeltaPercentage=(A(this,g),A(this,m,0)),this.useNaturalPinchZoom=(A(this,T),A(this,E,!1)),this.panningSensibility=(A(this,R),A(this,y,1e3)),this.pinchInwards=(A(this,M),!0),this._activeEntry=null,this._pointerLockConditions={button:0,modifiers:{}},this._pointerModifiers={ctrl:!1,alt:!1,shift:!1},this._pointerConditions={modifiers:this._pointerModifiers}}getClassName(){return"ArcRotateCameraPointersInput"}_computeMultiTouchPanning(e,t){if(e&&t){const s=t.x-e.x,i=t.y-e.y,r=this.camera.movement.input.getEntry("pointer","pan"),n=r?.sensitivity??(0!==this.panningSensibility?1/this.panningSensibility:0);0!==n&&(this.camera.movement.activeInput=!0,this.camera.movement.panAccumulatedPixels.x+=-s*n,this.camera.movement.panAccumulatedPixels.y+=i*n)}}_computePinchZoom(t,s){const i=this.camera.radius||e.MinimumRadiusForPinch;if(this.useNaturalPinchZoom)this.camera.radius=i*Math.sqrt(t)/Math.sqrt(s);else if(this.pinchDeltaPercentage){const e=.001*(s-t)*i*this.pinchDeltaPercentage;this.camera.movement.activeInput=!0,this.camera.movement.zoomAccumulatedPixels+=e}else{const e=(s-t)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2);this.camera.movement.activeInput=!0,this.camera.movement.zoomAccumulatedPixels+=e}}onTouch(e,t,s){const i=this._activeEntry??(this.camera.getEngine().isPointerLock?this.camera.movement.input.resolveInteraction("pointer",this._pointerLockConditions):null);if(i)if("pan"===i.interaction){const e=i.sensitivity??(0!==this.panningSensibility?1/this.panningSensibility:0);0!==e&&(this.camera.movement.activeInput=!0,this.camera.movement.panAccumulatedPixels.x+=-t*e,this.camera.movement.panAccumulatedPixels.y+=s*e)}else if("rotate"===i.interaction){const e=i.sensitivityX??i.sensitivity??1/this.angularSensibilityX,r=i.sensitivityY??i.sensitivity??1/this.angularSensibilityY;this.camera.movement.activeInput=!0,this.camera.movement.rotationAccumulatedPixels.x+=-t*e,this.camera.movement.rotationAccumulatedPixels.y+=-s*r}}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,s,i,r,n){this._shouldStartPinchZoom=this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(i)-Math.sqrt(s))>this.camera.pinchToPanMaxDistance,super.onMultiTouch(e,t,s,i,r,n)}onButtonDown(e){this._pointerConditions.button=e.button,this._pointerModifiers.ctrl=e.ctrlKey,this._pointerModifiers.alt=e.altKey,this._pointerModifiers.shift=e.shiftKey,this._activeEntry=this.camera.movement.input.resolveInteraction("pointer",this._pointerConditions),super.onButtonDown(e)}onButtonUp(e){this._activeEntry=null,super.onButtonUp(e)}onLostFocus(){this._activeEntry=null,super.onLostFocus()}},(()=>{const A="function"==typeof Symbol&&Symbol.metadata?Object.create(h[Symbol.metadata]??null):void 0;t=[L()],s=[L()],i=[L()],r=[L()],n=[L()],a=[L()],o=[L()],b(null,null,t,{kind:"field",name:"buttons",static:!1,private:!1,access:{has:e=>"buttons"in e,get:e=>e.buttons,set:(e,t)=>{e.buttons=t}},metadata:A},l,c),b(null,null,s,{kind:"field",name:"angularSensibilityX",static:!1,private:!1,access:{has:e=>"angularSensibilityX"in e,get:e=>e.angularSensibilityX,set:(e,t)=>{e.angularSensibilityX=t}},metadata:A},u,d),b(null,null,i,{kind:"field",name:"angularSensibilityY",static:!1,private:!1,access:{has:e=>"angularSensibilityY"in e,get:e=>e.angularSensibilityY,set:(e,t)=>{e.angularSensibilityY=t}},metadata:A},_,p),b(null,null,r,{kind:"field",name:"pinchPrecision",static:!1,private:!1,access:{has:e=>"pinchPrecision"in e,get:e=>e.pinchPrecision,set:(e,t)=>{e.pinchPrecision=t}},metadata:A},f,g),b(null,null,n,{kind:"field",name:"pinchDeltaPercentage",static:!1,private:!1,access:{has:e=>"pinchDeltaPercentage"in e,get:e=>e.pinchDeltaPercentage,set:(e,t)=>{e.pinchDeltaPercentage=t}},metadata:A},m,T),b(null,null,a,{kind:"field",name:"useNaturalPinchZoom",static:!1,private:!1,access:{has:e=>"useNaturalPinchZoom"in e,get:e=>e.useNaturalPinchZoom,set:(e,t)=>{e.useNaturalPinchZoom=t}},metadata:A},E,R),b(null,null,o,{kind:"field",name:"panningSensibility",static:!1,private:!1,access:{has:e=>"panningSensibility"in e,get:e=>e.panningSensibility,set:(e,t)=>{e.panningSensibility=t}},metadata:A},y,M),A&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:A})})(),e.MinimumRadiusForPinch=.001,e})();ka.ArcRotateCameraPointersInput=za;class Wa{}Wa.KEYDOWN=1,Wa.KEYUP=2;class Xa{constructor(e,t){this.type=e,this.event=t}}class Ka extends Xa{get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}}let Ya=(()=>{var e;let t,s,i,r,n,a,o,h,l,c,u,d=[],_=[],p=[],f=[],g=[],m=[],T=[],E=[],R=[],y=[],M=[],x=[],S=[],v=[],I=[],P=[],C=[],O=[],D=[],w=[],F=[];return e=class{constructor(){this.camera=A(this,d),this.keysUp=A(this,_,[38]),this.keysDown=(A(this,p),A(this,f,[40])),this.keysLeft=(A(this,g),A(this,m,[37])),this.keysRight=(A(this,T),A(this,E,[39])),this.keysReset=(A(this,R),A(this,y,[220])),this.keysZoomIn=(A(this,M),A(this,x,[187,107])),this.keysZoomOut=(A(this,S),A(this,v,[189,109])),this.panningSensibility=(A(this,I),A(this,P,50)),this.zoomingSensibility=(A(this,C),A(this,O,25)),this.angularSpeed=(A(this,D),A(this,w,.01)),this._useAltToZoom=(A(this,F),!0),this._keys=new Array,this._keyboardModifiers={ctrl:!1,alt:!1},this._keyboardConditions={modifiers:this._keyboardModifiers},this._rotateDirection=new Me,this._panDirection=new Me}get useAltToZoom(){return this._useAltToZoom}set useAltToZoom(e){this._useAltToZoom=e,this._applyUseAltToZoomToInputMap()}_applyUseAltToZoomToInputMap(){if(!this.camera?.movement)return;const e=this.camera.movement.input,t=e.getEntry("keyboard","zoom",{modifiers:{alt:!0}});!this._useAltToZoom&&t?e.inputMap.splice(e.inputMap.indexOf(t),1):this._useAltToZoom&&!t&&e.addEntry({source:"keyboard",modifiers:{alt:!0},interaction:"zoom"})}attachControl(e){e=Fs.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._applyUseAltToZoomToInputMap(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{const s=t.event;if(!s.metaKey)if(t.type===Wa.KEYDOWN){if(this._ctrlPressed=s.ctrlKey,this._altPressed=s.altKey,-1!==this.keysUp.indexOf(s.keyCode)||-1!==this.keysDown.indexOf(s.keyCode)||-1!==this.keysLeft.indexOf(s.keyCode)||-1!==this.keysRight.indexOf(s.keyCode)||-1!==this.keysReset.indexOf(s.keyCode)||-1!==this.keysZoomIn.indexOf(s.keyCode)||-1!==this.keysZoomOut.indexOf(s.keyCode)){-1===this._keys.indexOf(s.keyCode)&&this._keys.push(s.keyCode),s.preventDefault&&(e||s.preventDefault())}}else if(-1!==this.keysUp.indexOf(s.keyCode)||-1!==this.keysDown.indexOf(s.keyCode)||-1!==this.keysLeft.indexOf(s.keyCode)||-1!==this.keysRight.indexOf(s.keyCode)||-1!==this.keysReset.indexOf(s.keyCode)||-1!==this.keysZoomIn.indexOf(s.keyCode)||-1!==this.keysZoomOut.indexOf(s.keyCode)){const t=this._keys.indexOf(s.keyCode);t>=0&&this._keys.splice(t,1),s.preventDefault&&(e||s.preventDefault())}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera,t=e.movement.input;this._keyboardModifiers.ctrl=this._ctrlPressed,this._keyboardModifiers.alt=this._altPressed;const s=this._rotateDirection.set(0,0),i=this._panDirection.set(0,0);let r=0,n=0;for(let a=0;a<this._keys.length;a++){const o=this._keys[a];if(this._keyboardConditions.key=o,-1===this.keysReset.indexOf(o)){const e=t.resolveInteraction("keyboard",this._keyboardConditions);if(e)if("pan"===e.interaction)n=Math.max(n,e.sensitivity??1/this.panningSensibility),-1!==this.keysLeft.indexOf(o)?i.x-=1:-1!==this.keysRight.indexOf(o)?i.x+=1:-1!==this.keysUp.indexOf(o)?i.y+=1:-1!==this.keysDown.indexOf(o)&&(i.y-=1);else if("zoom"===e.interaction){const s=e.sensitivity??1/this.zoomingSensibility;-1!==this.keysUp.indexOf(o)||-1!==this.keysZoomIn.indexOf(o)?t.handlers.zoom(s):-1===this.keysDown.indexOf(o)&&-1===this.keysZoomOut.indexOf(o)||t.handlers.zoom(-s)}else"rotate"===e.interaction&&(r=Math.max(r,e.sensitivity??this.angularSpeed),-1!==this.keysLeft.indexOf(o)?s.x-=1:-1!==this.keysRight.indexOf(o)?s.x+=1:-1!==this.keysUp.indexOf(o)?s.y-=1:-1!==this.keysDown.indexOf(o)&&(s.y+=1))}-1!==this.keysReset.indexOf(o)&&e.useInputToRestoreState&&e.restoreState()}0===s.x&&0===s.y||(s.normalize().scaleInPlace(r),t.handlers.rotate(s.x,s.y)),0===i.x&&0===i.y||(i.normalize().scaleInPlace(n),t.handlers.pan(i.x,i.y))}}getClassName(){return"ArcRotateCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}},(()=>{const A="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[L()],s=[L()],i=[L()],r=[L()],n=[L()],a=[L()],o=[L()],h=[L()],l=[L()],c=[L()],u=[L()],b(e,null,u,{kind:"getter",name:"useAltToZoom",static:!1,private:!1,access:{has:e=>"useAltToZoom"in e,get:e=>e.useAltToZoom},metadata:A},null,d),b(null,null,t,{kind:"field",name:"keysUp",static:!1,private:!1,access:{has:e=>"keysUp"in e,get:e=>e.keysUp,set:(e,t)=>{e.keysUp=t}},metadata:A},_,p),b(null,null,s,{kind:"field",name:"keysDown",static:!1,private:!1,access:{has:e=>"keysDown"in e,get:e=>e.keysDown,set:(e,t)=>{e.keysDown=t}},metadata:A},f,g),b(null,null,i,{kind:"field",name:"keysLeft",static:!1,private:!1,access:{has:e=>"keysLeft"in e,get:e=>e.keysLeft,set:(e,t)=>{e.keysLeft=t}},metadata:A},m,T),b(null,null,r,{kind:"field",name:"keysRight",static:!1,private:!1,access:{has:e=>"keysRight"in e,get:e=>e.keysRight,set:(e,t)=>{e.keysRight=t}},metadata:A},E,R),b(null,null,n,{kind:"field",name:"keysReset",static:!1,private:!1,access:{has:e=>"keysReset"in e,get:e=>e.keysReset,set:(e,t)=>{e.keysReset=t}},metadata:A},y,M),b(null,null,a,{kind:"field",name:"keysZoomIn",static:!1,private:!1,access:{has:e=>"keysZoomIn"in e,get:e=>e.keysZoomIn,set:(e,t)=>{e.keysZoomIn=t}},metadata:A},x,S),b(null,null,o,{kind:"field",name:"keysZoomOut",static:!1,private:!1,access:{has:e=>"keysZoomOut"in e,get:e=>e.keysZoomOut,set:(e,t)=>{e.keysZoomOut=t}},metadata:A},v,I),b(null,null,h,{kind:"field",name:"panningSensibility",static:!1,private:!1,access:{has:e=>"panningSensibility"in e,get:e=>e.panningSensibility,set:(e,t)=>{e.panningSensibility=t}},metadata:A},P,C),b(null,null,l,{kind:"field",name:"zoomingSensibility",static:!1,private:!1,access:{has:e=>"zoomingSensibility"in e,get:e=>e.zoomingSensibility,set:(e,t)=>{e.zoomingSensibility=t}},metadata:A},O,D),b(null,null,c,{kind:"field",name:"angularSpeed",static:!1,private:!1,access:{has:e=>"angularSpeed"in e,get:e=>e.angularSpeed,set:(e,t)=>{e.angularSpeed=t}},metadata:A},w,F),A&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:A})})(),e})();var ja;ka.ArcRotateCameraKeyboardMoveInput=Ya,function(e){e[e.PointerMove=0]="PointerMove",e[e.PointerDown=1]="PointerDown",e[e.PointerUp=2]="PointerUp"}(ja||(ja={}));class qa{}qa.DOM_DELTA_PIXEL=0,qa.DOM_DELTA_LINE=1,qa.DOM_DELTA_PAGE=2;let $a=(()=>{var e;let t,s,i,r=[],n=[],a=[],o=[],h=[],l=[];return e=class{constructor(){this.wheelPrecision=A(this,r,3),this.zoomToMouseLocation=(A(this,n),A(this,a,!1)),this.wheelDeltaPercentage=(A(this,o),A(this,h,0)),this.customComputeDeltaFromMouseWheel=(A(this,l),null),this._viewOffset=new xe(0,0,0),this._globalOffset=new xe(0,0,0),this._inertialPanning=xe.Zero(),this._zoomToMouseRadiusOffset=0}_computeDeltaFromMouseWheelLegacyEvent(e,t){let s;const i=.01*e*this.wheelDeltaPercentage*t;return s=e>0?i/(1+this.wheelDeltaPercentage):i*(1+this.wheelDeltaPercentage),s}attachControl(e){e=Fs.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Yn.POINTERWHEEL)return;const s=t.event;let i;const r=s.deltaMode===qa.DOM_DELTA_LINE?40:1,n=-s.deltaY*r;if(this.customComputeDeltaFromMouseWheel)i=this.customComputeDeltaFromMouseWheel(n,this,s);else if(this.wheelDeltaPercentage){if(i=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),i>0){const e=this.zoomToMouseLocation?this._zoomToMouseRadiusOffset:this.camera.inertialRadiusOffset;let t=this.camera.radius,s=e+i;for(let e=0;e<20&&!(t<=s)&&!(Math.abs(s*this.camera.inertia)<.001);e++)t-=s,s*=this.camera.inertia;t=ne(t,0,Number.MAX_VALUE),i=this._computeDeltaFromMouseWheelLegacyEvent(n,t)}}else{const e=this.camera.movement.input.getEntry("wheel","zoom");i=n*(e?.sensitivity??1/(40*this.wheelPrecision))}i&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(i)):this.camera.movement.zoomAccumulatedPixels+=i),s.preventDefault&&(e||s.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Yn.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;const e=this.camera;if(Math.abs(this._zoomToMouseRadiusOffset)+this._inertialPanning.lengthSquared()+Math.abs(e.inertialAlphaOffset)+Math.abs(e.inertialBetaOffset)+Math.abs(e.inertialRadiusOffset)){this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),e.radius-=this._zoomToMouseRadiusOffset;const t=e.movement.getFrameIndependentDecay(e.inertia);this._inertialPanning.scaleInPlace(t),this._zoomToMouseRadiusOffset*=t,this._zeroIfClose(this._inertialPanning),Math.abs(this._zoomToMouseRadiusOffset)<j&&(this._zoomToMouseRadiusOffset=0)}}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){const e=this.camera,t=e.target.subtract(e.position);this._hitPlane=Ys.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),s=t.createPickingRay(t.pointerX,t.pointerY,Ie.Identity(),e,!1);0===e.targetScreenOffset.x&&0===e.targetScreenOffset.y||(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=xe.TransformNormal(this._viewOffset,e._cameraTransformMatrix),s.origin.addInPlace(this._globalOffset));let i=0;return this._hitPlane&&(i=s.intersectsPlane(this._hitPlane)??0),s.origin.addInPlace(s.direction.scaleInPlace(i))}_zoomToMouse(e){const t=this.camera,s=1-t.inertia,i=t.movement.getFrameIndependentInputScale(t.inertia);if(t.lowerRadiusLimit){const r=t.lowerRadiusLimit??0;t.radius-(this._zoomToMouseRadiusOffset+e*i)/s<r&&(e=((t.radius-r)*s-this._zoomToMouseRadiusOffset)/i)}if(t.upperRadiusLimit){const r=t.upperRadiusLimit??0;t.radius-(this._zoomToMouseRadiusOffset+e*i)/s>r&&(e=((t.radius-r)*s-this._zoomToMouseRadiusOffset)/i)}const r=e/s/t.radius,n=this._getPosition(),a=Ce.Vector3[6];n.subtractToRef(t.target,a),a.scaleInPlace(r),a.scaleInPlace(s),a.scaleInPlace(i),this._inertialPanning.addInPlace(a),this._zoomToMouseRadiusOffset+=e*i}_zeroIfClose(e){Math.abs(e.x)<j&&(e.x=0),Math.abs(e.y)<j&&(e.y=0),Math.abs(e.z)<j&&(e.z=0)}},(()=>{const c="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[L()],s=[L()],i=[L()],b(null,null,t,{kind:"field",name:"wheelPrecision",static:!1,private:!1,access:{has:e=>"wheelPrecision"in e,get:e=>e.wheelPrecision,set:(e,t)=>{e.wheelPrecision=t}},metadata:c},r,n),b(null,null,s,{kind:"field",name:"zoomToMouseLocation",static:!1,private:!1,access:{has:e=>"zoomToMouseLocation"in e,get:e=>e.zoomToMouseLocation,set:(e,t)=>{e.zoomToMouseLocation=t}},metadata:c},a,o),b(null,null,i,{kind:"field",name:"wheelDeltaPercentage",static:!1,private:!1,access:{has:e=>"wheelDeltaPercentage"in e,get:e=>e.wheelDeltaPercentage,set:(e,t)=>{e.wheelDeltaPercentage=t}},metadata:c},h,l),c&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:c})})(),e})();ka.ArcRotateCameraMouseWheelInput=$a;class Za extends Ga{constructor(e){super(e)}addMouseWheel(){return this.add(new $a),this}addPointers(){return this.add(new za),this}addKeyboard(){return this.add(new Ya),this}}Za.prototype.addVRDeviceOrientation??=Ne("ArcRotateCameraInputsManager","addVRDeviceOrientation"),Za.prototype.addGamepad??=Ne("ArcRotateCameraInputsManager","addGamepad");class Qa extends wa{constructor(e,t,s){super(e,t,s),this.input=new La({pan:(e,t)=>{this.panAccumulatedPixels.x+=e,this.panAccumulatedPixels.y+=t},rotate:(e,t)=>{this.rotationAccumulatedPixels.x+=e,this.rotationAccumulatedPixels.y+=t},zoom:e=>{this.zoomAccumulatedPixels+=e}},()=>this._createDefaultInputMap())}_createDefaultInputMap(){return[{source:"pointer",button:0,modifiers:{ctrl:!0},interaction:"pan"},{source:"pointer",button:0,interaction:"rotate"},{source:"pointer",button:2,interaction:"pan"},{source:"wheel",interaction:"zoom"},{source:"keyboard",key:[187,107,189,109],interaction:"zoom"},{source:"keyboard",modifiers:{ctrl:!0},interaction:"pan"},{source:"keyboard",modifiers:{alt:!0},interaction:"zoom"},{source:"keyboard",interaction:"rotate"}]}}function Ja(e){let t=Math.PI/2;return 0===e.x&&0===e.z||(t=Math.acos(e.x/Math.sqrt(Math.pow(e.x,2)+Math.pow(e.z,2)))),e.z<0&&(t=2*Math.PI-t),t}function eo(e,t){return Math.acos(e/t)}function to(e,t){return isNaN(e)?t:e}let so=(()=>{var e;let t,s,i,r,n,a,o,h,l,u,d,_,p,f,g,m,T,E,R,y,M,x,S,v,I,P,C,O,D=Ua,w=[],F=[],N=[],B=[],V=[],H=[],z=[],W=[],X=[],K=[],Y=[],q=[],$=[],Z=[],Q=[],J=[],ee=[],te=[],se=[],ie=[],re=[],ae=[],oe=[],he=[],le=[],ce=[],ue=[],de=[],_e=[],pe=[],fe=[],ge=[],me=[],Te=[],Ee=[],Re=[],be=[],Ae=[],ye=[],Se=[],Pe=[],Oe=[],De=[],we=[],Le=[],Fe=[],Ne=[];return e=class extends D{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new Ie,this._upToYMatrix=new Ie,this._upVector=xe.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){Ie.RotationAlignToRef(xe.UpReadOnly,this._upVector,this._yToUpMatrix),Ie.RotationAlignToRef(this._upVector,xe.UpReadOnly,this._upToYMatrix)}get inertialAlphaOffset(){if(0!==this._inertialAlphaOffset)return this._inertialAlphaOffset;if(0!==this.movement.rotationAccumulatedPixels.x)return this.movement.rotationAccumulatedPixels.x;const e=this.movement.rotationDeltaCurrentFrame.x;return Math.abs(e)<this._rotationEpsilon?0:e}set inertialAlphaOffset(e){this._inertialAlphaOffset=e,0===e&&this.movement.resetRotationVelocity()}get inertialBetaOffset(){if(0!==this._inertialBetaOffset)return this._inertialBetaOffset;if(0!==this.movement.rotationAccumulatedPixels.y)return this.movement.rotationAccumulatedPixels.y;const e=this.movement.rotationDeltaCurrentFrame.y;return Math.abs(e)<this._rotationEpsilon?0:e}set inertialBetaOffset(e){this._inertialBetaOffset=e,0===e&&this.movement.resetRotationVelocity()}get inertialRadiusOffset(){if(0!==this._inertialRadiusOffset)return this._inertialRadiusOffset;if(0!==this.movement.zoomAccumulatedPixels)return this.movement.zoomAccumulatedPixels;const e=this.movement.zoomDeltaCurrentFrame;return Math.abs(e)<this._rotationEpsilon?0:e}set inertialRadiusOffset(e){this._inertialRadiusOffset=e,0===e&&this.movement.resetZoomVelocity()}get panningInertia(){return this._panningInertia}set panningInertia(e){this._panningInertia=e,this.movement&&(this.movement.panInertia=e)}get inertia(){return this._inertia}set inertia(e){this._inertia=e,this.movement&&(this.movement.rotationInertia=e,this.movement.zoomInertia=e)}get angularSensibilityX(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){const e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){const t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){const e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){const t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){const e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){const t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){const e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){const t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){const e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){const e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){const t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){const e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get _useCtrlForPanning(){return this._useCtrlForPanningInternal}set _useCtrlForPanning(e){this._useCtrlForPanningInternal=e;const t=this.movement.input,s=t.getEntry("keyboard","pan",{modifiers:{ctrl:!0}});!e&&s?t.inputMap.splice(t.inputMap.indexOf(s),1):e&&!s&&t.addEntry({source:"keyboard",modifiers:{ctrl:!0},interaction:"pan"});const i=t.getEntry("pointer","pan",{modifiers:{ctrl:!0}});!e&&i?t.inputMap.splice(t.inputMap.indexOf(i),1):e&&!i&&t.addEntry({source:"pointer",button:0,modifiers:{ctrl:!0},interaction:"pan"})}get _panningMouseButton(){return this._panningMouseButtonInternal}set _panningMouseButton(e){this._panningMouseButtonInternal=e;const t=this.movement.input.getEntry("pointer","pan",{modifiers:{}});t&&(t.button=e)}get isInterpolating(){return this._isInterpolating}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Oa,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return null!=this._framingBehavior}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new Da,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return null!=this._autoRotationBehavior}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new Zn,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,s,i,r,n,a=!0){super(e,xe.Zero(),n,a),this.alpha=(A(this,w),A(this,F,void 0)),this.beta=(A(this,N),A(this,B,void 0)),this.radius=(A(this,V),A(this,H,void 0)),this.overrideCloneAlphaBetaRadius=(A(this,z),A(this,W,void 0)),this._target=(A(this,X),A(this,K,void 0)),this._targetHost=(A(this,Y),A(this,q,void 0)),this._upToYMatrix=A(this,$),this._inertialAlphaOffset=0,this._inertialBetaOffset=0,this._inertialRadiusOffset=0,this.lowerAlphaLimit=A(this,Z,null),this.upperAlphaLimit=(A(this,Q),A(this,J,null)),this.lowerBetaLimit=(A(this,ee),A(this,te,.01)),this.upperBetaLimit=(A(this,se),A(this,ie,Math.PI-.01)),this.lowerRadiusLimit=(A(this,re),A(this,ae,null)),this.upperRadiusLimit=(A(this,oe),A(this,he,null)),this.lowerTargetYLimit=(A(this,le),A(this,ce,-1/0)),this.inertialPanningX=(A(this,ue),A(this,de,0)),this.inertialPanningY=(A(this,_e),A(this,pe,0)),this.pinchToPanMaxDistance=(A(this,fe),A(this,ge,20)),this.panningDistanceLimit=(A(this,me),A(this,Te,null)),this.panningOriginTarget=(A(this,Ee),A(this,Re,xe.Zero())),this._panningInertia=(A(this,be),.9),this._inertia=.9,this.zoomOnFactor=A(this,Ae,1),this.targetScreenOffset=(A(this,ye),A(this,Se,Me.Zero())),this.allowUpsideDown=(A(this,Pe),A(this,Oe,!0)),this.useInputToRestoreState=(A(this,De),A(this,we,!0)),this.restoreStateInterpolationFactor=(A(this,Le),A(this,Fe,0)),this._currentInterpolationFactor=(A(this,Ne),0),this._viewMatrix=new Ie,this._useCtrlForPanningInternal=!0,this._panningMouseButtonInternal=2,this.panningAxis=new xe(1,1,0),this._transformedDirection=new xe,this.mapPanning=!1,this._isInterpolating=!1,this.onMeshTargetChangedObservable=new c,this.checkCollisions=!1,this.collisionRadius=new xe(.5,.5,.5),this._previousPosition=xe.Zero(),this._collisionVelocity=xe.Zero(),this._newPosition=xe.Zero(),this._computationVector=xe.Zero(),this._goalAlpha=NaN,this._goalBeta=NaN,this._goalRadius=NaN,this._goalTarget=new xe(NaN,NaN,NaN),this._goalTargetScreenOffset=new Me(NaN,NaN),this._onCollisionPositionChange=(e,t,s=null)=>{s?(this.setPosition(t),this.onCollide&&this.onCollide(s)):this._previousPosition.copyFrom(this._position);const i=Math.cos(this.alpha),r=Math.sin(this.alpha),n=Math.cos(this.beta);let a=Math.sin(this.beta);0===a&&(a=1e-4);const o=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*i*a,this.radius*n,this.radius*r*a),o.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let h=this.upVector;this.allowUpsideDown&&this.beta<0&&(h=h.clone(),h=h.negate()),this._computeViewMatrix(this._position,o,h),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=xe.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=s,this.radius=i,this.getViewMatrix(),this.inputs=new Za(this),this.inputs.addKeyboard().addMouseWheel().addPointers(),this.movement=new Qa(this.getScene(),this._position),this.movement.rotationInertia=this._inertia,this.movement.zoomInertia=this._inertia,this.movement.panInertia=this._panningInertia}_initCache(){super._initCache(),this._cache._target=new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=Me.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){const e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}const e=this._getLockedTargetPosition();return e||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return this.hasStateStored()&&this.restoreStateInterpolationFactor>j&&this.restoreStateInterpolationFactor<1?(this.interpolateTo(this._storedAlpha,this._storedBeta,this._storedRadius,this._storedTarget,this._storedTargetScreenOffset,this.restoreStateInterpolationFactor),!0):!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}stopInterpolation(){this._goalAlpha=NaN,this._goalBeta=NaN,this._goalRadius=NaN,this._goalTarget.set(NaN,NaN,NaN),this._goalTargetScreenOffset.set(NaN,NaN)}interpolateTo(e=this.alpha,t=this.beta,s=this.radius,i=this.target,r=this.targetScreenOffset,n){this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,null!=n?this._currentInterpolationFactor=n:0!==this.restoreStateInterpolationFactor?this._currentInterpolationFactor=this.restoreStateInterpolationFactor:this._currentInterpolationFactor=.1,this._goalAlpha=to(e,this._goalAlpha),this._goalBeta=to(t,this._goalBeta),this._goalRadius=to(s,this._goalRadius),this._goalTarget.set(to(i.x,this._goalTarget.x),to(i.y,this._goalTarget.y),to(i.z,this._goalTarget.z)),this._goalTargetScreenOffset.set(to(r.x,this._goalTargetScreenOffset.x),to(r.y,this._goalTargetScreenOffset.y)),this._goalAlpha=ne(this._goalAlpha,this.lowerAlphaLimit??-1/0,this.upperAlphaLimit??1/0),this._goalBeta=ne(this._goalBeta,this.lowerBetaLimit??-1/0,this.upperBetaLimit??1/0),this._goalRadius=ne(this._goalRadius,this.lowerRadiusLimit??-1/0,this.upperRadiusLimit??1/0),this._goalTarget.y=ne(this._goalTarget.y,this.lowerTargetYLimit??-1/0,1/0),this._isInterpolating=!0}_isSynchronizedViewMatrix(){return!!super._isSynchronizedViewMatrix()&&(this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset))}attachControl(e,t,s=!0,i=2){const r=arguments;t=Fs.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=s,this._panningMouseButton=i,"boolean"==typeof r[0]&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_applyRotationAndZoomDelta(e,t,s){const i=this.invertRotation?-1:1;let r=e*this._calculateHandednessMultiplier();this.beta<0&&(r*=-1),this.alpha+=r*i,this.beta+=t*i,this.radius-=s}_applyPanDelta(e,t){const s=Ce.Vector3[0].copyFromFloats(e,t,t);if(this._viewMatrix.invertToRef(this._cameraTransformMatrix),s.multiplyInPlace(this.panningAxis),xe.TransformNormalToRef(s,this._cameraTransformMatrix,this._transformedDirection),this.mapPanning){const e=this.upVector,t=xe.CrossToRef(this._transformedDirection,e,this._transformedDirection);xe.CrossToRef(e,t,this._transformedDirection)}else this.panningAxis.y||(this._transformedDirection.y=0);if(!this._targetHost)if(null!==this.panningDistanceLimit){this._transformedDirection.addInPlace(this._target);xe.DistanceSquared(this._transformedDirection,this.panningOriginTarget)<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection)}else{if(this.parent){const e=Ce.Matrix[0];this.parent.getWorldMatrix().getRotationMatrixToRef(e),e.transposeToRef(e),xe.TransformCoordinatesToRef(this._transformedDirection,e,this._transformedDirection)}this._target.addInPlace(this._transformedDirection)}}_checkInputs(){if(this._collisionTriggered)return;this.inputs.checkInputs();let e=!1;this.movement.computeCurrentFrameDeltas();const t=this.movement.rotationDeltaCurrentFrame,s=this.movement.zoomDeltaCurrentFrame,i=this.movement.panDeltaCurrentFrame;if(0===t.x&&0===t.y&&0===s&&0===i.x&&0===i.y||(e=!0,0===t.x&&0===t.y&&0===s||this._applyRotationAndZoomDelta(t.x,t.y,s),0===i.x&&0===i.y||this._applyPanDelta(i.x,i.y)),0===this._inertialAlphaOffset&&0===this._inertialBetaOffset&&0===this._inertialRadiusOffset||(this._applyRotationAndZoomDelta(this._inertialAlphaOffset,this._inertialBetaOffset,this._inertialRadiusOffset),this._inertialAlphaOffset*=this.inertia,this._inertialBetaOffset*=this.inertia,this._inertialRadiusOffset*=this.inertia,Math.abs(this._inertialAlphaOffset)<this._rotationEpsilon&&(this._inertialAlphaOffset=0),Math.abs(this._inertialBetaOffset)<this._rotationEpsilon&&(this._inertialBetaOffset=0),Math.abs(this._inertialRadiusOffset)<this._rotationEpsilon&&(this._inertialRadiusOffset=0),e=!0),0!==this.inertialPanningX||0!==this.inertialPanningY){this._applyPanDelta(this.inertialPanningX,this.inertialPanningY),this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia;const t=this._panningEpsilon;Math.abs(this.inertialPanningX)<t&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<t&&(this.inertialPanningY=0),e=!0}if(e)this.stopInterpolation();else if(this._isInterpolating){let e=!1;const t=this._scene.getEngine().getDeltaTime()/1e3,s=1-Math.pow(2,-t/this._currentInterpolationFactor),i=to(this._goalRadius,this.radius);if(!isNaN(this._goalTarget.x)||!isNaN(this._goalTarget.y)||!isNaN(this._goalTarget.z)){const t=Ce.Vector3[0].set(to(this._goalTarget.x,this._target.x),to(this._goalTarget.y,this._target.y),to(this._goalTarget.z,this._target.z));xe.LerpToRef(this.target,t,s,this._target),10*xe.Distance(this.target,t)/i<j?(this._goalTarget.set(NaN,NaN,NaN),this.target.copyFrom(t),this.setTarget(this.target,!1,!0,!0)):e=!0}if(!isNaN(this._goalAlpha)||!isNaN(this._goalBeta)){const t=ve.RotationAlphaBetaGammaToRef(to(this._goalAlpha,this.alpha),to(this._goalBeta,this.beta),0,Ce.Quaternion[0]),i=ve.RotationAlphaBetaGammaToRef(this.alpha,this.beta,0,Ce.Quaternion[1]),r=ve.SlerpToRef(i,t,s,Ce.Quaternion[2]);r.normalize();const n=r.toAlphaBetaGammaToRef(Ce.Vector3[0]);if(this.alpha=n.x,this.beta=n.y,r.isApprox(t,2e-4)){this._goalAlpha=NaN,this._goalBeta=NaN;const e=t.toAlphaBetaGammaToRef(Ce.Vector3[0]);this.alpha=e.x,this.beta=e.y}else e=!0}if(isNaN(this._goalRadius)||(this.radius+=(i-this.radius)*s,Math.abs(i/this.radius-1)<j?(this._goalRadius=NaN,this.radius=i):e=!0),!isNaN(this._goalTargetScreenOffset.x)||!isNaN(this._goalTargetScreenOffset.y)){const t=Ce.Vector2[0].set(to(this._goalTargetScreenOffset.x,this.targetScreenOffset.x),to(this._goalTargetScreenOffset.y,this.targetScreenOffset.y));Me.LerpToRef(this.targetScreenOffset,t,s,this.targetScreenOffset),Me.Distance(this.targetScreenOffset,t)<j?(this._goalTargetScreenOffset.set(NaN,NaN),this.targetScreenOffset.copyFrom(t)):e=!0}this._isInterpolating=e}this._checkLimits(),super._checkInputs()}_checkLimits(){null===this.lowerBetaLimit||void 0===this.lowerBetaLimit?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),null===this.upperBetaLimit||void 0===this.upperBetaLimit?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),null!==this.upperAlphaLimit&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit,this.inertialRadiusOffset=0),null!==this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0),this.target.y=Math.max(this.target.y,this.lowerTargetYLimit)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||xe.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;this.alpha=Ja(this._computationVector),this.beta=eo(this._computationVector.y,this.radius);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,s=!1,i=!1){if(i=this.overrideCloneAlphaBetaRadius??i,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const t=e,i=this._getTargetPosition();if(i&&!s&&i.equals(t))return;this._targetHost=null,this._target=t,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}i||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),s=Math.cos(this.beta);let i=Math.sin(this.beta);0===i&&(i=1e-4),0===this.radius&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*i,this.radius*s,this.radius*t*i),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||xe.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&i<0&&(e=e.negate()),this._computeViewMatrix(this._position,r,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget.copyFrom(r),this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const s=Xn.MinMax(e);let i=this._calculateLowerRadiusFromModelBoundingSphere(s.min,s.max);if(i=Math.max(Math.min(i,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=i*this.zoomOnFactor,this.mode===bi.ORTHOGRAPHIC_CAMERA){const e=this.getScene().getEngine().getAspectRatio(this),t=i*this.zoomOnFactor/2;this.orthoLeft=-t*e,this.orthoRight=t*e,this.orthoBottom=-t,this.orthoTop=t}this.focusOn({min:s.min,max:s.max,distance:i},t)}focusOn(e,t=!1){let s,i;if(void 0===e.min){const t=e||this.getScene().meshes;s=Xn.MinMax(t),i=xe.Distance(s.min,s.max)}else{s=e,i=e.distance}this._target=Xn.Center(s),t||(this.maxZ=2*i)}createRigCamera(t,s){let i=0;switch(this.cameraRigMode){case bi.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case bi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case bi.RIG_MODE_STEREOSCOPIC_OVERUNDER:case bi.RIG_MODE_STEREOSCOPIC_INTERLACED:case bi.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===s?1:-1);break;case bi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===s?-1:1)}const r=new e(t,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case bi.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case bi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case bi.RIG_MODE_STEREOSCOPIC_OVERUNDER:case bi.RIG_MODE_STEREOSCOPIC_INTERLACED:case bi.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case bi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,s=1){const i=xe.Distance(e,t),r=this.getScene().getEngine().getAspectRatio(this),n=Math.tan(this.fov/2),a=n*r,o=.5*i*s,h=o*Math.sqrt(1+1/(a*a)),l=o*Math.sqrt(1+1/(n*n));return Math.max(h,l)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}},(()=>{const c="function"==typeof Symbol&&Symbol.metadata?Object.create(D[Symbol.metadata]??null):void 0;t=[L()],s=[L()],i=[L()],r=[L()],n=[k("target")],a=[G("targetHost")],o=[L()],h=[L()],l=[L()],u=[L()],d=[L()],_=[L()],p=[L()],f=[L()],g=[L()],m=[L()],T=[L()],E=[L()],R=[L()],y=[L()],M=[k()],x=[L()],S=[L()],v=[L()],I=[U()],P=[L()],C=[L()],O=[L()],b(e,null,o,{kind:"getter",name:"inertialAlphaOffset",static:!1,private:!1,access:{has:e=>"inertialAlphaOffset"in e,get:e=>e.inertialAlphaOffset},metadata:c},null,w),b(e,null,h,{kind:"getter",name:"inertialBetaOffset",static:!1,private:!1,access:{has:e=>"inertialBetaOffset"in e,get:e=>e.inertialBetaOffset},metadata:c},null,w),b(e,null,l,{kind:"getter",name:"inertialRadiusOffset",static:!1,private:!1,access:{has:e=>"inertialRadiusOffset"in e,get:e=>e.inertialRadiusOffset},metadata:c},null,w),b(e,null,x,{kind:"getter",name:"panningInertia",static:!1,private:!1,access:{has:e=>"panningInertia"in e,get:e=>e.panningInertia},metadata:c},null,w),b(e,null,S,{kind:"getter",name:"zoomToMouseLocation",static:!1,private:!1,access:{has:e=>"zoomToMouseLocation"in e,get:e=>e.zoomToMouseLocation},metadata:c},null,w),b(null,null,t,{kind:"field",name:"alpha",static:!1,private:!1,access:{has:e=>"alpha"in e,get:e=>e.alpha,set:(e,t)=>{e.alpha=t}},metadata:c},F,N),b(null,null,s,{kind:"field",name:"beta",static:!1,private:!1,access:{has:e=>"beta"in e,get:e=>e.beta,set:(e,t)=>{e.beta=t}},metadata:c},B,V),b(null,null,i,{kind:"field",name:"radius",static:!1,private:!1,access:{has:e=>"radius"in e,get:e=>e.radius,set:(e,t)=>{e.radius=t}},metadata:c},H,z),b(null,null,r,{kind:"field",name:"overrideCloneAlphaBetaRadius",static:!1,private:!1,access:{has:e=>"overrideCloneAlphaBetaRadius"in e,get:e=>e.overrideCloneAlphaBetaRadius,set:(e,t)=>{e.overrideCloneAlphaBetaRadius=t}},metadata:c},W,X),b(null,null,n,{kind:"field",name:"_target",static:!1,private:!1,access:{has:e=>"_target"in e,get:e=>e._target,set:(e,t)=>{e._target=t}},metadata:c},K,Y),b(null,null,a,{kind:"field",name:"_targetHost",static:!1,private:!1,access:{has:e=>"_targetHost"in e,get:e=>e._targetHost,set:(e,t)=>{e._targetHost=t}},metadata:c},q,$),b(null,null,u,{kind:"field",name:"lowerAlphaLimit",static:!1,private:!1,access:{has:e=>"lowerAlphaLimit"in e,get:e=>e.lowerAlphaLimit,set:(e,t)=>{e.lowerAlphaLimit=t}},metadata:c},Z,Q),b(null,null,d,{kind:"field",name:"upperAlphaLimit",static:!1,private:!1,access:{has:e=>"upperAlphaLimit"in e,get:e=>e.upperAlphaLimit,set:(e,t)=>{e.upperAlphaLimit=t}},metadata:c},J,ee),b(null,null,_,{kind:"field",name:"lowerBetaLimit",static:!1,private:!1,access:{has:e=>"lowerBetaLimit"in e,get:e=>e.lowerBetaLimit,set:(e,t)=>{e.lowerBetaLimit=t}},metadata:c},te,se),b(null,null,p,{kind:"field",name:"upperBetaLimit",static:!1,private:!1,access:{has:e=>"upperBetaLimit"in e,get:e=>e.upperBetaLimit,set:(e,t)=>{e.upperBetaLimit=t}},metadata:c},ie,re),b(null,null,f,{kind:"field",name:"lowerRadiusLimit",static:!1,private:!1,access:{has:e=>"lowerRadiusLimit"in e,get:e=>e.lowerRadiusLimit,set:(e,t)=>{e.lowerRadiusLimit=t}},metadata:c},ae,oe),b(null,null,g,{kind:"field",name:"upperRadiusLimit",static:!1,private:!1,access:{has:e=>"upperRadiusLimit"in e,get:e=>e.upperRadiusLimit,set:(e,t)=>{e.upperRadiusLimit=t}},metadata:c},he,le),b(null,null,m,{kind:"field",name:"lowerTargetYLimit",static:!1,private:!1,access:{has:e=>"lowerTargetYLimit"in e,get:e=>e.lowerTargetYLimit,set:(e,t)=>{e.lowerTargetYLimit=t}},metadata:c},ce,ue),b(null,null,T,{kind:"field",name:"inertialPanningX",static:!1,private:!1,access:{has:e=>"inertialPanningX"in e,get:e=>e.inertialPanningX,set:(e,t)=>{e.inertialPanningX=t}},metadata:c},de,_e),b(null,null,E,{kind:"field",name:"inertialPanningY",static:!1,private:!1,access:{has:e=>"inertialPanningY"in e,get:e=>e.inertialPanningY,set:(e,t)=>{e.inertialPanningY=t}},metadata:c},pe,fe),b(null,null,R,{kind:"field",name:"pinchToPanMaxDistance",static:!1,private:!1,access:{has:e=>"pinchToPanMaxDistance"in e,get:e=>e.pinchToPanMaxDistance,set:(e,t)=>{e.pinchToPanMaxDistance=t}},metadata:c},ge,me),b(null,null,y,{kind:"field",name:"panningDistanceLimit",static:!1,private:!1,access:{has:e=>"panningDistanceLimit"in e,get:e=>e.panningDistanceLimit,set:(e,t)=>{e.panningDistanceLimit=t}},metadata:c},Te,Ee),b(null,null,M,{kind:"field",name:"panningOriginTarget",static:!1,private:!1,access:{has:e=>"panningOriginTarget"in e,get:e=>e.panningOriginTarget,set:(e,t)=>{e.panningOriginTarget=t}},metadata:c},Re,be),b(null,null,v,{kind:"field",name:"zoomOnFactor",static:!1,private:!1,access:{has:e=>"zoomOnFactor"in e,get:e=>e.zoomOnFactor,set:(e,t)=>{e.zoomOnFactor=t}},metadata:c},Ae,ye),b(null,null,I,{kind:"field",name:"targetScreenOffset",static:!1,private:!1,access:{has:e=>"targetScreenOffset"in e,get:e=>e.targetScreenOffset,set:(e,t)=>{e.targetScreenOffset=t}},metadata:c},Se,Pe),b(null,null,P,{kind:"field",name:"allowUpsideDown",static:!1,private:!1,access:{has:e=>"allowUpsideDown"in e,get:e=>e.allowUpsideDown,set:(e,t)=>{e.allowUpsideDown=t}},metadata:c},Oe,De),b(null,null,C,{kind:"field",name:"useInputToRestoreState",static:!1,private:!1,access:{has:e=>"useInputToRestoreState"in e,get:e=>e.useInputToRestoreState,set:(e,t)=>{e.useInputToRestoreState=t}},metadata:c},we,Le),b(null,null,O,{kind:"field",name:"restoreStateInterpolationFactor",static:!1,private:!1,access:{has:e=>"restoreStateInterpolationFactor"in e,get:e=>e.restoreStateInterpolationFactor,set:(e,t)=>{e.restoreStateInterpolationFactor=t}},metadata:c},Fe,Ne),c&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:c})})(),e})(),io=!1;io||(io=!0,Qe.AddNodeConstructor("ArcRotateCamera",(e,t)=>()=>new so(e,0,0,1,xe.Zero(),t)),be("BABYLON.ArcRotateCamera",so));let ro=(()=>{var e,t;let s,i,r,n,a,o,h,l,c,u,d,_,p,f=Qe,g=[],m=[],T=[],E=[],R=[],y=[],S=[],v=[],I=[],P=[],C=[],O=[],D=[],F=[],B=[],U=[],k=[],G=[],V=[],H=[],z=[];return e=class extends f{get range(){return this._range}set range(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)}get intensityMode(){return this._intensityMode}set intensityMode(e){this._intensityMode=e,this._computePhotometricScale()}get radius(){return this._radius}set radius(e){this._radius=e,this._computePhotometricScale()}get renderPriority(){return M(this,t,"f")}set renderPriority(e){x(this,t,e,"f")}get shadowEnabled(){return this._shadowEnabled}set shadowEnabled(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())}get includedOnlyMeshes(){return this._includedOnlyMeshes}set includedOnlyMeshes(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)}get excludedMeshes(){return this._excludedMeshes}set excludedMeshes(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)}get excludeWithLayerMask(){return this._excludeWithLayerMask}set excludeWithLayerMask(e){this._excludeWithLayerMask=e,this._resyncMeshes()}get includeOnlyWithLayerMask(){return this._includeOnlyWithLayerMask}set includeOnlyWithLayerMask(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()}get lightmapMode(){return this._lightmapMode}set lightmapMode(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())}getViewMatrix(e){return null}getProjectionMatrix(e,t){return null}constructor(s,i,r){super(s,i,!1),this.diffuse=(A(this,g),A(this,m,new Xe(1,1,1))),this.specular=(A(this,T),A(this,E,new Xe(1,1,1))),this.falloffType=(A(this,R),A(this,y,e.FALLOFF_DEFAULT)),this.intensity=(A(this,S),A(this,v,1)),this._range=(A(this,I),Number.MAX_VALUE),this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=e.INTENSITYMODE_AUTOMATIC,this._radius=1e-5,this._renderPriority=A(this,P,void 0),t.set(this,(A(this,C),A(this,O,0))),this._shadowEnabled=(A(this,D),A(this,F,!0)),this._includedOnlyMeshes=A(this,B),this._excludeWithLayerMask=A(this,U,0),this._includeOnlyWithLayerMask=(A(this,k),A(this,G,0)),this._lightmapMode=(A(this,V),A(this,H,0)),this._shadowGenerators=(A(this,z),null),this._excludedMeshesIds=new Array,this._includedOnlyMeshesIds=new Array,this._currentViewDepth=0,this._clusteredContainer=null,this._isLight=!0,r||this.getScene().addLight(this),this._uniformBuffer=new dr(this.getScene().getEngine(),void 0,void 0,s),this._buildUniformLayout(),this.includedOnlyMeshes=[],this.excludedMeshes=[],r||this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,s,i,r=!0){const n=e.toString();let a=!1;if(this._uniformBuffer.bindToEffect(s,"Light"+n),this._renderId!==t.getRenderId()||this._lastUseSpecular!==i||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=i;const e=this.getScaledIntensity();this.transferToEffect(s,n),this.diffuse.scaleToRef(e,Ye.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",Ye.Color3[0],this.range,n),i&&(this.specular.scaleToRef(e,Ye.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",Ye.Color3[1],this.radius,n)),a=!0}if(this.transferTexturesToEffect(s,n),t.shadowsEnabled&&this.shadowEnabled&&r){const e=this.getShadowGenerator(t.activeCamera)??this.getShadowGenerator();e&&(e.bindShadowLight(n,s),a=!0)}a?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()}getClassName(){return"Light"}toString(e){let t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric","Clustered"][this.getTypeID()],this.animations)for(let s=0;s<this.animations.length;s++)t+=", animation[0]: "+this.animations[s].toString(e);return t}_syncParentEnabledState(){super._syncParentEnabledState(),this.isDisposed()||this._resyncMeshes()}setEnabled(e){super.setEnabled(e),this._resyncMeshes()}getShadowGenerator(e=null){return null===this._shadowGenerators?null:this._shadowGenerators.get(e)??null}getShadowGenerators(){return this._shadowGenerators}getAbsolutePosition(){return xe.Zero()}canAffectMesh(e){return!e||!(this.includedOnlyMeshes&&this.includedOnlyMeshes.length>0&&-1===this.includedOnlyMeshes.indexOf(e))&&(!(this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e))&&((0===this.includeOnlyWithLayerMask||0!==(this.includeOnlyWithLayerMask&e.layerMask))&&!(0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask)))}dispose(e,t=!1){if(this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next()){t.value.dispose()}this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(const e of this.getScene().meshes)e._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(t,s=null){const i=e.GetConstructorFromName(this.getTypeID(),t,this.getScene());if(!i)return null;const r=$e.Clone(i,this);return t&&(r.name=t),s&&(r.parent=s),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){const e=$e.Serialize(this);if(e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0){e.excludedMeshesIds=[];for(const t of this.excludedMeshes)e.excludedMeshesIds.push(t.id)}if(this.includedOnlyMeshes.length>0){e.includedOnlyMeshesIds=[];for(const t of this.includedOnlyMeshes)e.includedOnlyMeshesIds.push(t.id)}return $e.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,s){const i=Qe.Construct("Light_Type_"+e,t,s);return i||null}static Parse(t,s,i=""){const r=e.GetConstructorFromName(t.type,t.name,s);if(!r)return null;const n=$e.Parse(r,t,s,i);if(t.excludedMeshesIds&&(n._excludedMeshesIds=t.excludedMeshesIds),t.includedOnlyMeshesIds&&(n._includedOnlyMeshesIds=t.includedOnlyMeshesIds),void 0!==t.parentId&&(n._waitingParentId=t.parentId),void 0!==t.parentInstanceIndex&&(n._waitingParentInstanceIndex=t.parentInstanceIndex),void 0!==t.falloffType&&(n.falloffType=t.falloffType),void 0!==t.lightmapMode&&(n.lightmapMode=t.lightmapMode),t.animations){for(let e=0;e<t.animations.length;e++){const s=t.animations[e],i=Ae("BABYLON.Animation");i&&n.animations.push(i.Parse(s))}Qe.ParseAnimationRanges(n,t,s)}return t.autoAnimate&&s.beginAnimation(n,t.autoAnimateFrom,t.autoAnimateTo,t.autoAnimateLoop,t.autoAnimateSpeed||1),void 0!==t.isEnabled&&n.setEnabled(t.isEnabled),n._onParsed(t,s,i),n}_onParsed(e,t,s=""){}_hookArrayForExcluded(e){const t=e.push;e.push=(...s)=>{const i=t.apply(e,s);if(this._clusteredContainer)return i;for(const e of s)e._resyncLightSource(this);return i};const s=e.splice;e.splice=(t,i)=>{const r=s.call(e,t,i??e.length);if(this._clusteredContainer)return r;for(const e of r)e._resyncLightSource(this);return r},this._resyncMeshes()}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...s)=>{const i=t.apply(e,s);return this._resyncMeshes(),i};const s=e.splice;e.splice=(t,i)=>{const r=s.call(e,t,i??e.length);return this._resyncMeshes(),r},this._resyncMeshes()}_resyncMeshes(){if(!this._clusteredContainer)for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let t=0;const s=this.getTypeID();let i=this.intensityMode;switch(i===e.INTENSITYMODE_AUTOMATIC&&(i=s===e.LIGHTTYPEID_DIRECTIONALLIGHT?e.INTENSITYMODE_ILLUMINANCE:e.INTENSITYMODE_LUMINOUSINTENSITY),s){case e.LIGHTTYPEID_POINTLIGHT:case e.LIGHTTYPEID_SPOTLIGHT:switch(i){case e.INTENSITYMODE_LUMINOUSPOWER:t=1/(4*Math.PI);break;case e.INTENSITYMODE_LUMINOUSINTENSITY:t=1;break;case e.INTENSITYMODE_LUMINANCE:t=this.radius*this.radius}break;case e.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case e.INTENSITYMODE_ILLUMINANCE:t=1;break;case e.INTENSITYMODE_LUMINANCE:{let e=this.radius;e=Math.max(e,.001);t=2*Math.PI*(1-Math.cos(e));break}}break;case e.LIGHTTYPEID_HEMISPHERICLIGHT:case e.LIGHTTYPEID_RECT_AREALIGHT:t=1}return t}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}areLightTexturesReady(){return!0}_isReady(){return!0}},t=new WeakMap,(()=>{const t="function"==typeof Symbol&&Symbol.metadata?Object.create(f[Symbol.metadata]??null):void 0;s=[N()],i=[N()],r=[L()],n=[L()],a=[L()],o=[L()],h=[L()],l=[L()],c=[w("_reorderLightsInScene")],u=[L("shadowEnabled")],d=[L("excludeWithLayerMask")],_=[L("includeOnlyWithLayerMask")],p=[L("lightmapMode")],b(e,null,a,{kind:"getter",name:"range",static:!1,private:!1,access:{has:e=>"range"in e,get:e=>e.range},metadata:t},null,g),b(e,null,o,{kind:"getter",name:"intensityMode",static:!1,private:!1,access:{has:e=>"intensityMode"in e,get:e=>e.intensityMode},metadata:t},null,g),b(e,null,h,{kind:"getter",name:"radius",static:!1,private:!1,access:{has:e=>"radius"in e,get:e=>e.radius},metadata:t},null,g),b(e,null,c,{kind:"accessor",name:"renderPriority",static:!1,private:!1,access:{has:e=>"renderPriority"in e,get:e=>e.renderPriority,set:(e,t)=>{e.renderPriority=t}},metadata:t},O,D),b(null,null,s,{kind:"field",name:"diffuse",static:!1,private:!1,access:{has:e=>"diffuse"in e,get:e=>e.diffuse,set:(e,t)=>{e.diffuse=t}},metadata:t},m,T),b(null,null,i,{kind:"field",name:"specular",static:!1,private:!1,access:{has:e=>"specular"in e,get:e=>e.specular,set:(e,t)=>{e.specular=t}},metadata:t},E,R),b(null,null,r,{kind:"field",name:"falloffType",static:!1,private:!1,access:{has:e=>"falloffType"in e,get:e=>e.falloffType,set:(e,t)=>{e.falloffType=t}},metadata:t},y,S),b(null,null,n,{kind:"field",name:"intensity",static:!1,private:!1,access:{has:e=>"intensity"in e,get:e=>e.intensity,set:(e,t)=>{e.intensity=t}},metadata:t},v,I),b(null,null,l,{kind:"field",name:"_renderPriority",static:!1,private:!1,access:{has:e=>"_renderPriority"in e,get:e=>e._renderPriority,set:(e,t)=>{e._renderPriority=t}},metadata:t},P,C),b(null,null,u,{kind:"field",name:"_shadowEnabled",static:!1,private:!1,access:{has:e=>"_shadowEnabled"in e,get:e=>e._shadowEnabled,set:(e,t)=>{e._shadowEnabled=t}},metadata:t},F,B),b(null,null,d,{kind:"field",name:"_excludeWithLayerMask",static:!1,private:!1,access:{has:e=>"_excludeWithLayerMask"in e,get:e=>e._excludeWithLayerMask,set:(e,t)=>{e._excludeWithLayerMask=t}},metadata:t},U,k),b(null,null,_,{kind:"field",name:"_includeOnlyWithLayerMask",static:!1,private:!1,access:{has:e=>"_includeOnlyWithLayerMask"in e,get:e=>e._includeOnlyWithLayerMask,set:(e,t)=>{e._includeOnlyWithLayerMask=t}},metadata:t},G,V),b(null,null,p,{kind:"field",name:"_lightmapMode",static:!1,private:!1,access:{has:e=>"_lightmapMode"in e,get:e=>e._lightmapMode,set:(e,t)=>{e._lightmapMode=t}},metadata:t},H,z),t&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:t})})(),e.FALLOFF_DEFAULT=Mr.FALLOFF_DEFAULT,e.FALLOFF_PHYSICAL=Mr.FALLOFF_PHYSICAL,e.FALLOFF_GLTF=Mr.FALLOFF_GLTF,e.FALLOFF_STANDARD=Mr.FALLOFF_STANDARD,e.LIGHTMAP_DEFAULT=Mr.LIGHTMAP_DEFAULT,e.LIGHTMAP_SPECULAR=Mr.LIGHTMAP_SPECULAR,e.LIGHTMAP_SHADOWSONLY=Mr.LIGHTMAP_SHADOWSONLY,e.INTENSITYMODE_AUTOMATIC=Mr.INTENSITYMODE_AUTOMATIC,e.INTENSITYMODE_LUMINOUSPOWER=Mr.INTENSITYMODE_LUMINOUSPOWER,e.INTENSITYMODE_LUMINOUSINTENSITY=Mr.INTENSITYMODE_LUMINOUSINTENSITY,e.INTENSITYMODE_ILLUMINANCE=Mr.INTENSITYMODE_ILLUMINANCE,e.INTENSITYMODE_LUMINANCE=Mr.INTENSITYMODE_LUMINANCE,e.LIGHTTYPEID_POINTLIGHT=Mr.LIGHTTYPEID_POINTLIGHT,e.LIGHTTYPEID_DIRECTIONALLIGHT=Mr.LIGHTTYPEID_DIRECTIONALLIGHT,e.LIGHTTYPEID_SPOTLIGHT=Mr.LIGHTTYPEID_SPOTLIGHT,e.LIGHTTYPEID_HEMISPHERICLIGHT=Mr.LIGHTTYPEID_HEMISPHERICLIGHT,e.LIGHTTYPEID_RECT_AREALIGHT=Mr.LIGHTTYPEID_RECT_AREALIGHT,e})(),no=(()=>{var e;let t,s,i,r,n=ro,a=[];return e=class extends n{constructor(){super(...arguments),this._position=A(this,a),this._needProjectionMatrixCompute=!0,this._viewMatrix=Ie.Identity(),this._projectionMatrix=Ie.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=xe.Zero()),xe.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=xe.Zero()),xe.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0)}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=xe.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=xe.Cross(this.direction,gr.Y),t=xe.Cross(e,this.direction);return xe.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=xe.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=Ie.Identity()),Ie.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return void 0!==this.shadowMinZ?this.shadowMinZ:e?.minZ||dt.ShadowMinZ}getDepthMaxZ(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e?.maxZ||dt.ShadowMaxZ}setShadowProjectionMatrix(e,t,s){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,s,e):this._setDefaultShadowProjectionMatrix(e,t,s),this}_syncParentEnabledState(){super._syncParentEnabledState(),this.parent&&this.parent.getWorldMatrix||(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=Ce.Vector3[0];let s=this.position;this.computeTransformedInformation()&&(s=this.transformedPosition),xe.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(xe.Dot(t,xe.Up()))&&(t.z=1e-13);const i=Ce.Vector3[1];return s.addToRef(t,i),Ie.LookAtLHToRef(s,i,xe.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}},(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(n[Symbol.metadata]??null):void 0;t=[k()],s=[k()],i=[L()],r=[L()],b(e,null,t,{kind:"getter",name:"position",static:!1,private:!1,access:{has:e=>"position"in e,get:e=>e.position},metadata:o},null,a),b(e,null,s,{kind:"getter",name:"direction",static:!1,private:!1,access:{has:e=>"direction"in e,get:e=>e.direction},metadata:o},null,a),b(e,null,i,{kind:"getter",name:"shadowMinZ",static:!1,private:!1,access:{has:e=>"shadowMinZ"in e,get:e=>e.shadowMinZ},metadata:o},null,a),b(e,null,r,{kind:"getter",name:"shadowMaxZ",static:!1,private:!1,access:{has:e=>"shadowMaxZ"in e,get:e=>e.shadowMaxZ},metadata:o},null,a),o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e})(),ao=(()=>{var e;let t,s,i,r,n,a,o,h,l=no,c=[],u=[],d=[],_=[],p=[],f=[],g=[],m=[],T=[],E=[],R=[],y=[],M=[];return e=class extends l{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,s,i){super(e,s,i),this._shadowFrustumSize=(A(this,c),0),this._shadowOrthoScale=.1,this.autoUpdateExtends=A(this,u,!0),this.autoCalcShadowZBounds=(A(this,d),A(this,_,!1)),this._orthoLeft=(A(this,p),A(this,f,Number.MAX_VALUE)),this._orthoRight=(A(this,g),A(this,m,Number.MIN_VALUE)),this._orthoTop=(A(this,T),A(this,E,Number.MIN_VALUE)),this._orthoBottom=(A(this,R),A(this,y,Number.MAX_VALUE)),A(this,M),this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return ro.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,s){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,s)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;Ie.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t?t.minZ:dt.ShadowMinZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t?t.maxZ:dt.ShadowMaxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,s){const i=this.getScene().activeCamera;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=xe.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let i=Number.MAX_VALUE,r=-Number.MAX_VALUE;for(let n=0;n<s.length;n++){const a=s[n];if(!a)continue;const o=a.getBoundingInfo().boundingBox;for(let s=0;s<o.vectorsWorld.length;s++)xe.TransformCoordinatesToRef(o.vectorsWorld[s],t,e),e.x<this._orthoLeft&&(this._orthoLeft=e.x),e.y<this._orthoBottom&&(this._orthoBottom=e.y),e.x>this._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.z<i&&(i=e.z),e.z>r&&(r=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=i,this._shadowMaxZ=r)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:i?.minZ||dt.ShadowMinZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:i?.maxZ||dt.ShadowMaxZ,h=this.getScene().getEngine().useReverseDepthBuffer;Ie.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,h?o:a,h?a:o,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}},(()=>{const A="function"==typeof Symbol&&Symbol.metadata?Object.create(l[Symbol.metadata]??null):void 0;t=[L()],s=[L()],i=[L()],r=[L()],n=[L("orthoLeft")],a=[L("orthoRight")],o=[L("orthoTop")],h=[L("orthoBottom")],b(e,null,t,{kind:"getter",name:"shadowFrustumSize",static:!1,private:!1,access:{has:e=>"shadowFrustumSize"in e,get:e=>e.shadowFrustumSize},metadata:A},null,c),b(e,null,s,{kind:"getter",name:"shadowOrthoScale",static:!1,private:!1,access:{has:e=>"shadowOrthoScale"in e,get:e=>e.shadowOrthoScale},metadata:A},null,c),b(null,null,i,{kind:"field",name:"autoUpdateExtends",static:!1,private:!1,access:{has:e=>"autoUpdateExtends"in e,get:e=>e.autoUpdateExtends,set:(e,t)=>{e.autoUpdateExtends=t}},metadata:A},u,d),b(null,null,r,{kind:"field",name:"autoCalcShadowZBounds",static:!1,private:!1,access:{has:e=>"autoCalcShadowZBounds"in e,get:e=>e.autoCalcShadowZBounds,set:(e,t)=>{e.autoCalcShadowZBounds=t}},metadata:A},_,p),b(null,null,n,{kind:"field",name:"_orthoLeft",static:!1,private:!1,access:{has:e=>"_orthoLeft"in e,get:e=>e._orthoLeft,set:(e,t)=>{e._orthoLeft=t}},metadata:A},f,g),b(null,null,a,{kind:"field",name:"_orthoRight",static:!1,private:!1,access:{has:e=>"_orthoRight"in e,get:e=>e._orthoRight,set:(e,t)=>{e._orthoRight=t}},metadata:A},m,T),b(null,null,o,{kind:"field",name:"_orthoTop",static:!1,private:!1,access:{has:e=>"_orthoTop"in e,get:e=>e._orthoTop,set:(e,t)=>{e._orthoTop=t}},metadata:A},E,R),b(null,null,h,{kind:"field",name:"_orthoBottom",static:!1,private:!1,access:{has:e=>"_orthoBottom"in e,get:e=>e._orthoBottom,set:(e,t)=>{e._orthoBottom=t}},metadata:A},y,M),A&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:A})})(),e})(),oo=!1;oo||(oo=!0,Qe.AddNodeConstructor("Light_Type_1",(e,t)=>()=>new ao(e,xe.Zero(),t)),be("BABYLON.DirectionalLight",ao));let ho=(()=>{var e;let t,s,i=ro,r=[],n=[],a=[],o=[];return e=class extends i{constructor(e,t,s,i){super(e,s,i),this.groundColor=A(this,r,new Xe(0,0,0)),this.direction=(A(this,n),A(this,a,void 0)),A(this,o),this.direction=t||xe.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=xe.Normalize(e.subtract(xe.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const s=xe.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",s.x,s.y,s.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){const s=xe.Normalize(this.direction);return e.setFloat3(t,s.x,s.y,s.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=Ie.Identity()),this._worldMatrix}getTypeID(){return ro.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}},(()=>{const h="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;t=[N()],s=[k()],b(null,null,t,{kind:"field",name:"groundColor",static:!1,private:!1,access:{has:e=>"groundColor"in e,get:e=>e.groundColor,set:(e,t)=>{e.groundColor=t}},metadata:h},r,n),b(null,null,s,{kind:"field",name:"direction",static:!1,private:!1,access:{has:e=>"direction"in e,get:e=>e.direction,set:(e,t)=>{e.direction=t}},metadata:h},a,o),h&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:h})})(),e})(),lo=!1;lo||(lo=!0,Qe.AddNodeConstructor("Light_Type_3",(e,t)=>()=>new ho(e,xe.Zero(),t)),be("BABYLON.HemisphericLight",ho));class co{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach((e,t)=>this.add(e,t))}get(e){const t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let s=this.get(e);return void 0!==s||(s=t(e),s&&this.add(e,s)),s}getOrAdd(e,t){const s=this.get(e);return void 0!==s?s:(this.add(e,t),t)}contains(e){return void 0!==this._data[e]}add(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)}set(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null}remove(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data){e(t,this._data[t])}}first(e){for(const t in this._data){const s=e(t,this._data[t]);if(s)return s}return null}}function uo(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}let _o=(()=>{var e;let t,s,i,r,n,a,o,h,l,c,u,d,_=[],p=[],f=[],g=[],m=[],T=[],E=[],R=[],y=[],M=[],x=[],S=[],v=[],I=[],P=[],C=[],O=[],D=[],w=[],F=[],N=[],B=[],U=[],k=[];return e=class{constructor(){this._dirty=!0,this._tempColor=new Ke(0,0,0,0),this._globalCurve=new Ke(0,0,0,0),this._highlightsCurve=new Ke(0,0,0,0),this._midtonesCurve=new Ke(0,0,0,0),this._shadowsCurve=new Ke(0,0,0,0),this._positiveCurve=new Ke(0,0,0,0),this._negativeCurve=new Ke(0,0,0,0),this._globalHue=A(this,_,30),this._globalDensity=(A(this,p),A(this,f,0)),this._globalSaturation=(A(this,g),A(this,m,0)),this._globalExposure=(A(this,T),A(this,E,0)),this._highlightsHue=(A(this,R),A(this,y,30)),this._highlightsDensity=(A(this,M),A(this,x,0)),this._highlightsSaturation=(A(this,S),A(this,v,0)),this._highlightsExposure=(A(this,I),A(this,P,0)),this._midtonesHue=(A(this,C),A(this,O,30)),this._midtonesDensity=(A(this,D),A(this,w,0)),this._midtonesSaturation=(A(this,F),A(this,N,0)),this._midtonesExposure=(A(this,B),A(this,U,0)),this._shadowsHue=(A(this,k),30),this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}_getColorGradingDataToRef(t,s,i,r,n){null!=t&&(t=e._Clamp(t,0,360),s=e._Clamp(s,-100,100),i=e._Clamp(i,-100,100),r=e._Clamp(r,-100,100),s=e._ApplyColorGradingSliderNonlinear(s),s*=.5,r=e._ApplyColorGradingSliderNonlinear(r),s<0&&(s*=-1,t=(t+180)%360),e._FromHSBToRef(t,s,50+.25*r,n),n.scaleToRef(2,n),n.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(t,s,i,r){let n=e._Clamp(t,0,360);const a=e._Clamp(s/100,0,1),o=e._Clamp(i/100,0,1);if(0===a)r.r=o,r.g=o,r.b=o;else{n/=60;const e=Math.floor(n),t=n-e,s=o*(1-a),i=o*(1-a*t),h=o*(1-a*(1-t));switch(e){case 0:r.r=o,r.g=h,r.b=s;break;case 1:r.r=i,r.g=o,r.b=s;break;case 2:r.r=s,r.g=o,r.b=h;break;case 3:r.r=s,r.g=i,r.b=o;break;case 4:r.r=h,r.g=s,r.b=o;break;default:r.r=o,r.g=s,r.b=i}}r.a=1}static _Clamp(e,t,s){return Math.min(Math.max(e,t),s)}clone(){return $e.Clone(()=>new e,this)}serialize(){return $e.Serialize(this)}_bind(e,t="vCameraColorCurvePositive",s="vCameraColorCurveNeutral",i="vCameraColorCurveNegative"){this._dirty&&(this._dirty=!1,this._getColorGradingDataToRef(this._globalHue,this._globalDensity,this._globalSaturation,this._globalExposure,this._globalCurve),this._getColorGradingDataToRef(this._highlightsHue,this._highlightsDensity,this._highlightsSaturation,this._highlightsExposure,this._tempColor),this._tempColor.multiplyToRef(this._globalCurve,this._highlightsCurve),this._getColorGradingDataToRef(this._midtonesHue,this._midtonesDensity,this._midtonesSaturation,this._midtonesExposure,this._tempColor),this._tempColor.multiplyToRef(this._globalCurve,this._midtonesCurve),this._getColorGradingDataToRef(this._shadowsHue,this._shadowsDensity,this._shadowsSaturation,this._shadowsExposure,this._tempColor),this._tempColor.multiplyToRef(this._globalCurve,this._shadowsCurve),this._highlightsCurve.subtractToRef(this._midtonesCurve,this._positiveCurve),this._midtonesCurve.subtractToRef(this._shadowsCurve,this._negativeCurve)),e&&(e.setFloat4(t,this._positiveCurve.r,this._positiveCurve.g,this._positiveCurve.b,this._positiveCurve.a),e.setFloat4(s,this._midtonesCurve.r,this._midtonesCurve.g,this._midtonesCurve.b,this._midtonesCurve.a),e.setFloat4(i,this._negativeCurve.r,this._negativeCurve.g,this._negativeCurve.b,this._negativeCurve.a))}},(()=>{const A="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[L()],s=[L()],i=[L()],r=[L()],n=[L()],a=[L()],o=[L()],h=[L()],l=[L()],c=[L()],u=[L()],d=[L()],b(null,null,t,{kind:"field",name:"_globalHue",static:!1,private:!1,access:{has:e=>"_globalHue"in e,get:e=>e._globalHue,set:(e,t)=>{e._globalHue=t}},metadata:A},_,p),b(null,null,s,{kind:"field",name:"_globalDensity",static:!1,private:!1,access:{has:e=>"_globalDensity"in e,get:e=>e._globalDensity,set:(e,t)=>{e._globalDensity=t}},metadata:A},f,g),b(null,null,i,{kind:"field",name:"_globalSaturation",static:!1,private:!1,access:{has:e=>"_globalSaturation"in e,get:e=>e._globalSaturation,set:(e,t)=>{e._globalSaturation=t}},metadata:A},m,T),b(null,null,r,{kind:"field",name:"_globalExposure",static:!1,private:!1,access:{has:e=>"_globalExposure"in e,get:e=>e._globalExposure,set:(e,t)=>{e._globalExposure=t}},metadata:A},E,R),b(null,null,n,{kind:"field",name:"_highlightsHue",static:!1,private:!1,access:{has:e=>"_highlightsHue"in e,get:e=>e._highlightsHue,set:(e,t)=>{e._highlightsHue=t}},metadata:A},y,M),b(null,null,a,{kind:"field",name:"_highlightsDensity",static:!1,private:!1,access:{has:e=>"_highlightsDensity"in e,get:e=>e._highlightsDensity,set:(e,t)=>{e._highlightsDensity=t}},metadata:A},x,S),b(null,null,o,{kind:"field",name:"_highlightsSaturation",static:!1,private:!1,access:{has:e=>"_highlightsSaturation"in e,get:e=>e._highlightsSaturation,set:(e,t)=>{e._highlightsSaturation=t}},metadata:A},v,I),b(null,null,h,{kind:"field",name:"_highlightsExposure",static:!1,private:!1,access:{has:e=>"_highlightsExposure"in e,get:e=>e._highlightsExposure,set:(e,t)=>{e._highlightsExposure=t}},metadata:A},P,C),b(null,null,l,{kind:"field",name:"_midtonesHue",static:!1,private:!1,access:{has:e=>"_midtonesHue"in e,get:e=>e._midtonesHue,set:(e,t)=>{e._midtonesHue=t}},metadata:A},O,D),b(null,null,c,{kind:"field",name:"_midtonesDensity",static:!1,private:!1,access:{has:e=>"_midtonesDensity"in e,get:e=>e._midtonesDensity,set:(e,t)=>{e._midtonesDensity=t}},metadata:A},w,F),b(null,null,u,{kind:"field",name:"_midtonesSaturation",static:!1,private:!1,access:{has:e=>"_midtonesSaturation"in e,get:e=>e._midtonesSaturation,set:(e,t)=>{e._midtonesSaturation=t}},metadata:A},N,B),b(null,null,d,{kind:"field",name:"_midtonesExposure",static:!1,private:!1,access:{has:e=>"_midtonesExposure"in e,get:e=>e._midtonesExposure,set:(e,t)=>{e._midtonesExposure=t}},metadata:A},U,k),A&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:A})})(),e.PrepareUniforms=uo,e})(),po=!1;function fo(e){return $e.Parse(()=>new _o,e,null,null)}function go(e,t,s="vCameraColorCurvePositive",i="vCameraColorCurveNeutral",r="vCameraColorCurveNegative"){e._bind(t,s,i,r)}function mo(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&uo(e),t.DITHER&&e.push("ditherIntensity")}function To(e,t){t.COLORGRADING&&e.push("txColorTransform")}let Eo=(()=>{var e;let t,s,i,r,n,a,o,h,l,u,d,_,p,f,g,m,T,E,R,y,M,x,S,v,I,P=[],C=[],O=[],w=[],N=[],B=[],U=[],k=[],G=[],H=[],z=[],W=[],X=[],K=[],Y=[],j=[],q=[],$=[],Z=[],Q=[],J=[],ee=[],te=[],se=[],ie=[],re=[],ne=[],ae=[],oe=[],he=[],le=[],ce=[],ue=[],de=[],_e=[],pe=[],fe=[],ge=[],me=[],Te=[],Ee=[],Re=[],be=[],Ae=[],ye=[],Me=[],xe=[],Se=[],ve=[],Ie=[];return e=class{constructor(){this.colorCurves=A(this,P,new _o),this._colorCurvesEnabled=(A(this,C),A(this,O,!1)),this._colorGradingTexture=(A(this,w),A(this,N,void 0)),this._colorGradingEnabled=(A(this,B),A(this,U,!1)),this._colorGradingWithGreenDepth=(A(this,k),A(this,G,!0)),this._colorGradingBGR=(A(this,H),A(this,z,!0)),this._exposure=(A(this,W),A(this,X,1)),this._toneMappingEnabled=(A(this,K),A(this,Y,!1)),this._toneMappingType=(A(this,j),A(this,q,e.TONEMAPPING_STANDARD)),this._contrast=(A(this,$),A(this,Z,1)),this.vignetteStretch=(A(this,Q),A(this,J,0)),this.vignetteCenterX=(A(this,ee),A(this,te,0)),this.vignetteCenterY=(A(this,se),A(this,ie,0)),this.vignetteWeight=(A(this,re),A(this,ne,1.5)),this.vignetteColor=(A(this,ae),A(this,oe,new Ke(0,0,0,0))),this.vignetteCameraFov=(A(this,he),A(this,le,.5)),this._vignetteBlendMode=(A(this,ce),A(this,ue,e.VIGNETTEMODE_MULTIPLY)),this._vignetteEnabled=(A(this,de),A(this,_e,!1)),this._ditheringEnabled=(A(this,pe),A(this,fe,!1)),this._ditheringIntensity=(A(this,ge),A(this,me,1/255)),this._skipFinalColorClamp=(A(this,Te),A(this,Ee,!1)),this._applyByPostProcess=(A(this,Re),A(this,be,!1)),this._isEnabled=(A(this,Ae),A(this,ye,!0)),this.outputTextureWidth=(A(this,Me),A(this,xe,0)),this.outputTextureHeight=(A(this,Se),A(this,ve,0)),this.onUpdateParameters=(A(this,Ie),new c)}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(t,s=!1){if(s!==this.applyByPostProcess||!this._isEnabled)return t.VIGNETTE=!1,t.TONEMAPPING=0,t.CONTRAST=!1,t.EXPOSURE=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.DITHER=!1,t.IMAGEPROCESSING=!1,t.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,void(t.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);if(t.VIGNETTE=this.vignetteEnabled,t.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===e._VIGNETTEMODE_MULTIPLY,t.VIGNETTEBLENDMODEOPAQUE=!t.VIGNETTEBLENDMODEMULTIPLY,this._toneMappingEnabled)switch(this._toneMappingType){case e.TONEMAPPING_KHR_PBR_NEUTRAL:t.TONEMAPPING=3;break;case e.TONEMAPPING_ACES:t.TONEMAPPING=2;break;default:t.TONEMAPPING=1}else t.TONEMAPPING=0;t.CONTRAST=1!==this.contrast,t.EXPOSURE=1!==this.exposure,t.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,t.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,t.COLORGRADING?t.COLORGRADING3D=this.colorGradingTexture.is3D:t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,t.SAMPLER3DBGRMAP=this.colorGradingBGR,t.DITHER=this._ditheringEnabled,t.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,t.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,t.IMAGEPROCESSING=t.VIGNETTE||!!t.TONEMAPPING||t.CONTRAST||t.EXPOSURE||t.COLORCURVES||t.COLORGRADING||t.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&go(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const s=1/(this.outputTextureWidth||e.getEngine().getRenderWidth()),i=1/(this.outputTextureHeight||e.getEngine().getRenderHeight());if(e.setFloat2("vInverseScreenSize",s,i),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=null!=t?t:i/s;let n=Math.tan(.5*this.vignetteCameraFov),a=n*r;const o=Math.sqrt(a*n);a=Ps(a,o,this.vignetteStretch),n=Ps(n,o,this.vignetteStretch),e.setFloat4("vignetteSettings1",a,n,-a*this.vignetteCenterX,-n*this.vignetteCenterY);const h=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,h)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return $e.Clone(()=>new e,this)}serialize(){return $e.Serialize(this)}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}},(()=>{const c="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;var A;t=[D(7,A)],s=[L()],i=[F("colorGradingTexture")],r=[L()],n=[L()],a=[L()],o=[L()],h=[L()],l=[L()],u=[L()],d=[L()],_=[L()],p=[L()],f=[L()],g=[V()],m=[L()],T=[L()],E=[L()],R=[L()],y=[L()],M=[L()],x=[L()],S=[L()],v=[L()],I=[L()],b(null,null,t,{kind:"field",name:"colorCurves",static:!1,private:!1,access:{has:e=>"colorCurves"in e,get:e=>e.colorCurves,set:(e,t)=>{e.colorCurves=t}},metadata:c},P,C),b(null,null,s,{kind:"field",name:"_colorCurvesEnabled",static:!1,private:!1,access:{has:e=>"_colorCurvesEnabled"in e,get:e=>e._colorCurvesEnabled,set:(e,t)=>{e._colorCurvesEnabled=t}},metadata:c},O,w),b(null,null,i,{kind:"field",name:"_colorGradingTexture",static:!1,private:!1,access:{has:e=>"_colorGradingTexture"in e,get:e=>e._colorGradingTexture,set:(e,t)=>{e._colorGradingTexture=t}},metadata:c},N,B),b(null,null,r,{kind:"field",name:"_colorGradingEnabled",static:!1,private:!1,access:{has:e=>"_colorGradingEnabled"in e,get:e=>e._colorGradingEnabled,set:(e,t)=>{e._colorGradingEnabled=t}},metadata:c},U,k),b(null,null,n,{kind:"field",name:"_colorGradingWithGreenDepth",static:!1,private:!1,access:{has:e=>"_colorGradingWithGreenDepth"in e,get:e=>e._colorGradingWithGreenDepth,set:(e,t)=>{e._colorGradingWithGreenDepth=t}},metadata:c},G,H),b(null,null,a,{kind:"field",name:"_colorGradingBGR",static:!1,private:!1,access:{has:e=>"_colorGradingBGR"in e,get:e=>e._colorGradingBGR,set:(e,t)=>{e._colorGradingBGR=t}},metadata:c},z,W),b(null,null,o,{kind:"field",name:"_exposure",static:!1,private:!1,access:{has:e=>"_exposure"in e,get:e=>e._exposure,set:(e,t)=>{e._exposure=t}},metadata:c},X,K),b(null,null,h,{kind:"field",name:"_toneMappingEnabled",static:!1,private:!1,access:{has:e=>"_toneMappingEnabled"in e,get:e=>e._toneMappingEnabled,set:(e,t)=>{e._toneMappingEnabled=t}},metadata:c},Y,j),b(null,null,l,{kind:"field",name:"_toneMappingType",static:!1,private:!1,access:{has:e=>"_toneMappingType"in e,get:e=>e._toneMappingType,set:(e,t)=>{e._toneMappingType=t}},metadata:c},q,$),b(null,null,u,{kind:"field",name:"_contrast",static:!1,private:!1,access:{has:e=>"_contrast"in e,get:e=>e._contrast,set:(e,t)=>{e._contrast=t}},metadata:c},Z,Q),b(null,null,d,{kind:"field",name:"vignetteStretch",static:!1,private:!1,access:{has:e=>"vignetteStretch"in e,get:e=>e.vignetteStretch,set:(e,t)=>{e.vignetteStretch=t}},metadata:c},J,ee),b(null,null,_,{kind:"field",name:"vignetteCenterX",static:!1,private:!1,access:{has:e=>"vignetteCenterX"in e,get:e=>e.vignetteCenterX,set:(e,t)=>{e.vignetteCenterX=t}},metadata:c},te,se),b(null,null,p,{kind:"field",name:"vignetteCenterY",static:!1,private:!1,access:{has:e=>"vignetteCenterY"in e,get:e=>e.vignetteCenterY,set:(e,t)=>{e.vignetteCenterY=t}},metadata:c},ie,re),b(null,null,f,{kind:"field",name:"vignetteWeight",static:!1,private:!1,access:{has:e=>"vignetteWeight"in e,get:e=>e.vignetteWeight,set:(e,t)=>{e.vignetteWeight=t}},metadata:c},ne,ae),b(null,null,g,{kind:"field",name:"vignetteColor",static:!1,private:!1,access:{has:e=>"vignetteColor"in e,get:e=>e.vignetteColor,set:(e,t)=>{e.vignetteColor=t}},metadata:c},oe,he),b(null,null,m,{kind:"field",name:"vignetteCameraFov",static:!1,private:!1,access:{has:e=>"vignetteCameraFov"in e,get:e=>e.vignetteCameraFov,set:(e,t)=>{e.vignetteCameraFov=t}},metadata:c},le,ce),b(null,null,T,{kind:"field",name:"_vignetteBlendMode",static:!1,private:!1,access:{has:e=>"_vignetteBlendMode"in e,get:e=>e._vignetteBlendMode,set:(e,t)=>{e._vignetteBlendMode=t}},metadata:c},ue,de),b(null,null,E,{kind:"field",name:"_vignetteEnabled",static:!1,private:!1,access:{has:e=>"_vignetteEnabled"in e,get:e=>e._vignetteEnabled,set:(e,t)=>{e._vignetteEnabled=t}},metadata:c},_e,pe),b(null,null,R,{kind:"field",name:"_ditheringEnabled",static:!1,private:!1,access:{has:e=>"_ditheringEnabled"in e,get:e=>e._ditheringEnabled,set:(e,t)=>{e._ditheringEnabled=t}},metadata:c},fe,ge),b(null,null,y,{kind:"field",name:"_ditheringIntensity",static:!1,private:!1,access:{has:e=>"_ditheringIntensity"in e,get:e=>e._ditheringIntensity,set:(e,t)=>{e._ditheringIntensity=t}},metadata:c},me,Te),b(null,null,M,{kind:"field",name:"_skipFinalColorClamp",static:!1,private:!1,access:{has:e=>"_skipFinalColorClamp"in e,get:e=>e._skipFinalColorClamp,set:(e,t)=>{e._skipFinalColorClamp=t}},metadata:c},Ee,Re),b(null,null,x,{kind:"field",name:"_applyByPostProcess",static:!1,private:!1,access:{has:e=>"_applyByPostProcess"in e,get:e=>e._applyByPostProcess,set:(e,t)=>{e._applyByPostProcess=t}},metadata:c},be,Ae),b(null,null,S,{kind:"field",name:"_isEnabled",static:!1,private:!1,access:{has:e=>"_isEnabled"in e,get:e=>e._isEnabled,set:(e,t)=>{e._isEnabled=t}},metadata:c},ye,Me),b(null,null,v,{kind:"field",name:"outputTextureWidth",static:!1,private:!1,access:{has:e=>"outputTextureWidth"in e,get:e=>e.outputTextureWidth,set:(e,t)=>{e.outputTextureWidth=t}},metadata:c},xe,Se),b(null,null,I,{kind:"field",name:"outputTextureHeight",static:!1,private:!1,access:{has:e=>"outputTextureHeight"in e,get:e=>e.outputTextureHeight,set:(e,t)=>{e.outputTextureHeight=t}},metadata:c},ve,Ie),c&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:c})})(),e.TONEMAPPING_STANDARD=0,e.TONEMAPPING_ACES=1,e.TONEMAPPING_KHR_PBR_NEUTRAL=2,e.PrepareUniforms=mo,e.PrepareSamplers=To,e._VIGNETTEMODE_MULTIPLY=0,e._VIGNETTEMODE_OPAQUE=1,e})(),Ro=!1;function bo(e){const t=$e.Parse(()=>new Eo,e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}function Ao(){Ro||(Ro=!0,Eo.Parse=bo,$e._ImageProcessingConfigurationParser=bo,be("BABYLON.ImageProcessingConfiguration",Eo))}class yo{constructor(e,t,s,i,r,n){this.source=e,this.pointerX=t,this.pointerY=s,this.meshUnderPointer=i,this.sourceEvent=r,this.additionalData=n}static CreateNew(e,t,s){const i=e.getScene();return new yo(e,i.pointerX,i.pointerY,i.meshUnderPointer||e,t,s)}static CreateNewFromSprite(e,t,s,i){return new yo(e,t.pointerX,t.pointerY,t.meshUnderPointer,s,i)}static CreateNewFromScene(e,t){return new yo(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,s,i){return new yo(e,t.x,t.y,null,s,i)}}class Mo{constructor(e){this._vertexBuffers={},this._activePostProcesses=[],this.onBeforeRenderObservable=new c,this._scene=e}_prepareBuffers(){if(this._vertexBuffers[Gi.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[Gi.PositionKind]=new Gi(this._scene.getEngine(),e,Gi.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}_getActivePostProcesses(e){const t=this._activePostProcesses;t.length=0;for(let s=0;s<e.length;s++){const i=e[s];i&&t.push(i)}return t}_rebuild(){const e=this._vertexBuffers[Gi.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const s=this._scene.activeCamera;return!!s&&(!(!(t=t||this._getActivePostProcesses(s._postProcesses))||0===t.length||!this._scene.postProcessesEnabled)&&(t[0].activate(s,e,null!=t),!0))}directRender(e,t=null,s=!1,i=0,r=0,n=!1,a=e.length){const o=this._scene.getEngine();for(let h=0;h<a;h++){h<e.length-1?e[h+1].activate(this._scene.activeCamera||this._scene,t?.texture):(t?o.bindFramebuffer(t,i,void 0,void 0,s,r):n||o.restoreDefaultFramebuffer(),o._debugInsertMarker?.(`post process ${e[h].name} output`));const a=e[h],l=a.apply();l&&(a.onBeforeRenderObservable.notifyObservers(l),this._prepareBuffers(),o.bindBuffers(this._vertexBuffers,this._indexBuffer,l),o.drawElementsType(dt.MATERIAL_TriangleFillMode,0,6),a.onAfterRenderObservable.notifyObservers(l))}o.setDepthBuffer(!0),o.setDepthWrite(!0)}_finalizeFrame(e,t,s,i,r=!1){const n=this._scene.activeCamera;if(!n)return;if(this.onBeforeRenderObservable.notifyObservers(this),0===(i=i||this._getActivePostProcesses(n._postProcesses)).length||!this._scene.postProcessesEnabled)return;const a=this._scene.getEngine();for(let o=0,h=i.length;o<h;o++){const l=i[o];if(o<h-1?l._outputTexture=i[o+1].activate(n,t?.texture):(t?(a.bindFramebuffer(t,s,void 0,void 0,r),l._outputTexture=t):(a.restoreDefaultFramebuffer(),l._outputTexture=null),a._debugInsertMarker?.(`post process ${i[o].name} output`)),e)break;const c=l.apply();c&&(l.onBeforeRenderObservable.notifyObservers(c),this._prepareBuffers(),a.bindBuffers(this._vertexBuffers,this._indexBuffer,c),a.drawElementsType(dt.MATERIAL_TriangleFillMode,0,6),l.onAfterRenderObservable.notifyObservers(c))}a.setDepthBuffer(!0),a.setDepthWrite(!0),a.setAlphaMode(dt.ALPHA_DISABLE)}dispose(){const e=this._vertexBuffers[Gi.PositionKind];e&&(e.dispose(),this._vertexBuffers[Gi.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)}}class xo{set opaqueSortCompareFn(e){this._opaqueSortCompareFn=e||xo.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){this._alphaTestSortCompareFn=e||xo.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){this._transparentSortCompareFn=e||xo.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,s=null,i=null,r=null){this.index=e,this._opaqueSubMeshes=new Ws(256),this._transparentSubMeshes=new Ws(256),this._alphaTestSubMeshes=new Ws(256),this._depthOnlySubMeshes=new Ws(256),this._particleSystems=new Ws(256),this._spriteManagers=new Ws(256),this._empty=!0,this._edgesRenderers=new Xs(16),this.disableDepthPrePass=!1,this._scene=t,this.opaqueSortCompareFn=s,this.alphaTestSortCompareFn=i,this.transparentSortCompareFn=r}render(e,t,s,i,r=!0,n=!0,a=!0,o=!0,h){if(e)return void e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);const l=this._scene.getEngine();r&&0!==this._depthOnlySubMeshes.length&&(l.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),l.setColorWrite(!0)),n&&0!==this._opaqueSubMeshes.length&&this._renderOpaque(this._opaqueSubMeshes),a&&0!==this._alphaTestSubMeshes.length&&this._renderAlphaTest(this._alphaTestSubMeshes);const c=l.getStencilBuffer();if(l.setStencilBuffer(!1),t&&this._renderSprites(),s&&this._renderParticles(i),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),o&&(h||0!==this._transparentSubMeshes.length||this._scene.useOrderIndependentTransparency)){if(l.setStencilBuffer(c),h)h(this._transparentSubMeshes,this);else if(this._scene.useOrderIndependentTransparency){const e=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);e.length&&this._renderTransparent(e)}else this._renderTransparent(this._transparentSubMeshes);l.setAlphaMode(dt.ALPHA_DISABLE)}if(l.setStencilBuffer(!1),n&&this._edgesRenderers.length){for(let e=0;e<this._edgesRenderers.length;e++)this._edgesRenderers.data[e].render();l.setAlphaMode(dt.ALPHA_DISABLE)}l.setStencilBuffer(c)}_renderOpaqueSorted(e){xo._RenderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera,!1,this.disableDepthPrePass)}_renderAlphaTestSorted(e){xo._RenderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera,!1,this.disableDepthPrePass)}_renderTransparentSorted(e){xo._RenderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera,!0,this.disableDepthPrePass)}static _RenderSorted(e,t,s,i,r){let n,a=0;const o=s?s.globalPosition:xo._ZeroVector;if(i)for(;a<e.length;a++)n=e.data[a],n._alphaIndex=n.getMesh().alphaIndex,n._distanceToCamera=xe.Distance(n.getBoundingInfo().boundingSphere.centerWorld,o);const h=e.length===e.data.length?e.data:e.data.slice(0,e.length);t&&h.sort(t);const l=h[0].getMesh().getScene();for(a=0;a<h.length;a++)if(n=h[a],!l._activeMeshesFrozenButKeepClipping||n.isInFrustum(l._frustumPlanes)){if(i){const e=n.getMaterial();if(e&&e.needDepthPrePass&&!r){const t=e.getScene().getEngine();t.setColorWrite(!1),t.setAlphaMode(dt.ALPHA_DISABLE),n.render(!1),t.setColorWrite(!0)}}n.render(i)}}static defaultTransparentSortCompare(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:xo.backToFrontSortCompare(e,t)}static backToFrontSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0}static PainterSortCompare(e,t){const s=e.getMesh(),i=t.getMesh();return s.material&&i.material?s.material.uniqueId-i.material.uniqueId:s.uniqueId-i.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,s){void 0===t&&(t=e.getMesh()),void 0===s&&(s=e.getMaterial()),null!=s&&(s.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):s.needAlphaTestingForMesh(t)?(s.needDepthPrePass&&!this.disableDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(s.needDepthPrePass&&!this.disableDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t.isEnabled()&&t.isVisible&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(0===this._particleSystems.length)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let s=0;s<this._particleSystems.length;s++){const i=this._particleSystems.data[s];if(0===(t&&t.layerMask&i.layerMask))continue;const r=i.emitter;r.position&&e&&-1===e.indexOf(r)||this._scene._activeParticles.addCount(i.render(),!1)}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}_renderSprites(){if(!this._scene.spritesEnabled||0===this._spriteManagers.length)return;const e=this._scene.activeCamera;this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);for(let t=0;t<this._spriteManagers.length;t++){const s=this._spriteManagers.data[t];0!==(e&&e.layerMask&s.layerMask)&&s.render()}this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)}}xo._ZeroVector=xe.Zero();class So{}class vo{get disableDepthPrePass(){return this._disableDepthPrePass}set disableDepthPrePass(e){this._disableDepthPrePass=e;for(const t of this._renderingGroups)t.disableDepthPrePass=e}get maintainStateBetweenFrames(){return this._maintainStateBetweenFrames}set maintainStateBetweenFrames(e){e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,this._maintainStateBetweenFrames||this.restoreDispachedFlags())}restoreDispachedFlags(){for(const e of this._scene.meshes)if(e.subMeshes)for(const t of e.subMeshes)t._wasDispatched=!1;if(this._scene.spriteManagers)for(const e of this._scene.spriteManagers)e._wasDispatched=!1;for(const e of this._scene.particleSystems)e._wasDispatched=!1}constructor(e){this._useSceneAutoClearSetup=!1,this._disableDepthPrePass=!1,this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new So,this._maintainStateBetweenFrames=!1,this._scene=e;for(let e=vo.MIN_RENDERINGGROUPS;e<vo.MAX_RENDERINGGROUPS;e++)this._autoClearDepthStencil[e]={autoClear:!0,depth:!0,stencil:!0}}get renderingGroups(){return this._renderingGroups}getRenderingGroup(e){const t=e||0;return this._prepareRenderingGroup(t),this._renderingGroups[t]}_clearDepthStencilBuffer(e=!0,t=!0){this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(null,!1,e,t),this._depthStencilBufferAlreadyCleaned=!0)}render(e,t,s,i,r=!0,n=!0,a=!0,o=!0,h){const l=this._renderingGroupInfo;if(l.scene=this._scene,l.camera=this._scene.activeCamera,l.renderingManager=this,this._scene.spriteManagers&&i)for(let e=0;e<this._scene.spriteManagers.length;e++){const t=this._scene.spriteManagers[e];this.dispatchSprites(t)}for(let c=vo.MIN_RENDERINGGROUPS;c<vo.MAX_RENDERINGGROUPS;c++){this._depthStencilBufferAlreadyCleaned=c===vo.MIN_RENDERINGGROUPS;const u=this._renderingGroups[c];if(!u||u._empty)continue;const d=1<<c;if(l.renderingGroupId=c,this._scene.onBeforeRenderingGroupObservable.notifyObservers(l,d),vo.AUTOCLEAR){const e=this._useSceneAutoClearSetup?this._scene.getAutoClearDepthStencilSetup(c):this._autoClearDepthStencil[c];e&&e.autoClear&&this._clearDepthStencilBuffer(e.depth,e.stencil)}for(const e of this._scene._beforeRenderingGroupDrawStage)e.action(c);u.render(e,i,s,t,r,n,a,o,h);for(const e of this._scene._afterRenderingGroupDrawStage)e.action(c);this._scene.onAfterRenderingGroupObservable.notifyObservers(l,d)}}reset(){if(!this.maintainStateBetweenFrames)for(let e=vo.MIN_RENDERINGGROUPS;e<vo.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.prepare()}}resetSprites(){if(!this.maintainStateBetweenFrames)for(let e=vo.MIN_RENDERINGGROUPS;e<vo.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.prepareSprites()}}dispose(){this.freeRenderingGroups(),this._renderingGroups.length=0,this._renderingGroupInfo=null}freeRenderingGroups(){for(let e=vo.MIN_RENDERINGGROUPS;e<vo.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.dispose()}}_prepareRenderingGroup(e){void 0===this._renderingGroups[e]&&(this._renderingGroups[e]=new xo(e,this._scene,this._customOpaqueSortCompareFn[e],this._customAlphaTestSortCompareFn[e],this._customTransparentSortCompareFn[e]),this._renderingGroups[e].disableDepthPrePass=this._disableDepthPrePass)}dispatchSprites(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchSprites(e))}dispatchParticles(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchParticles(e))}dispatch(e,t,s){void 0===t&&(t=e.getMesh()),this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(t.renderingGroupId).dispatch(e,t,s))}setRenderingOrder(e,t=null,s=null,i=null){if(this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=s,this._customTransparentSortCompareFn[e]=i,this._renderingGroups[e]){const t=this._renderingGroups[e];t.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],t.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],t.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}}setRenderingAutoClearDepthStencil(e,t,s=!0,i=!0){this._autoClearDepthStencil[e]={autoClear:t,depth:s,stencil:i}}getAutoClearDepthStencilSetup(e){return this._autoClearDepthStencil[e]}}vo.MAX_RENDERINGGROUPS=4,vo.MIN_RENDERINGGROUPS=0,vo.AUTOCLEAR=!0;class Io{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1,this.disposeWhenUnowned=!0}static get HasTriggers(){for(const e in Io.Triggers)if(Object.prototype.hasOwnProperty.call(Io.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in Io.Triggers)if(Object.prototype.hasOwnProperty.call(Io.Triggers,e)){const t=parseInt(e);if(t>=dt.ACTION_OnPickTrigger&&t<=dt.ACTION_OnPickUpTrigger)return!0}return!1}static HasSpecificTrigger(e){for(const t in Io.Triggers)if(Object.prototype.hasOwnProperty.call(Io.Triggers,t)){if(parseInt(t)===e)return!0}return!1}}var Po,Co,Oo,Do,wo,Lo,Fo;Io.Triggers={},function(e){e[e.Generic=0]="Generic",e[e.Keyboard=1]="Keyboard",e[e.Mouse=2]="Mouse",e[e.Touch=3]="Touch",e[e.DualShock=4]="DualShock",e[e.Xbox=5]="Xbox",e[e.Switch=6]="Switch",e[e.DualSense=7]="DualSense"}(Po||(Po={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.Move=12]="Move"}(Co||(Co={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.DeltaHorizontal=10]="DeltaHorizontal",e[e.DeltaVertical=11]="DeltaVertical"}(Oo||(Oo={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(Do||(Do={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Create=8]="Create",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(wo||(wo={})),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.LT=6]="LT",e[e.RT=7]="RT",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.LStickXAxis=17]="LStickXAxis",e[e.LStickYAxis=18]="LStickYAxis",e[e.RStickXAxis=19]="RStickXAxis",e[e.RStickYAxis=20]="RStickYAxis"}(Lo||(Lo={})),function(e){e[e.B=0]="B",e[e.A=1]="A",e[e.Y=2]="Y",e[e.X=3]="X",e[e.L=4]="L",e[e.R=5]="R",e[e.ZL=6]="ZL",e[e.ZR=7]="ZR",e[e.Minus=8]="Minus",e[e.Plus=9]="Plus",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.Capture=17]="Capture",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(Fo||(Fo={}));class No{static CreateDeviceEvent(e,t,s,i,r,n,a){switch(e){case Po.Keyboard:return this._CreateKeyboardEvent(s,i,r,n);case Po.Mouse:if(s===Co.MouseWheelX||s===Co.MouseWheelY||s===Co.MouseWheelZ)return this._CreateWheelEvent(e,t,s,i,r,n);case Po.Touch:return this._CreatePointerEvent(e,t,s,i,r,n,a);default:throw`Unable to generate event for device ${Po[e]}`}}static _CreatePointerEvent(e,t,s,i,r,n,a){const o=this._CreateMouseEvent(e,t,s,i,r,n);e===Po.Mouse?(o.deviceType=Po.Mouse,o.pointerId=1,o.pointerType="mouse"):(o.deviceType=Po.Touch,o.pointerId=a??t,o.pointerType="touch");let h=0;return h+=r.pollInput(e,t,Co.LeftClick),h+=2*r.pollInput(e,t,Co.RightClick),h+=4*r.pollInput(e,t,Co.MiddleClick),o.buttons=h,s===Co.Move?o.type="pointermove":s>=Co.LeftClick&&s<=Co.RightClick&&(o.type=1===i?"pointerdown":"pointerup",o.button=s-2),o}static _CreateWheelEvent(e,t,s,i,r,n){const a=this._CreateMouseEvent(e,t,s,i,r,n);switch(a.pointerId=1,a.type="wheel",a.deltaMode=qa.DOM_DELTA_PIXEL,a.deltaX=0,a.deltaY=0,a.deltaZ=0,s){case Co.MouseWheelX:a.deltaX=i;break;case Co.MouseWheelY:a.deltaY=i;break;case Co.MouseWheelZ:a.deltaZ=i}return a}static _CreateMouseEvent(e,t,s,i,r,n){const a=this._CreateEvent(n),o=r.pollInput(e,t,Co.Horizontal),h=r.pollInput(e,t,Co.Vertical);return n?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-n.getBoundingClientRect().x,a.offsetY=a.movementY-n.getBoundingClientRect().y):(a.movementX=r.pollInput(e,t,10),a.movementY=r.pollInput(e,t,11),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,r),a.clientX=o,a.clientY=h,a.x=o,a.y=h,a.deviceType=e,a.deviceSlot=t,a.inputIndex=s,a}static _CreateKeyboardEvent(e,t,s,i){const r=this._CreateEvent(i);return this._CheckNonCharacterKeys(r,s),r.deviceType=Po.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=1===t?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const s=t.isDeviceAvailable(Po.Keyboard),i=s&&1===t.pollInput(Po.Keyboard,0,dt.INPUT_ALT_KEY),r=s&&1===t.pollInput(Po.Keyboard,0,dt.INPUT_CTRL_KEY),n=s&&(1===t.pollInput(Po.Keyboard,0,dt.INPUT_META_KEY1)||1===t.pollInput(Po.Keyboard,0,dt.INPUT_META_KEY2)||1===t.pollInput(Po.Keyboard,0,dt.INPUT_META_KEY3)),a=s&&1===t.pollInput(Po.Keyboard,0,dt.INPUT_SHIFT_KEY);e.altKey=i,e.ctrlKey=r,e.metaKey=n,e.shiftKey=a}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class Bo{constructor(e,t,s){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(e,t,i,r)=>{const n=No.CreateDeviceEvent(e,t,i,r,this);s(e,t,n)}):this._createDummyNativeInput()}pollInput(e,t,s){return this._nativeInput.pollInput(e,t,s)}isDeviceAvailable(e){return e===Po.Mouse||e===Po.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const Uo=Object.keys(Co).length/2;class ko{constructor(e,t,s,i){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Fs.IsSafari(),this._usingMacOs=et()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=e=>{},this._keyboardUpEvent=e=>{},this._keyboardBlurEvent=e=>{},this._pointerMoveEvent=e=>{},this._pointerDownEvent=e=>{},this._pointerUpEvent=e=>{},this._pointerCancelEvent=e=>{},this._pointerCancelTouch=e=>{},this._pointerLeaveEvent=e=>{},this._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._pointerMacOsChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=et()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=et()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=Fs.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=s,this._onInputChanged=i,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOs&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,s){const i=this._inputs[e][t];if(!i)throw`Unable to find device ${Po[e]}`;e>=Po.DualShock&&e<=Po.DualSense&&this._updateDevice(e,t,s);const r=i[s];if(void 0===r)throw`Unable to find input ${s} for device ${Po[e]} in slot ${t}`;return s===Co.Move&&Fs.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this?._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const s=e[+t];if(s)for(let e=0;e<s.length;e++)s[e]=0}this._elementToAttachTo=e,this._elementToAttachTo.tabIndex=-1!==this._elementToAttachTo.tabIndex?this._elementToAttachTo.tabIndex:this._engine.canvasTabIndex,this._handleKeyActions(),this._handlePointerActions(),this._handleGamepadActions(),this._eventsAttached=!0,this._checkForConnectedDevices()}}_disableEvents(){this._elementToAttachTo&&(this._elementToAttachTo.removeEventListener("blur",this._keyboardBlurEvent),this._elementToAttachTo.removeEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.removeEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.removeEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"leave",this._pointerLeaveEvent),this._elementToAttachTo.removeEventListener(this._wheelEventName,this._pointerWheelEvent),this._usingMacOs&&this._isUsingChromium&&this._elementToAttachTo.removeEventListener("lostpointercapture",this._pointerMacOsChromeOutEvent),window.removeEventListener("gamepadconnected",this._gamepadConnectedEvent),window.removeEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)),this._pointerInputClearObserver&&this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver),this._eventsAttached=!1}_checkForConnectedDevices(){if(navigator.getGamepads){const e=navigator.getGamepads();for(const t of e)t&&this._addGamePad(t)}"function"==typeof matchMedia&&matchMedia("(pointer:fine)").matches&&this._addPointerDevice(Po.Mouse,0,0,0)}_addGamePad(e){const t=this._getGamepadDeviceType(e.id),s=e.index;this._gamepads=this._gamepads||new Array(e.index+1),this._registerDevice(t,s,e.buttons.length+e.axes.length),this._gamepads[s]=t}_addPointerDevice(e,t,s,i){this._pointerActive||(this._pointerActive=!0),this._registerDevice(e,t,Uo);const r=this._inputs[e][t];r[0]=s,r[1]=i}_registerDevice(e,t,s){if(void 0===t)throw`Unable to register device ${Po[e]} to undefined slot.`;if(this._inputs[e]||(this._inputs[e]={}),!this._inputs[e][t]){const i=new Array(s);i.fill(0),this._inputs[e][t]=i,this._onDeviceConnected(e,t)}}_unregisterDevice(e,t){this._inputs[e][t]&&(delete this._inputs[e][t],this._onDeviceDisconnected(e,t))}_handleKeyActions(){this._keyboardDownEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Po.Keyboard,0,255));const t=this._inputs[Po.Keyboard][0];if(t){t[e.keyCode]=1;const s=e;s.inputIndex=e.keyCode,this._usingMacOs&&e.metaKey&&"Meta"!==e.key&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(Po.Keyboard,0,s)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Po.Keyboard,0,255));const t=this._inputs[Po.Keyboard][0];if(t){t[e.keyCode]=0;const s=e;if(s.inputIndex=e.keyCode,this._usingMacOs&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const s=No.CreateDeviceEvent(Po.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(Po.Keyboard,0,s)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(Po.Keyboard,0,s)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[Po.Keyboard][0];for(let t=0;t<e.length;t++)if(0!==e[t]){e[t]=0;const s=No.CreateDeviceEvent(Po.Keyboard,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Po.Keyboard,0,s)}this._usingMacOs&&this._metaKeys.splice(0,this._metaKeys.length)}},this._elementToAttachTo.addEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.addEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.addEventListener("blur",this._keyboardBlurEvent)}_handlePointerActions(){this._maxTouchPoints=et()&&navigator.maxTouchPoints||2,this._activeTouchIds||(this._activeTouchIds=new Array(this._maxTouchPoints));for(let e=0;e<this._maxTouchPoints;e++)this._activeTouchIds[e]=-1;this._pointerMoveEvent=e=>{const t=this._getPointerType(e);let s=t===Po.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===Po.Touch&&-1===s){if(0===e.buttons)return;const i=this._activeTouchIds.indexOf(-1);if(!(i>=0))return void Fs.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);s=i,this._activeTouchIds[i]=e.pointerId,this._onDeviceConnected(t,s)}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][s]||this._addPointerDevice(t,s,e.clientX,e.clientY);const i=this._inputs[t][s];if(i){const r=e;r.inputIndex=Co.Move,i[Co.Horizontal]=e.clientX,i[Co.Vertical]=e.clientY,t===Po.Touch&&0===i[Co.LeftClick]&&(i[Co.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,s,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,i[e.button+2]=i[e.button+2]?0:1,this._onInputChanged(t,s,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let s=t===Po.Mouse?0:e.pointerId;if(t===Po.Touch){let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t&&(t=this._activeTouchIds.indexOf(-1)),!(t>=0))return void Fs.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);s=t,this._activeTouchIds[t]=e.pointerId}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][s]?t===Po.Touch&&this._onDeviceConnected(t,s):this._addPointerDevice(t,s,e.clientX,e.clientY);const i=this._inputs[t][s];if(i){const r=i[Co.Horizontal],n=i[Co.Vertical];if(t===Po.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}i[Co.Horizontal]=e.clientX,i[Co.Vertical]=e.clientY,i[e.button+2]=1;const a=e;a.inputIndex=e.button+2,this._onInputChanged(t,s,a),r===e.clientX&&n===e.clientY||(a.inputIndex=Co.Move,this._onInputChanged(t,s,a))}},this._pointerUpEvent=e=>{const t=this._getPointerType(e),s=t===Po.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===Po.Touch){if(-1===s)return;this._activeTouchIds[s]=-1}const i=this._inputs[t]?.[s];let r=e.button,n=i&&0!==i[r+2];if(!n&&this._isUsingFirefox&&this._usingMacOs&&i&&(r=2===r?0:2,n=0!==i[r+2]),n){const n=i[Co.Horizontal],a=i[Co.Vertical];i[Co.Horizontal]=e.clientX,i[Co.Vertical]=e.clientY,i[r+2]=0;const o=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),n===e.clientX&&a===e.clientY||(o.inputIndex=Co.Move,this._onInputChanged(t,s,o)),o.inputIndex=r+2,t===Po.Mouse&&this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(t,s,o),t===Po.Touch&&this._onDeviceDisconnected(t,s)}},this._pointerCancelTouch=e=>{const t=this._activeTouchIds.indexOf(e);if(-1===t)return;this._elementToAttachTo.hasPointerCapture?.(e)&&this._elementToAttachTo.releasePointerCapture(e),this._inputs[Po.Touch][t][Co.LeftClick]=0;const s=No.CreateDeviceEvent(Po.Touch,t,Co.LeftClick,0,this,this._elementToAttachTo,e);this._onInputChanged(Po.Touch,t,s),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(Po.Touch,t)},this._pointerCancelEvent=e=>{if("mouse"===e.pointerType){const e=this._inputs[Po.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=Co.LeftClick;t<=Co.BrowserForward;t++)if(1===e[t]){e[t]=0;const s=No.CreateDeviceEvent(Po.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Po.Mouse,0,s)}}else this._pointerCancelTouch(e.pointerId)},this._pointerLeaveEvent=e=>{"pen"===e.pointerType&&this._pointerCancelTouch(e.pointerId)},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1;const t=function(){};try{const s=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,s),this._elementToAttachTo.removeEventListener("test",t,s)}catch(e){}this._pointerBlurEvent=()=>{if(this.isDeviceAvailable(Po.Mouse)){const e=this._inputs[Po.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=Co.LeftClick;t<=Co.BrowserForward;t++)if(1===e[t]){e[t]=0;const s=No.CreateDeviceEvent(Po.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Po.Mouse,0,s)}}if(this.isDeviceAvailable(Po.Touch)){const e=this._inputs[Po.Touch];for(let t=0;t<this._activeTouchIds.length;t++){const s=this._activeTouchIds[t];if(this._elementToAttachTo.hasPointerCapture?.(s)&&this._elementToAttachTo.releasePointerCapture(s),-1!==s&&1===e[t]?.[Co.LeftClick]){e[t][Co.LeftClick]=0;const i=No.CreateDeviceEvent(Po.Touch,t,Co.LeftClick,0,this,this._elementToAttachTo,s);this._onInputChanged(Po.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(Po.Touch,t)}}}},this._pointerWheelEvent=e=>{const t=Po.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,Uo));const s=this._inputs[t][0];if(s){s[Co.MouseWheelX]=e.deltaX||0,s[Co.MouseWheelY]=e.deltaY||e.wheelDelta||0,s[Co.MouseWheelZ]=e.deltaZ||0;const i=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==s[Co.MouseWheelX]&&(i.inputIndex=Co.MouseWheelX,this._onInputChanged(t,0,i)),0!==s[Co.MouseWheelY]&&(i.inputIndex=Co.MouseWheelY,this._onInputChanged(t,0,i)),0!==s[Co.MouseWheelZ]&&(i.inputIndex=Co.MouseWheelZ,this._onInputChanged(t,0,i))}},this._usingMacOs&&this._isUsingChromium&&(this._pointerMacOsChromeOutEvent=e=>{e.buttons>1&&this._pointerCancelEvent(e)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOsChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"leave",this._pointerLeaveEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,!!e&&{passive:!1}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add(()=>{if(this.isDeviceAvailable(Po.Mouse)){const e=this._inputs[Po.Mouse][0];e[Co.MouseWheelX]=0,e[Co.MouseWheelY]=0,e[Co.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),s=e.gamepad.index;this._unregisterDevice(t,s),delete this._gamepads[s]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,s){const i=navigator.getGamepads()[t];if(i&&e===this._gamepads[t]){const r=this._inputs[e][t];s>=i.buttons.length?r[s]=i.axes[s-i.buttons.length].valueOf():r[s]=i.buttons[s].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?Po.DualSense:Po.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")||-1!==e.indexOf("045e")&&-1===e.indexOf("Surface Dock")?Po.Xbox:-1!==e.indexOf("057e")?Po.Switch:Po.Generic}_getPointerType(e){let t=Po.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=Po.Touch),t}}class Go{constructor(e,t,s=0){this.deviceType=t,this.deviceSlot=s,this.onInputChangedObservable=new c,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class Vo{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t<this._devices.length;t++){const s=this._devices[t];for(const i in s){const s=+i;e._addDevice(new Go(this._deviceInputSystem,t,s))}}this._registeredManagers.push(e)},this.unregisterManager=e=>{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(Po).length/2;this._devices=new Array(t);const s=(e,t)=>{this._devices[e]||(this._devices[e]=new Array),this._devices[e][t]||(this._devices[e][t]=t);for(const s of this._registeredManagers){const i=new Go(this._deviceInputSystem,e,t);s._addDevice(i)}},i=(e,t)=>{this._devices[e]?.[t]&&delete this._devices[e][t];for(const s of this._registeredManagers)s._removeDevice(e,t)},r=(e,t,s)=>{if(s)for(const i of this._registeredManagers)i._onInputChanged(e,t,s)};"undefined"!=typeof _native?this._deviceInputSystem=new Bo(s,i,r):this._deviceInputSystem=new ko(e,s,i,r)}dispose(){this._deviceInputSystem.dispose()}}class Ho{getDeviceSource(e,t){if(void 0===t){if(void 0===this._firstDevice[e])return null;t=this._firstDevice[e]}return this._devices[e]&&void 0!==this._devices[e][t]?this._devices[e][t]:null}getDeviceSources(e){return this._devices[e]?this._devices[e].filter(e=>!!e):[]}constructor(e){const t=Object.keys(Po).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new Vo(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new c(e=>{for(const t of this._devices)if(t)for(const s of t)s&&this.onDeviceConnectedObservable.notifyObserver(e,s)}),this.onDeviceDisconnectedObservable=new c,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=[]),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){const s=this._devices[e]?.[t];this.onDeviceDisconnectedObservable.notifyObservers(s),this._devices[e]?.[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,s){this._devices[e]?.[t]?.onInputChangedObservable.notifyObservers(s)}_updateFirstDevices(e){switch(e){case Po.Keyboard:case Po.Mouse:this._firstDevice[e]=0;break;case Po.Touch:case Po.DualSense:case Po.DualShock:case Po.Xbox:case Po.Switch:case Po.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let s=0;s<t.length;s++)if(t[s]){this._firstDevice[e]=s;break}break}}}}class zo{}zo._IsPickingAvailable=!1;class Wo{constructor(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}get singleClick(){return this._singleClick}get doubleClick(){return this._doubleClick}get hasSwiped(){return this._hasSwiped}get ignore(){return this._ignore}set singleClick(e){this._singleClick=e}set doubleClick(e){this._doubleClick=e}set hasSwiped(e){this._hasSwiped=e}set ignore(e){this._ignore=e}}class Xo{constructor(e){this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._activePointerIds=new Array,this._activePointerIdsCount=0,this._doubleClickOccured=!1,this._isSwiping=!1,this._swipeButtonPressed=-1,this._skipPointerTap=!1,this._isMultiTouchGesture=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new Me(0,0),this._previousStartingPointerPosition=new Me(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._movePointerInfo=null,this._cameraObserverCount=0,this._delayedClicks=[null,null,null,null,null],this._deviceSourceManager=null,this._scene=e||ee.LastCreatedScene,this._scene}get meshUnderPointer(){return this._movePointerInfo&&(this._movePointerInfo._generatePickInfo(),this._movePointerInfo=null),this._pointerOverMesh}getMeshUnderPointerByPointerId(e){return this._meshUnderPointerId[e]||null}get unTranslatedPointer(){return new Me(this._unTranslatedPointerX,this._unTranslatedPointerY)}get pointerX(){return this._pointerX}set pointerX(e){this._pointerX=e}get pointerY(){return this._pointerY}set pointerY(e){this._pointerY=e}_updatePointerPosition(e){const t=this._scene.getEngine().getInputElementClientRect();t&&(this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)}_processPointerMove(e,t){const s=this._scene,i=s.getEngine(),r=i.getInputElement();r&&(r.tabIndex=i.canvasTabIndex,s.doNotHandleCursors||(r.style.cursor=s.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,s);for(const i of s._pointerMoveStage){e=e||this._pickMove(t);const s=!!e?.pickedMesh;e=i.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,s,r)}const n=t.inputIndex>=Co.MouseWheelX&&t.inputIndex<=Co.MouseWheelZ?Yn.POINTERWHEEL:Yn.POINTERMOVE;let a;s.onPointerMove&&(e=e||this._pickMove(t),s.onPointerMove(t,e,n)),e?(a=new $n(n,t,e),this._setRayOnPointerInfo(e,t)):(a=new $n(n,t,null,this),this._movePointerInfo=a),s.onPointerObservable.hasObservers()&&s.onPointerObservable.notifyObservers(a,n)}_setRayOnPointerInfo(e,t){const s=this._scene;e&&zo._IsPickingAvailable&&(e.ray||(e.ray=s.createPickingRay(t.offsetX,t.offsetY,Ie.Identity(),s.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,s){const i=this._scene,r=new qn(s,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(r.nearInteractionPickingInfo=e)),i.onPrePointerObservable.notifyObservers(r,s),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,s=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(s,e,t),s}_setCursorAndPointerOverMesh(e,t,s){const i=s.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!s.doNotHandleCursors&&i&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(i.style.cursor=e.hoverCursor||s.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const s=new PointerEvent("pointermove",t);s.inputIndex=Co.Move,this._checkPrePointerObservable(e,s,Yn.POINTERMOVE)||this._processPointerMove(e,s)}simulatePointerDown(e,t){const s=new PointerEvent("pointerdown",t);s.inputIndex=s.button+2,this._checkPrePointerObservable(e,s,Yn.POINTERDOWN)||this._processPointerDown(e,s)}_processPointerDown(e,t){const s=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const i=e.pickedMesh._getActionManagerForTrigger();if(i){if(i.hasPickTriggers)switch(i.processTrigger(dt.ACTION_OnPickDownTrigger,new yo(e.pickedMesh,s.pointerX,s.pointerY,e.pickedMesh,t,e)),t.button){case 0:i.processTrigger(dt.ACTION_OnLeftPickTrigger,new yo(e.pickedMesh,s.pointerX,s.pointerY,e.pickedMesh,t,e));break;case 1:i.processTrigger(dt.ACTION_OnCenterPickTrigger,new yo(e.pickedMesh,s.pointerX,s.pointerY,e.pickedMesh,t,e));break;case 2:i.processTrigger(dt.ACTION_OnRightPickTrigger,new yo(e.pickedMesh,s.pointerX,s.pointerY,e.pickedMesh,t,e))}i.hasSpecificTrigger(dt.ACTION_OnLongPressTrigger)&&window.setTimeout(()=>{const e=s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(dt.ACTION_OnLongPressTrigger)&&e===this._pickedDownMesh,!1,s.cameraToUseForPointers);e?.pickedMesh&&i&&0!==this._activePointerIdsCount&&Date.now()-this._startingPointerTime>Xo.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,i.processTrigger(dt.ACTION_OnLongPressTrigger,yo.CreateNew(e.pickedMesh,t)))},Xo.LongPressDelay)}}else for(const i of s._pointerDownStage)e=i.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let i;const r=Yn.POINTERDOWN;e?(s.onPointerDown&&s.onPointerDown(t,e,r),i=new $n(r,t,e),this._setRayOnPointerInfo(e,t)):i=new $n(r,t,null,this),s.onPointerObservable.hasObservers()&&s.onPointerObservable.notifyObservers(i,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,s){const i=new PointerEvent("pointerup",t);i.inputIndex=Co.Move;const r=new Wo;s?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,i,Yn.POINTERUP)||this._processPointerUp(e,i,r)}_processPointerUp(e,t,s){const i=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(i.onPointerPick&&i.onPointerPick(t,e),s.singleClick&&!s.ignore&&i.onPointerObservable.observers.length>this._cameraObserverCount)){const s=Yn.POINTERPICK,r=new $n(s,t,e);this._setRayOnPointerInfo(e,t),i.onPointerObservable.notifyObservers(r,s)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!s.ignore){r.processTrigger(dt.ACTION_OnPickUpTrigger,yo.CreateNew(e.pickedMesh,t,e)),!s.hasSwiped&&s.singleClick&&r.processTrigger(dt.ACTION_OnPickTrigger,yo.CreateNew(e.pickedMesh,t,e));const i=e.pickedMesh._getActionManagerForTrigger(dt.ACTION_OnDoublePickTrigger);s.doubleClick&&i&&i.processTrigger(dt.ACTION_OnDoublePickTrigger,yo.CreateNew(e.pickedMesh,t,e))}}else if(!s.ignore)for(const r of i._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,s.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(dt.ACTION_OnPickOutTrigger);e&&e.processTrigger(dt.ACTION_OnPickOutTrigger,yo.CreateNew(this._pickedDownMesh,t))}if(!s.ignore){const r=new $n(Yn.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),i.onPointerObservable.notifyObservers(r,Yn.POINTERUP),i.onPointerUp&&i.onPointerUp(t,e,Yn.POINTERUP),!s.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(s.singleClick?r=Yn.POINTERTAP:s.doubleClick&&(r=Yn.POINTERDOUBLETAP),r){const s=new $n(r,t,e);i.onPointerObservable.hasObservers()&&i.onPointerObservable.hasSpecificMask(r)&&i.onPointerObservable.notifyObservers(s,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,s=!0,i=null){const r=this._scene,n=r.getEngine();i||(i=n.getInputElement()),this._alreadyAttached&&this.detachControl(),i&&(this._alreadyAttachedTo=i),this._deviceSourceManager=new Ho(n),this._initActionManager=e=>{if(!this._meshPickProceed){const t=r.skipPointerUpPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers,r.pointerUpTrianglePredicate);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,s)=>{if((Date.now()-this._previousStartingPointerTime>Xo.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){const t=this._delayedClicks[e].evt,s=Yn.POINTERTAP,i=new $n(s,t,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(s)&&r.onPointerObservable.notifyObservers(i,s),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,s,i)=>{const r=new Wo;this._currentPickResult=null;let n=null,a=e.hasSpecificMask(Yn.POINTERPICK)||t.hasSpecificMask(Yn.POINTERPICK)||e.hasSpecificMask(Yn.POINTERTAP)||t.hasSpecificMask(Yn.POINTERTAP)||e.hasSpecificMask(Yn.POINTERDOUBLETAP)||t.hasSpecificMask(Yn.POINTERDOUBLETAP);!a&&Io&&(n=this._initActionManager(n,r),n&&(a=n.hasPickTriggers));let o=!1;if(a=a&&!this._isMultiTouchGesture,a){const a=s.button;if(r.hasSwiped=this._isPointerSwiping(),!r.hasSwiped){let h=!Xo.ExclusiveDoubleClickMode;if(h||(h=!e.hasSpecificMask(Yn.POINTERDOUBLETAP)&&!t.hasSpecificMask(Yn.POINTERDOUBLETAP),h&&!Io.HasSpecificTrigger(dt.ACTION_OnDoublePickTrigger)&&(n=this._initActionManager(n,r),n&&(h=!n.hasSpecificTrigger(dt.ACTION_OnDoublePickTrigger)))),h)(Date.now()-this._previousStartingPointerTime>Xo.DoubleClickDelay||a!==this._previousButtonPressed)&&(r.singleClick=!0,i(r,this._currentPickResult),o=!0);else{const e={evt:s,clickInfo:r,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,a,r,i),Xo.DoubleClickDelay)};this._delayedClicks[a]=e}let l=e.hasSpecificMask(Yn.POINTERDOUBLETAP)||t.hasSpecificMask(Yn.POINTERDOUBLETAP);!l&&Io.HasSpecificTrigger(dt.ACTION_OnDoublePickTrigger)&&(n=this._initActionManager(n,r),n&&(l=n.hasSpecificTrigger(dt.ACTION_OnDoublePickTrigger))),l&&(a===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime<Xo.DoubleClickDelay&&!this._doubleClickOccured?(r.hasSwiped||this._isPointerSwiping()?(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=a,Xo.ExclusiveDoubleClickMode?(this._delayedClicks[a]&&(clearTimeout(this._delayedClicks[a]?.timeoutId),this._delayedClicks[a]=null),i(r,this._previousPickResult)):i(r,this._currentPickResult)):(this._previousStartingPointerTime=0,this._doubleClickOccured=!0,r.doubleClick=!0,r.ignore=!1,Xo.ExclusiveDoubleClickMode&&this._delayedClicks[a]&&(clearTimeout(this._delayedClicks[a]?.timeoutId),this._delayedClicks[a]=null),i(r,this._currentPickResult)),o=!0):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=a))}}o||i(r,this._currentPickResult)},this._onPointerMove=e=>{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>Xo.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>Xo.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=Co.MouseWheelX&&e.inputIndex<=Co.MouseWheelZ?Yn.POINTERWHEEL:Yn.POINTERMOVE))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking)return void this._processPointerMove(new ur,e);r.pointerMovePredicate||(r.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!r.cameraToUseForPointers||0!==(r.cameraToUseForPointers.layerMask&e.layerMask)));const t=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{const t=this._activePointerIds.indexOf(-1);if(-1===t?this._activePointerIds.push(e.pointerId):this._activePointerIds[t]=e.pointerId,this._activePointerIdsCount++,this._pickedDownMesh=null,this._meshPickProceed=!1,Xo.ExclusiveDoubleClickMode)for(let t=0;t<this._delayedClicks.length;t++)if(this._delayedClicks[t])if(e.button===t)clearTimeout(this._delayedClicks[t]?.timeoutId);else{const e=this._delayedClicks[t].clickInfo;this._doubleClickOccured=!1,e.singleClick=!0,e.ignore=!1;const s=this._delayedClicks[t].evt,i=Yn.POINTERTAP,n=new $n(i,s,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(i)&&r.onPointerObservable.notifyObservers(n,i),this._delayedClicks[t]=null}if(this._updatePointerPosition(e),-1===this._swipeButtonPressed&&(this._swipeButtonPressed=e.button),r.preventDefaultOnPointerDown&&i&&(e.preventDefault(),i.focus()),this._startingPointerPosition.x=this._pointerX,this._startingPointerPosition.y=this._pointerY,this._startingPointerTime=Date.now(),this._checkPrePointerObservable(null,e,Yn.POINTERDOWN))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;let s;this._pointerCaptures[e.pointerId]=!0,r.pointerDownPredicate||(r.pointerDownPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||0!==(r.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,s=r.skipPointerDownPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerDown?new ur:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers,r.pointerDownTrianglePredicate),this._processPointerDown(s,e)},this._onPointerUp=e=>{const t=this._activePointerIds.indexOf(e.pointerId);-1!==t&&(this._activePointerIds[t]=-1,this._activePointerIdsCount--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),r.preventDefaultOnPointerUp&&i&&(e.preventDefault(),i.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,e,(t,s)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,Yn.POINTERUP))return this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),void(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1));t.hasSwiped||(t.singleClick&&r.onPrePointerObservable.hasSpecificMask(Yn.POINTERTAP)&&this._checkPrePointerObservable(null,e,Yn.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&r.onPrePointerObservable.hasSpecificMask(Yn.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,Yn.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(r.cameraToUseForPointers||r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||0!==(r.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(Io&&Io.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,t),s||(s=this._currentPickResult),this._processPointerUp(s,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))):this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1)}))},this._onKeyDown=e=>{const t=Wa.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const s=new Ka(t,e);if(r.onPreKeyboardObservable.notifyObservers(s,t),s.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const s=new Xa(t,e);r.onKeyboardObservable.notifyObservers(s,t)}r.actionManager&&r.actionManager.processTrigger(dt.ACTION_OnKeyDownTrigger,yo.CreateNewFromScene(r,e))},this._onKeyUp=e=>{const t=Wa.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const s=new Ka(t,e);if(r.onPreKeyboardObservable.notifyObservers(s,t),s.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const s=new Xa(t,e);r.onKeyboardObservable.notifyObservers(s,t)}r.actionManager&&r.actionManager.processTrigger(dt.ACTION_OnKeyUpTrigger,yo.CreateNewFromScene(r,e))},this._deviceSourceManager.onDeviceConnectedObservable.add(i=>{i.deviceType===Po.Mouse?i.onInputChangedObservable.add(r=>{this._originMouseEvent=r,r.inputIndex===Co.LeftClick||r.inputIndex===Co.MiddleClick||r.inputIndex===Co.RightClick||r.inputIndex===Co.BrowserBack||r.inputIndex===Co.BrowserForward?t&&1===i.getInput(r.inputIndex)?this._onPointerDown(r):e&&0===i.getInput(r.inputIndex)&&this._onPointerUp(r):s&&(r.inputIndex===Co.Move?this._onPointerMove(r):r.inputIndex!==Co.MouseWheelX&&r.inputIndex!==Co.MouseWheelY&&r.inputIndex!==Co.MouseWheelZ||this._onPointerMove(r))}):i.deviceType===Po.Touch?i.onInputChangedObservable.add(r=>{r.inputIndex===Co.LeftClick&&(t&&1===i.getInput(r.inputIndex)?(this._onPointerDown(r),this._activePointerIdsCount>1&&(this._isMultiTouchGesture=!0)):e&&0===i.getInput(r.inputIndex)&&(this._onPointerUp(r),0===this._activePointerIdsCount&&(this._isMultiTouchGesture=!1))),s&&r.inputIndex===Co.Move&&this._onPointerMove(r)}):i.deviceType===Po.Keyboard&&i.onInputChangedObservable.add(e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)})}),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,s,i){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(dt.ACTION_OnPointerOutTrigger),n&&n.processTrigger(dt.ACTION_OnPointerOutTrigger,new yo(r,this._pointerX,this._pointerY,e,i,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(dt.ACTION_OnPointerOverTrigger),n&&n.processTrigger(dt.ACTION_OnPointerOverTrigger,new yo(e,this._pointerX,this._pointerY,e,i,{pointerId:t,pickResult:s}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null),this._scene.onMeshUnderPointerUpdatedObservable.hasObservers()&&this._scene.onMeshUnderPointerUpdatedObservable.notifyObservers({mesh:e,pointerId:t})}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}Xo.DragMovementThreshold=10,Xo.LongPressDelay=500,Xo.DoubleClickDelay=300,Xo.ExclusiveDoubleClickMode=!1;class Ko{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._hasResult=!1,this._hasCurrentValue=!1,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._hasCurrentValue=Ko.Enabled,this._lastSecValueCount++}addCount(e,t){Ko.Enabled&&(this._current+=e,this._hasCurrentValue=!0,t&&this._fetchResult())}beginMonitoring(){Ko.Enabled&&(this._startMonitoringTime=nt.Now)}endMonitoring(e=!0){if(!Ko.Enabled)return;e&&this.fetchNewFrame();const t=nt.Now;this._current=t-this._startMonitoringTime,this._hasCurrentValue=!0,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){if(!this._hasCurrentValue)return;this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._hasResult?(this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current)):(this._min=this._current,this._max=this._current,this._hasResult=!0),this._average=this._totalAccumulated/this._totalValueCount;const e=nt.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}Ko.Enabled=!0;class Yo{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}Yo._UniqueIdCounter=1;class jo{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}const qo=new Se,$o=new Se;var Zo;!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(Zo||(Zo={}));class Qo{static DefaultMaterialFactory(e){throw Le("StandardMaterial")}static CollisionCoordinatorFactory(){throw Le("DefaultCollisionCoordinator")}get clearColor(){return this._clearColor}set clearColor(e){e!==this._clearColor&&(this._clearColor=e,this.onClearColorChangedObservable.notifyObservers(this._clearColor))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case 0:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case 1:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case 2:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(dt.MATERIAL_MiscDirtyFlag))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(dt.MATERIAL_MiscDirtyFlag))}get forcePointsCloud(){return this._forcePointsCloud}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.onEnvironmentTextureChangedObservable.notifyObservers(e),this.markAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}getNodes(){let e=[];e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes);for(const t of this.skeletons)e=e.concat(t.bones);return e}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return Xo.DragMovementThreshold}static set DragMovementThreshold(e){Xo.DragMovementThreshold=e}static get LongPressDelay(){return Xo.LongPressDelay}static set LongPressDelay(e){Xo.LongPressDelay=e}static get DoubleClickDelay(){return Xo.DoubleClickDelay}static set DoubleClickDelay(e){Xo.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return Xo.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){Xo.ExclusiveDoubleClickMode=e}get _eyePosition(){return this._forcedViewPosition??this.activeCamera?.globalPosition??xe.ZeroReadOnly}bindEyePosition(e,t="vEyePosition",s=!1){const i=this._eyePosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition),n=this.floatingOriginOffset,a=qo.set(i.x,i.y,i.z,r?-1:1),o=a.subtractFromFloatsToRef(n.x,n.y,n.z,0,$o);return e&&(s?e.setFloat3(t,o.x,o.y,o.z):e.setVector4(t,o)),a}finalizeSceneUbo(){const e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null),s=this.floatingOriginOffset;return e.updateFloat4("vEyePosition",t.x-s.x,t.y-s.y,t.z-s.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(dt.MATERIAL_MiscDirtyFlag))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(dt.MATERIAL_MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(dt.MATERIAL_MiscDirtyFlag))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(dt.MATERIAL_LightDirtyFlag))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(dt.MATERIAL_LightDirtyFlag))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=Q(e,()=>{this.onActiveCamerasChanged.notifyObservers(this)})),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get _hasDefaultMaterial(){return Qo.DefaultMaterialFactory!==Qo._OriginalDefaultMaterialFactory}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=Qo.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag))}get texturesEnabled(){return this._texturesEnabled}get frameGraph(){return this._frameGraph}set frameGraph(e){if(this._frameGraph)return this._frameGraph=e,void(e||(this.customRenderFunction=this._currentCustomRenderFunction));this._frameGraph=e,e&&(this._currentCustomRenderFunction=this.customRenderFunction,this.customRenderFunction=this._renderWithFrameGraph,this.activeCamera=null)}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(dt.MATERIAL_AttributesDirtyFlag))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=Qo.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}get uniqueId(){return this._uniqueId}constructor(e,t){this._inputManager=new Xo(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this._clearColor=new Ke(.2,.2,.3,1),this.onClearColorChangedObservable=new c,this.ambientColor=new Xe(0,0,0),this.environmentIntensity=1,this.iblIntensity=1,this._performancePriority=0,this.onScenePerformancePriorityChangedObservable=new c,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.objectRenderers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[],this.effectLayers=[],this.sounds=null,this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new c,this._onDisposeObserver=null,this.onBeforeRenderObservable=new c,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new c,this.onAfterRenderCameraObservable=new c,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new c,this.onAfterAnimationsObservable=new c,this.onBeforeDrawPhaseObservable=new c,this.onAfterDrawPhaseObservable=new c,this.onReadyObservable=new c,this.onBeforeCameraRenderObservable=new c,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new c,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new c,this.onAfterActiveMeshesEvaluationObservable=new c,this.onBeforeParticlesRenderingObservable=new c,this.onAfterParticlesRenderingObservable=new c,this.onDataLoadedObservable=new c,this.onNewCameraAddedObservable=new c,this.onCameraRemovedObservable=new c,this.onNewLightAddedObservable=new c,this.onLightRemovedObservable=new c,this.onNewGeometryAddedObservable=new c,this.onGeometryRemovedObservable=new c,this.onNewTransformNodeAddedObservable=new c,this.onTransformNodeRemovedObservable=new c,this.onNewMeshAddedObservable=new c,this.onMeshRemovedObservable=new c,this.onNewSkeletonAddedObservable=new c,this.onSkeletonRemovedObservable=new c,this.onNewParticleSystemAddedObservable=new c,this.onParticleSystemRemovedObservable=new c,this.onNewAnimationGroupAddedObservable=new c,this.onAnimationGroupRemovedObservable=new c,this.onNewMaterialAddedObservable=new c,this.onNewMultiMaterialAddedObservable=new c,this.onMaterialRemovedObservable=new c,this.onMultiMaterialRemovedObservable=new c,this.onNewTextureAddedObservable=new c,this.onTextureRemovedObservable=new c,this.onNewFrameGraphAddedObservable=new c,this.onFrameGraphRemovedObservable=new c,this.onNewObjectRendererAddedObservable=new c,this.onObjectRendererRemovedObservable=new c,this.onNewPostProcessAddedObservable=new c,this.onPostProcessRemovedObservable=new c,this.onNewEffectLayerAddedObservable=new c,this.onEffectLayerRemovedObservable=new c,this.onBeforeRenderTargetsRenderObservable=new c,this.onAfterRenderTargetsRenderObservable=new c,this.onBeforeStepObservable=new c,this.onAfterStepObservable=new c,this.onActiveCameraChanged=new c,this.onActiveCamerasChanged=new c,this.onBeforeRenderingGroupObservable=new c,this.onAfterRenderingGroupObservable=new c,this.onMeshImportedObservable=new c,this.onAnimationFileImportedObservable=new c,this.onEnvironmentTextureChangedObservable=new c,this.onMeshUnderPointerUpdatedObservable=new c,this._registeredForLateAnimationBindings=new Xs(256),this._pointerPickingConfiguration=new jo,this.onPrePointerObservable=new c,this.onPointerObservable=new c,this.onPreKeyboardObservable=new c,this.onKeyboardObservable=new c,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Qo.FOGMODE_NONE,this.fogColor=new Xe(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this._frameGraph=null,this.frameGraphs=[],this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new xe(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new Xs(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new Ko,this._activeIndices=new Ko,this._activeParticles=new Ko,this._activeBones=new Ko,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=new Array(256),this._activeRequests=new Array,this._delayedFileRequests=null,this._pendingData=[],this._isDisposed=!1,this._isDisposing=!1,this._isReadyChecks=[],this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new Ws(256),this._processedMaterials=new Ws(256),this._renderTargets=new Xs(256),this._materialsRenderTargets=new Xs(256),this._activeParticleSystems=new Ws(256),this._activeSkeletons=new Xs(32),this._softwareSkinnedMeshes=new Xs(32),this._activeAnimatables=new Array,this._transformMatrix=Ie.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=Nn.Create(),this._beforeClearStage=Nn.Create(),this._beforeRenderTargetClearStage=Nn.Create(),this._gatherRenderTargetsStage=Nn.Create(),this._gatherActiveCameraRenderTargetsStage=Nn.Create(),this._isReadyForMeshStage=Nn.Create(),this._beforeEvaluateActiveMeshStage=Nn.Create(),this._evaluateSubMeshStage=Nn.Create(),this._preActiveMeshStage=Nn.Create(),this._cameraDrawRenderTargetStage=Nn.Create(),this._beforeCameraDrawStage=Nn.Create(),this._beforeRenderTargetDrawStage=Nn.Create(),this._beforeRenderingGroupDrawStage=Nn.Create(),this._beforeRenderingMeshStage=Nn.Create(),this._afterRenderingMeshStage=Nn.Create(),this._afterRenderingGroupDrawStage=Nn.Create(),this._afterCameraDrawStage=Nn.Create(),this._afterCameraPostProcessStage=Nn.Create(),this._afterRenderTargetDrawStage=Nn.Create(),this._afterRenderTargetPostProcessStage=Nn.Create(),this._afterRenderStage=Nn.Create(),this._pointerMoveStage=Nn.Create(),this._pointerDownStage=Nn.Create(),this._pointerUpStage=Nn.Create(),this._geometriesByUniqueId=null,this._uniqueId=0,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this.onReadyTimeoutObservable=new c,this.onReadyTimeoutDuration=12e4,this._timeoutChecksStartTime=0,this._floatingOriginScene=void 0,this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._freezeActiveMeshesCancel=null,this._useCurrentFrameBuffer=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._getFloatingOriginScene=()=>this._floatingOriginScene,this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[],this._uniqueId=this.getUniqueId();const s={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,defaultCameraLayerMask:268435455,defaultRenderableLayerMask:268435455,...t};this.defaultCameraLayerMask=s.defaultCameraLayerMask,this.defaultRenderableLayerMask=s.defaultRenderableLayerMask,e=this._engine=e||ee.LastCreatedEngine,s.virtual?e._virtualScenes.push(this):(ee._LastCreatedScene=this,e.scenes.push(this)),(e.getCreationOptions().useLargeWorldRendering||t?.useFloatingOrigin)&&(Ur.prototype._setMatrixOverride=Gr,Ur.prototype.setMatrix=function(e,t){return this._setMatrixOverride(e,Nr(e,t)),this},Br.prototype._updateMatrixForUniformOverride=kr,Br.prototype._updateMatrixForUniform=function(e,t){this._updateMatrixForUniformOverride(e,Nr(e,t))},this._floatingOriginScene=this,Ir.getScene=this._getFloatingOriginScene),this._uid=null,this._renderingManager=new vo(this),Mo&&(this.postProcessManager=new Mo(this)),Je()&&this.attachControl(),this._createUbo(),Eo&&(this._imageProcessingConfiguration=new Eo),this.setDefaultCandidateProviders(),s.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=s.useMaterialMeshMap,this.useClonedMeshMap=s.useClonedMeshMap,t&&t.virtual||e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,s=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==s}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return void 0!==this._animationRatio?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,s){return this._inputManager.simulatePointerUp(e,t,s),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,s=!0){this._inputManager.attachControl(e,t,s)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){if(this._isDisposed)return!1;let t;const s=this.getEngine(),i=s.currentRenderPassId;s.currentRenderPassId=this.activeCamera?.renderPassId??i;let r=!0;for(this._pendingData.length>0&&(r=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&(r&&=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t<this.meshes.length;t++){const i=this.meshes[t];if(!i.subMeshes||0===i.subMeshes.length)continue;if(!i.isReady(!0)){r=!1;continue}const n=i.hasThinInstances||"InstancedMesh"===i.getClassName()||"InstancedLinesMesh"===i.getClassName()||s.getCaps().instancedArrays&&i.instances.length>0;for(const e of this._isReadyForMeshStage)e.action(i,n)||(r=!1);if(!e)continue;const a=i.material||this.defaultMaterial;if(a)if(a._storeEffectOnSubMeshes)for(const e of i.subMeshes){const t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else a.hasRenderTargetTextures&&null!=a.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(a)&&(this._processedMaterials.push(a),this._materialsRenderTargets.concatWithNoDuplicate(a.getRenderTargetTextures()))}if(e){for(t=0;t<this._materialsRenderTargets.length;++t){this._materialsRenderTargets.data[t].isReadyForRendering()||(r=!1)}for(t=0;t<this.customRenderTargets.length;++t){this.customRenderTargets[t].isReadyForRendering()||(r=!1)}}for(t=0;t<this.geometries.length;t++){this.geometries[t].delayLoadState===dt.DELAYLOADSTATE_LOADING&&(r=!1)}if(this.activeCameras&&this.activeCameras.length>0)for(const e of this.activeCameras)e.isReady(!0)||(r=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(r=!1));for(const e of this.particleSystems)e.isReady()||(r=!1);if(this.proceduralTexturesEnabled)for(const e of this.proceduralTextures)e.isReady()||(r=!1);if(this.layers)for(const e of this.layers)e.isReady()||(r=!1);if(this.effectLayers)for(const e of this.effectLayers)e.isLayerReady()||(r=!1);for(const e of this._isReadyChecks)e.isReady()||(r=!1);return s.areAllEffectsReady()||(r=!1),s.currentRenderPassId=i,r}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout(()=>{this.unregisterBeforeRender(t)})};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){void 0!==t?setTimeout(()=>{this._executeOnceBeforeRender(e)},t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){const t=this.isLoading,s=this._pendingData.indexOf(e);-1!==s&&this._pendingData.splice(s,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}addIsReadyCheck(e){-1===this._isReadyChecks.indexOf(e)&&this._isReadyChecks.push(e)}removeIsReadyCheck(e){const t=this._isReadyChecks.indexOf(e);-1!==t&&this._isReadyChecks.splice(t,1)}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}async whenReadyAsync(e=!1){return await new Promise(t=>{this.executeWhenReady(()=>{t()},e)})}_clearReadynessChecksData(){this._timeoutChecksStartTime=0,this.onReadyTimeoutObservable.clear(),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null}_checkIsReady(e=!1){if(this._registerTransientComponents(),0===this._timeoutChecksStartTime)this._timeoutChecksStartTime=nt.Now;else if(this.onReadyTimeoutDuration>0&&nt.Now-this._timeoutChecksStartTime>this.onReadyTimeoutDuration)return this.onReadyTimeoutObservable.notifyObservers(this),void this._clearReadynessChecksData();if(this.isReady(e))return this.onReadyObservable.notifyObservers(this),void this._clearReadynessChecksData();this._isDisposed?this._clearReadynessChecksData():this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=nt.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getInverseProjectionMatrix(){return this._inverseProjectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,s,i){this._multiviewSceneUboIsActive=!!(s&&i&&this._multiviewSceneUbo),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._inverseProjectionMatrix||(this._inverseProjectionMatrix=new Ie),this._projectionMatrix.invertToRef(this._inverseProjectionMatrix),this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?js.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=js.GetPlanes(this._transformMatrix),this._multiviewSceneUboIsActive&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(s,i):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix),this._sceneUbo.updateMatrix("inverseProjection",this._inverseProjectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUboIsActive&&this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e,t){const s="boolean"==typeof t?t:t?.trackUBOsInFrame,i=new dr(this._engine,void 0,!1,e??"scene",void 0,s);return i.addUniform("viewProjection",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i.addUniform("inverseProjection",16),i}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}get floatingOriginMode(){return void 0!==this._floatingOriginScene}get floatingOriginOffset(){return this.floatingOriginMode?this._eyePosition:xe.ZeroReadOnly}getUniqueId(){return Yo.UniqueId}addMesh(e,t=!1){if(!this._blockEntityCollection&&(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),Xt.SetImmediate(()=>{this.onNewMeshAddedObservable.notifyObservers(e)}),t)){const t=e.getChildMeshes();for(const e of t)this.addMesh(e)}}removeMesh(e,t=!1){const s=this.meshes.indexOf(e);if(-1!==s&&(this.meshes.splice(s,1),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t){const t=e.getChildMeshes();for(const e of t)this.removeMesh(e)}return s}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){const e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){const t=this.skeletons.indexOf(e);return-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(-1!==t){for(const t of this.meshes)t._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes(),this.onLightRemovedObservable.notifyObservers(e)}return t}removeCamera(e){const t=this.cameras.indexOf(e);if(-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){const t=this.particleSystems.indexOf(e);return-1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),this.onParticleSystemRemovedObservable.notifyObservers(e),t}removeAnimation(e){const t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,s){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),this.onAnimationGroupRemovedObservable.notifyObservers(e),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(-1!==t&&t<this.materials.length){if(t!==this.materials.length-1){const e=this.materials[this.materials.length-1];this.materials[t]=e,e._indexInSceneMaterialArray=t}e._indexInSceneMaterialArray=-1,this.materials.pop()}return this.onMaterialRemovedObservable.notifyObservers(e),t}removeActionManager(e){const t=this.actionManagers.indexOf(e);return-1!==t&&this.actionManagers.splice(t,1),t}removeTexture(e){const t=this.textures.indexOf(e);return-1!==t&&this.textures.splice(t,1),this.onTextureRemovedObservable.notifyObservers(e),t}removeFrameGraph(e){const t=this.frameGraphs.indexOf(e);return-1!==t&&this.frameGraphs.splice(t,1),this.onFrameGraphRemovedObservable.notifyObservers(e),t}removeObjectRenderer(e){const t=this.objectRenderers.indexOf(e);return-1!==t&&this.objectRenderers.splice(t,1),this.onObjectRendererRemovedObservable.notifyObservers(e),t}removePostProcess(e){const t=this.postProcesses.indexOf(e);return-1!==t&&this.postProcesses.splice(t,1),this.onPostProcessRemovedObservable.notifyObservers(e),t}removeEffectLayer(e){const t=this.effectLayers.indexOf(e);return-1!==t&&this.effectLayers.splice(t,1),this.onEffectLayerRemovedObservable.notifyObservers(e),t}addLight(e){if(!this._blockEntityCollection){this.lights.push(e),this.sortLightsByPriority(),e.parent||e._addToSceneRootNodes();for(const t of this.meshes)-1===t.lightSources.indexOf(e)&&(t.lightSources.push(e),t._resyncLightSources());Xt.SetImmediate(()=>{this.onNewLightAddedObservable.notifyObservers(e)})}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(Mr.CompareLightsPriority)}addCamera(e){this._blockEntityCollection||(this.cameras.push(e),Xt.SetImmediate(()=>{this.onNewCameraAddedObservable.notifyObservers(e)}),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),Xt.SetImmediate(()=>{this.onNewSkeletonAddedObservable.notifyObservers(e)}))}addParticleSystem(e){this._blockEntityCollection||(this.particleSystems.push(e),Xt.SetImmediate(()=>{this.onNewParticleSystemAddedObservable.notifyObservers(e)}))}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||(this.animationGroups.push(e),Xt.SetImmediate(()=>{this.onNewAnimationGroupAddedObservable.notifyObservers(e)}))}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),Xt.SetImmediate(()=>{this.onNewMultiMaterialAddedObservable.notifyObservers(e)}))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneMaterialArray||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),Xt.SetImmediate(()=>{this.onNewMaterialAddedObservable.notifyObservers(e)}))}addMorphTargetManager(e){this._blockEntityCollection||this.morphTargetManagers.push(e)}addGeometry(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))}addActionManager(e){this.actionManagers.push(e)}addTexture(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))}addFrameGraph(e){this.frameGraphs.push(e),Xt.SetImmediate(()=>{this.onNewFrameGraphAddedObservable.notifyObservers(e)})}addObjectRenderer(e){this.objectRenderers.push(e),Xt.SetImmediate(()=>{this.onNewObjectRendererAddedObservable.notifyObservers(e)})}addPostProcess(e){this._blockEntityCollection||(this.postProcesses.push(e),Xt.SetImmediate(()=>{this.onNewPostProcessAddedObservable.notifyObservers(e)}))}addEffectLayer(e){this._blockEntityCollection||(this.effectLayers.push(e),Xt.SetImmediate(()=>{this.onNewEffectLayerAddedObservable.notifyObservers(e)}))}switchActiveCamera(e,t=!0){this._engine.getInputElement()&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())}setActiveCameraById(e){const t=this.getCameraById(e);return t?(this.activeCamera=t,t):null}setActiveCameraByName(e){const t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null}getAnimationGroupByName(e){for(let t=0;t<this.animationGroups.length;t++)if(this.animationGroups[t].name===e)return this.animationGroups[t];return null}_getMaterial(e,t){for(let e=0;e<this.materials.length;e++){const s=this.materials[e];if(t(s))return s}if(e)for(let e=0;e<this.multiMaterials.length;e++){const s=this.multiMaterials[e];if(t(s))return s}return null}getMaterialByUniqueID(e,t=!1){return this.getMaterialByUniqueId(e,t)}getMaterialByUniqueId(e,t=!1){return this._getMaterial(t,t=>t.uniqueId===e)}getMaterialById(e,t=!1){return this._getMaterial(t,t=>t.id===e)}getMaterialByName(e,t=!1){return this._getMaterial(t,t=>t.name===e)}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t)for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t];return null}getTextureByUniqueId(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].uniqueId===e)return this.textures[t];return null}getTextureByName(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].name===e)return this.textures[t];return null}getCameraById(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null}getCameraByUniqueId(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null}getCameraByName(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null}getBoneById(e){for(let t=0;t<this.skeletons.length;t++){const s=this.skeletons[t];for(let t=0;t<s.bones.length;t++)if(s.bones[t].id===e)return s.bones[t]}return null}getBoneByName(e){for(let t=0;t<this.skeletons.length;t++){const s=this.skeletons[t];for(let t=0;t<s.bones.length;t++)if(s.bones[t].name===e)return s.bones[t]}return null}getLightByName(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null}getLightById(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null}getLightByUniqueId(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];return null}getParticleSystemById(e){for(let t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null}getGeometryById(e){for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].id===e)return this.geometries[t];return null}_getGeometryByUniqueId(e){if(this._geometriesByUniqueId){const t=this._geometriesByUniqueId[e];if(void 0!==t)return this.geometries[t]}else for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].uniqueId===e)return this.geometries[t];return null}getFrameGraphByName(e){for(let t=0;t<this.frameGraphs.length;t++)if(this.frameGraphs[t].name===e)return this.frameGraphs[t];return null}pushGeometry(e,t){return!(!t&&this._getGeometryByUniqueId(e.uniqueId))&&(this.addGeometry(e),Xt.SetImmediate(()=>{this.onNewGeometryAddedObservable.notifyObservers(e)}),!0)}removeGeometry(e){let t;if(this._geometriesByUniqueId){if(t=this._geometriesByUniqueId[e.uniqueId],void 0===t)return!1}else if(t=this.geometries.indexOf(e),t<0)return!1;if(t!==this.geometries.length-1){const e=this.geometries[this.geometries.length-1];e&&(this.geometries[t]=e,this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0}getGeometries(){return this.geometries}getMeshById(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null}getMeshesById(e){return this.meshes.filter(function(t){return t.id===e})}getTransformNodeById(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getTransformNodeByUniqueId(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].uniqueId===e)return this.transformNodes[t];return null}getTransformNodesById(e){return this.transformNodes.filter(function(t){return t.id===e})}getMeshByUniqueId(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null}getLastMeshById(e){for(let t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];for(t=this.skeletons.length-1;t>=0;t--){const s=this.skeletons[t];for(let t=s.bones.length-1;t>=0;t--)if(s.bones[t].id===e)return s.bones[t]}return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const s=this.getTransformNodeById(e);if(s)return s;const i=this.getLightById(e);if(i)return i;const r=this.getCameraById(e);if(r)return r;const n=this.getBoneById(e);return n||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const s=this.getTransformNodeByName(e);if(s)return s;const i=this.getLightByName(e);if(i)return i;const r=this.getCameraByName(e);if(r)return r;const n=this.getBoneByName(e);return n||null}getMeshByName(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null}getTransformNodeByName(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].name===e)return this.transformNodes[t];return null}getLastSkeletonById(e){for(let t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].uniqueId===e)return this.skeletons[t];return null}getSkeletonById(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByName(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null}getMorphTargetManagerById(e){for(let t=0;t<this.morphTargetManagers.length;t++)if(this.morphTargetManagers[t].uniqueId===e)return this.morphTargetManagers[t];return null}getMorphTargetById(e){for(let t=0;t<this.morphTargetManagers.length;++t){const s=this.morphTargetManagers[t];for(let t=0;t<s.numTargets;++t){const i=s.getTarget(t);if(i.id===e)return i}}return null}getMorphTargetByName(e){for(let t=0;t<this.morphTargetManagers.length;++t){const s=this.morphTargetManagers[t];for(let t=0;t<s.numTargets;++t){const i=s.getTarget(t);if(i.name===e)return i}}return null}getPostProcessByName(e){for(let t=0;t<this.postProcesses.length;++t){const s=this.postProcesses[t];if(s.name===e)return s}return null}isActiveMesh(e){return-1!==this._activeMeshes.indexOf(e)}get uid(){return this._uid||(this._uid=Fs.RandomId()),this._uid}addExternalData(e,t){return this._externalData||(this._externalData=new co),this._externalData.add(e,t)}getExternalData(e){return this._externalData?this._externalData.get(e):null}getOrAddExternalDataWithFactory(e,t){return this._externalData||(this._externalData=new co),this._externalData.getOrAddWithFactory(e,t)}removeExternalData(e){return this._externalData.remove(e)}_evaluateSubMesh(e,t,s,i){if(i||e.isInFrustum(this._frustumPlanes)){for(const s of this._evaluateSubMeshStage)s.action(t,e);const s=e.getMaterial();null!=s&&(s.hasRenderTargetTextures&&null!=s.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(s)&&(this._processedMaterials.push(s),this._materialsRenderTargets.concatWithNoDuplicate(s.getRenderTargetTextures())),this._renderingManager.dispatch(e,t,s))}}freeProcessedMaterials(){this._processedMaterials.dispose()}get blockfreeActiveMeshesAndRenderingGroups(){return this._preventFreeActiveMeshesAndRenderingGroups}set blockfreeActiveMeshesAndRenderingGroups(e){this._preventFreeActiveMeshesAndRenderingGroups!==e&&(e&&(this.freeActiveMeshes(),this.freeRenderingGroups()),this._preventFreeActiveMeshesAndRenderingGroups=e)}freeActiveMeshes(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._activeMeshes.dispose(),this.activeCamera&&this.activeCamera._activeMeshes&&this.activeCamera._activeMeshes.dispose(),this.activeCameras))for(let e=0;e<this.activeCameras.length;e++){const t=this.activeCameras[e];t&&t._activeMeshes&&t._activeMeshes.dispose()}}freeRenderingGroups(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._renderingManager&&this._renderingManager.freeRenderingGroups(),this.textures))for(let e=0;e<this.textures.length;e++){const t=this.textures[e];t&&t.renderList&&t.freeRenderingGroups()}}_isInIntermediateRendering(){return this._intermediateRendering}freezeActiveMeshes(e=!1,t,s,i=!0,r=!1){if(this.frameGraph){this._renderWithFrameGraph(!0,!1,!0);const n=this.frameGraph.getTasksByClassName(["FrameGraphObjectRendererTask","FrameGraphGeometryRendererTask"]);for(const e of n)e.objectRenderer._freezeActiveMeshes(i);return this._freezeActiveMeshesCancel=Yt(()=>{let e=!0,t=!0;for(const s of n)e&&=s.objectRenderer._isFrozen,t&&=null!==s.objectRenderer._freezeActiveMeshesCancel;if(e)return!0;if(!t)throw new Error("Freezing active meshes was cancelled");return!1},()=>{this._freezeActiveMeshesCancel=null,this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,t?.()},(e,t)=>{if(this._freezeActiveMeshesCancel=null,this.unfreezeActiveMeshes(),t){const t="Scene: Timeout while waiting for meshes to be frozen.";s?s(t):(a.Error(t),e&&a.Error(e))}else{const t="Scene: An unexpected error occurred while trying to freeze active meshes.";s?s(t):(a.Error(t),e&&(a.Error(e),e.stack&&a.Error(e.stack)))}}),this}return this.executeWhenReady(()=>{if(this.activeCamera){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,i)for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._freeze();t&&t()}else s&&s("No active camera found")}),this}unfreezeActiveMeshes(){for(let e=0;e<this.meshes.length;e++){const t=this.meshes[e];t._internalAbstractMeshDataInfo&&(t._internalAbstractMeshDataInfo._isActive=!1)}if(this._freezeActiveMeshesCancel?.(),this._freezeActiveMeshesCancel=null,this.frameGraph){const e=this.frameGraph.getTasksByClassName(["FrameGraphObjectRendererTask","FrameGraphGeometryRendererTask"]);for(const t of e)t.objectRenderer._unfreezeActiveMeshes()}else for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._unFreeze();return this._activeMeshesFrozen=!1,this}_executeActiveContainerCleanup(e){(!this._engine.snapshotRendering||this._engine.snapshotRenderingMode!==dt.SNAPSHOTRENDERING_FAST)&&this._activeMeshesFrozen&&this._activeMeshes.length||this.onBeforeRenderObservable.addOnce(()=>e.dispose())}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===dt.SNAPSHOTRENDERING_FAST)return void(this._activeMeshes.length>0&&(this.activeCamera?._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset()));if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const e=this._activeMeshes.length;for(let t=0;t<e;t++){this._activeMeshes.data[t].computeWorldMatrix()}}if(this._activeParticleSystems){const e=this._activeParticleSystems.length;for(let t=0;t<e;t++)this._activeParticleSystems.data[t].animate()}return void this._renderingManager.resetSprites()}if(!this.activeCamera)return;this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this),this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset(),this._materialsRenderTargets.reset();for(const e of this._beforeEvaluateActiveMeshStage)e.action();const e=this.getActiveMeshCandidates(),t=e.length;for(let s=0;s<t;s++){const t=e.data[s];let i=t._internalAbstractMeshDataInfo._currentLOD.get(this.activeCamera);if(i?i[1]=-1:(i=[t,-1],t._internalAbstractMeshDataInfo._currentLOD.set(this.activeCamera,i)),t.isBlocked)continue;if(this._totalVertices.addCount(t.getTotalVertices(),!1),!t.isReady()||!t.isEnabled()||t.scaling.hasAZeroComponent)continue;t.computeWorldMatrix(),t.actionManager&&t.actionManager.hasSpecificTriggers2(dt.ACTION_OnIntersectionEnterTrigger,dt.ACTION_OnIntersectionExitTrigger)&&this._meshesForIntersections.pushNoDuplicate(t);let r=this.customLODSelector?this.customLODSelector(t,this.activeCamera):t.getLOD(this.activeCamera);if(i[0]=r,i[1]=this._frameId,null!=r&&(r!==t&&0!==r.billboardMode&&r.computeWorldMatrix(),t._preActivate(),t.isVisible&&t.visibility>0&&0!==(t.layerMask&this.activeCamera.layerMask)&&(this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||t.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(t),this.activeCamera._activeMeshes.push(t),r!==t&&r._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(t);t._activate(this._renderId,!1)&&(t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(r=t):r._internalAbstractMeshDataInfo._onlyForInstances=!1,r._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(t,r)),t._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e<this.particleSystems.length;e++){const t=this.particleSystems[e];if(!t.isStarted()||!t.emitter)continue;const s=t.emitter;s.position&&!s.isEnabled()||(this._activeParticleSystems.push(t),t.animate(),this._renderingManager.dispatchParticles(t))}this.onAfterParticlesRenderingObservable.notifyObservers(this)}}_prepareSkeleton(e){this._skeletonsEnabled&&e.skeleton&&(this._activeSkeletons.pushNoDuplicate(e.skeleton)&&(e.skeleton.prepare(),this._activeBones.addCount(e.skeleton.bones.length,!1)),e.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(e)&&this.frameGraph&&e.applySkeleton(e.skeleton))}_activeMesh(e,t){this._prepareSkeleton(t);let s=e.hasInstances||e.isAnInstance||this.dispatchAllSubMeshesOfActiveMeshes||this._skipFrustumClipping||t.alwaysSelectAsActiveMesh;if(t&&t.subMeshes&&t.subMeshes.length>0){const i=this.getActiveSubMeshCandidates(t),r=i.length;s=s||1===r;for(let n=0;n<r;n++){const r=i.data[n];this._evaluateSubMesh(r,t,e,s)}}}updateTransformMatrix(e){const t=this.activeCamera;if(t)if(t._renderingMultiview){const s=t._rigCameras[0],i=t._rigCameras[1];this.setTransformMatrix(s.getViewMatrix(),s.getProjectionMatrix(e),i.getViewMatrix(),i.getProjectionMatrix(e))}else this.setTransformMatrix(t.getViewMatrix(),t.getProjectionMatrix(e))}_bindFrameBuffer(e,t=!0){this._useCurrentFrameBuffer||(e&&e._multiviewTexture?e._multiviewTexture._bindFrameBuffer():e&&e.outputRenderTarget?e.outputRenderTarget._bindFrameBuffer():this._engine._currentFrameBufferIsDefaultFrameBuffer()||this._engine.restoreDefaultFramebuffer()),t&&this._clearFrameBuffer(e)}_clearFrameBuffer(e){if(e&&e._multiviewTexture);else if(e&&e.outputRenderTarget&&!e._renderingMultiview){const t=e.outputRenderTarget;t.onClearObservable.hasObservers()?t.onClearObservable.notifyObservers(this._engine):t.skipInitialClear||e.isRightCamera||(this.autoClear&&this._engine.clear(t.clearColor||this._clearColor,!t._cleared,!0,!0),t._cleared=!0)}else this._defaultFrameBufferCleared?this._engine.clear(null,!1,!0,!0):(this._defaultFrameBufferCleared=!0,this._clear())}_renderForCamera(e,t,s=!0){if(e&&e._skipRendering)return;const i=this._engine;if(this._activeCamera=e,!this.activeCamera)throw new Error("Active camera not set");if(i.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,!this.prePass&&s){let t=!0;e._renderingMultiview&&e.outputRenderTarget&&(t=e.outputRenderTarget.skipInitialClear,this.autoClear&&(this._defaultFrameBufferCleared=!1,e.outputRenderTarget.skipInitialClear=!1)),this._bindFrameBuffer(this._activeCamera),e._renderingMultiview&&e.outputRenderTarget&&(e.outputRenderTarget.skipInitialClear=t)}this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??dt.RENDERPASS_MAIN,this._evaluateActiveMeshes();for(let e=0;e<this._softwareSkinnedMeshes.length;e++){const t=this._softwareSkinnedMeshes.data[e];t.applySkeleton(t.skeleton)}this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets),e.customRenderTargets&&e.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const e of this._gatherActiveCameraRenderTargetsStage)e.action(this._renderTargets);let r=!1;if(this.renderTargetsEnabled){let e;if(this._intermediateRendering=!0,this._renderTargets.length>0){Fs.StartPerformanceCounter("Render targets",this._renderTargets.length>0);const t=this.getBoundingBoxRenderer?.();for(let s=0;s<this._renderTargets.length;s++){const i=this._renderTargets.data[s];if(i._shouldRender()){this._renderId++;const s=i.activeCamera&&i.activeCamera!==this.activeCamera;t&&!e&&(e=t.renderList.length>0?t.renderList.data.slice():[],e.length=t.renderList.length),i.render(s,this.dumpNextRenderTargets),r=!0}}t&&e&&(t.renderList.data=e,t.renderList.length=e.length),Fs.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}if(this._cameraDrawRenderTargetStage.length>0){const t=this.getBoundingBoxRenderer?.();t&&!e&&(e=t.renderList.length>0?t.renderList.data.slice():[],e.length=t.renderList.length);for(const e of this._cameraDrawRenderTargetStage)r=e.action(this.activeCamera)||r;t&&e&&(t.renderList.data=e,t.renderList.length=e.length)}this._intermediateRendering=!1}r&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(const e of this._beforeCameraDrawStage)e.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this);const n=i.snapshotRendering&&i.snapshotRenderingMode===dt.SNAPSHOTRENDERING_FAST;n&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!n),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const e of this._afterCameraDrawStage)e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(const e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(e.cameraRigMode===dt.RIG_MODE_NONE||e._renderingMultiview)return e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t<e._rigCameras.length;t++)this._renderForCamera(e._rigCameras[t],e)}this._activeCamera=e,this.updateTransformMatrix(),this.onAfterRenderCameraObservable.notifyObservers(e)}_checkIntersections(){for(let e=0;e<this._meshesForIntersections.length;e++){const t=this._meshesForIntersections.data[e];if(t.actionManager)for(let e=0;t.actionManager&&e<t.actionManager.actions.length;e++){const s=t.actionManager.actions[e];if(s.trigger===dt.ACTION_OnIntersectionEnterTrigger||s.trigger===dt.ACTION_OnIntersectionExitTrigger){const e=s.getTriggerParameter(),i=e.mesh?e.mesh:e,r=i.intersectsMesh(t,e.usePreciseIntersection),n=t._intersectionsInProgress.indexOf(i);r&&-1===n?s.trigger===dt.ACTION_OnIntersectionEnterTrigger?(s._executeCurrent(yo.CreateNew(t,void 0,i)),t._intersectionsInProgress.push(i)):s.trigger===dt.ACTION_OnIntersectionExitTrigger&&t._intersectionsInProgress.push(i):!r&&n>-1&&(s.trigger===dt.ACTION_OnIntersectionExitTrigger&&s._executeCurrent(yo.CreateNew(t,void 0,i)),t.actionManager.hasSpecificTrigger(dt.ACTION_OnIntersectionExitTrigger,e=>{const t=e.mesh?e.mesh:e;return i===t})&&s.trigger!==dt.ACTION_OnIntersectionExitTrigger||t._intersectionsInProgress.splice(n,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Qo.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Qo.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),s=1e3/t/1e3;let i=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&i<n;)this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=t*s,this._animate(t),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(t),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,i++,e-=t;this._timeAccumulator=e<0?0:e}else{const e=this.useConstantAnimationDeltaTime?16:Math.max(Qo.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Qo.MaxDeltaTime));this._animationRatio=.06*e,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(e)}}_clear(){(this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this._clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil)}_checkCameraRenderTarget(e){if(e?.outputRenderTarget&&!e?.isRigCamera&&(e.outputRenderTarget._cleared=!1),e?.rigCameras?.length)for(let t=0;t<e.rigCameras.length;++t){const s=e.rigCameras[t].outputRenderTarget;s&&(s._cleared=!1)}}resetDrawCache(e){if(this.meshes)for(const t of this.meshes)t.resetDrawCache(e)}_renderWithFrameGraph(e=!0,t=!1,s=!1){if(this.activeCamera=null,this.activeCameras=null,e)for(const e of this.cameras)if(e.update(),e.cameraRigMode!==dt.RIG_MODE_NONE)for(let t=0;t<e._rigCameras.length;t++)e._rigCameras[t].update();this.onBeforeRenderObservable.notifyObservers(this),this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),this._renderTargets.reset();const i=this._frameGraph?.findMainCamera()??null;if(this.renderTargetsEnabled){this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture),this._renderTargets.concatWithNoDuplicate(this.customRenderTargets),Fs.StartPerformanceCounter("Custom render targets",this._renderTargets.length>0);for(let e=0;e<this._renderTargets.length;e++){const t=this._renderTargets.data[e],s=t.activeCamera||i;this._renderRenderTarget(t,s,!0,this.dumpNextRenderTargets)}Fs.EndPerformanceCounter("Custom render targets",this._renderTargets.length>0),this._renderId++}this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const e of this._beforeClearStage)e.action();if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===dt.SNAPSHOTRENDERING_FAST)this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset();else{const e=this.getActiveMeshCandidates(),t=e.length;if(this._activeMeshesFrozen){if(!this._skipEvaluateActiveMeshesCompletely)for(let s=0;s<t;s++){const t=e.data[s];t._internalAbstractMeshDataInfo._wasActiveLastFrame&&t.computeWorldMatrix()}if(this.particlesEnabled){const e=this._activeParticleSystems.length;for(let t=0;t<e;t++)this._activeParticleSystems.data[t].animate()}}else{this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset();for(let i=0;i<t;i++){const t=e.data[i];t._internalAbstractMeshDataInfo._wasActiveLastFrame=!1,t.isBlocked||(this._totalVertices.addCount(t.getTotalVertices(),!1),t.isReady()&&t.isEnabled()&&!t.scaling.hasAZeroComponent&&(t.computeWorldMatrix(s),t.actionManager&&t.actionManager.hasSpecificTriggers2(dt.ACTION_OnIntersectionEnterTrigger,dt.ACTION_OnIntersectionExitTrigger)&&this._meshesForIntersections.pushNoDuplicate(t)))}if(this.particlesEnabled)for(let e=0;e<this.particleSystems.length;e++){const t=this.particleSystems[e];if(!t.isStarted()||!t.emitter)continue;const s=t.emitter;s.position&&!s.isEnabled()||(this._activeParticleSystems.push(t),t.animate())}}}this.frameGraph?.execute()}_renderRenderTarget(e,t,s=!1,i=!1){if(this._intermediateRendering=!0,e._shouldRender()){if(this._renderId++,this.activeCamera=t,!this.activeCamera)throw new Error("Active camera not set");this._engine.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),e.render(s,i)}this._intermediateRendering=!1}render(e=!0,t=!1){if(!this.isDisposed){if(this.onReadyObservable.hasObservers()&&null===this._executeWhenReadyTimeoutId&&this._checkIsReady(),Ir.getScene=this._getFloatingOriginScene,this._frameId++,this._defaultFrameBufferCleared=!1,this._checkCameraRenderTarget(this.activeCamera),this.activeCameras?.length)for(const e of this.activeCameras)this._checkCameraRenderTarget(e);this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(dt.ACTION_OnEveryFrameTrigger),t||this.animate();for(const e of this._beforeCameraUpdateStage)e.action();if(e)if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e<this.activeCameras.length;e++){const t=this.activeCameras[e];if(t.update(),t.cameraRigMode!==dt.RIG_MODE_NONE)for(let e=0;e<t._rigCameras.length;e++)t._rigCameras[e].update()}else if(this.activeCamera&&(this.activeCamera.update(),this.activeCamera.cameraRigMode!==dt.RIG_MODE_NONE))for(let e=0;e<this.activeCamera._rigCameras.length;e++)this.activeCamera._rigCameras[e].update();if(this.customRenderFunction)this._renderId++,this._engine.currentRenderPassId=dt.RENDERPASS_MAIN,this.customRenderFunction(e,t);else{this.onBeforeRenderObservable.notifyObservers(this),this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);const e=this.activeCameras?.length?this.activeCameras[0]:this.activeCamera;if(this.renderTargetsEnabled){Fs.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0);for(let t=0;t<this.customRenderTargets.length;t++){const s=this.customRenderTargets[t],i=s.activeCamera||this.activeCamera;this._renderRenderTarget(s,i,e!==i,this.dumpNextRenderTargets)}Fs.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._renderId++}this._engine.currentRenderPassId=e?.renderPassId??dt.RENDERPASS_MAIN,this.activeCamera=e,this._activeCamera&&this._activeCamera.cameraRigMode!==dt.RIG_MODE_CUSTOM&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const e of this._beforeClearStage)e.action();this._clearFrameBuffer(this.activeCamera);for(const e of this._gatherRenderTargetsStage)e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e<this.activeCameras.length;e++)this._processSubCameras(this.activeCameras[e],e>0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}}this._checkIntersections();for(const e of this._afterRenderStage)e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e<this._toBeDisposed.length;e++){const t=this._toBeDisposed[e];t&&t.dispose()}this._toBeDisposed.length=0}this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0),this._engine.restoreDefaultFramebuffer()}}freezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].freeze()}unfreezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].unfreeze()}dispose(){if(this.isDisposed)return;if(this._isDisposing=!0,this.beforeRender=null,this.afterRender=null,this.metadata=null,this.skeletons.length=0,this.morphTargetManagers.length=0,this._transientComponents.length=0,this._isReadyForMeshStage.clear(),this._beforeEvaluateActiveMeshStage.clear(),this._evaluateSubMeshStage.clear(),this._preActiveMeshStage.clear(),this._cameraDrawRenderTargetStage.clear(),this._beforeCameraDrawStage.clear(),this._beforeRenderTargetDrawStage.clear(),this._beforeRenderingGroupDrawStage.clear(),this._beforeRenderingMeshStage.clear(),this._afterRenderingMeshStage.clear(),this._afterRenderingGroupDrawStage.clear(),this._afterCameraDrawStage.clear(),this._afterRenderTargetDrawStage.clear(),this._afterRenderStage.clear(),this._beforeCameraUpdateStage.clear(),this._beforeClearStage.clear(),this._gatherRenderTargetsStage.clear(),this._gatherActiveCameraRenderTargetsStage.clear(),this._pointerMoveStage.clear(),this._pointerDownStage.clear(),this._pointerUpStage.clear(),this._isReadyChecks.length=0,this.importedMeshesFiles=[],this._activeAnimatables&&Be(this.stopAllAnimations)){for(const e of this._activeAnimatables)e.onAnimationEndObservable.clear(),e.onAnimationEnd=null;this.stopAllAnimations()}this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){a.Error("An error occurred while calling onDisposeObservable!",e)}this.detachControl();const t=this._engine.getInputElement?.();if(t)for(let e=0;e<this.cameras.length;e++)this.cameras[e].detachControl();this._disposeList(this.animationGroups),this._disposeList(this.lights),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.meshes,e=>e.dispose(!0)),this._disposeList(this.transformNodes,e=>e.dispose(!0));const s=this.cameras;this._disposeList(s),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._disposeList(this.frameGraphs),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let i=this._engine.scenes.indexOf(this);if(i>-1&&this._engine.scenes.splice(i,1),this._floatingOriginScene=void 0,0===this._engine.scenes.length&&(li.prototype.setMatrix=Gr,Ur._setMatrixOverride=void 0,Br.prototype._updateMatrixForUniform=kr,Br.prototype._updateMatrixForUniformOverride=void 0),ee._LastCreatedScene===this){ee._LastCreatedScene=null;let e=ee.Instances.length-1;for(;e>=0;){const t=ee.Instances[e];if(t.scenes.length>0){ee._LastCreatedScene=t.scenes[this._engine.scenes.length-1];break}e--}}i=this._engine._virtualScenes.indexOf(this),i>-1&&this._engine._virtualScenes.splice(i,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onNewFrameGraphAddedObservable.clear(),this.onFrameGraphRemovedObservable.clear(),this.onNewObjectRendererAddedObservable.clear(),this.onObjectRendererRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this.onClearColorChangedObservable.clear(),this.onEnvironmentTextureChangedObservable.clear(),this.onMeshUnderPointerUpdatedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const s=e.slice(0);t=t??(e=>e.dispose());for(const e of s)t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e<this.meshes.length;e++){const t=this.meshes[e].geometry;t&&t.clearCachedData()}}cleanCachedTextureBuffer(){for(const e of this.textures){e._buffer&&(e._buffer=null)}}getWorldExtends(e){const t=new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new xe(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);e=e||(()=>!0);const i=this.meshes.filter(e);for(const e of i){if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)continue;const i=e.getBoundingInfo(),r=i.boundingBox.minimumWorld,n=i.boundingBox.maximumWorld;xe.CheckExtends(r,t,s),xe.CheckExtends(n,t,s)}return t.x===Number.MAX_VALUE?{min:xe.Zero(),max:xe.Zero()}:{min:t,max:s}}createPickingRay(e,t,s,i,r=!1){throw Le("Ray")}createPickingRayToRef(e,t,s,i,r,n=!1,a=!1){throw Le("Ray")}createPickingRayInCameraSpace(e,t,s){throw Le("Ray")}createPickingRayInCameraSpaceToRef(e,t,s,i){throw Le("Ray")}pick(e,t,s,i,r,n){const o=Le("Ray",!0);return o&&a.Warn(o),new ur}pickWithBoundingInfo(e,t,s,i,r){const n=Le("Ray",!0);return n&&a.Warn(n),new ur}pickWithRay(e,t,s,i){throw Le("Ray")}multiPick(e,t,s,i,r){throw Le("Ray")}multiPickWithRay(e,t,s){throw Le("Ray")}setPointerOverMesh(e,t,s){this._inputManager.setPointerOverMesh(e,t,s)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag)}_getByTags(e,t,s){if(void 0===t)return e;const i=[];for(const r in e){const n=e[r];Ge&&Ge.MatchesQuery(n,t)&&(!s||s(n))&&i.push(n)}return i}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,s=null,i=null){this._renderingManager.setRenderingOrder(e,t,s,i)}setRenderingAutoClearDepthStencil(e,t,s=!0,i=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,s,i)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(dt.MATERIAL_AllDirtyFlag))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const s of this.materials)t&&!t(s)||s.markAsDirty(e)}_loadFile(e,t,s,i,r,n,a){const o=fs(e,t,s,i?this.offlineProvider:void 0,r,n,a);return this._activeRequests.push(o),o.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),o}async _loadFileAsync(e,t,s,i,r){return await new Promise((n,a)=>{this._loadFile(e,e=>{n(e)},t,s,i,(e,t)=>{a(t)},r)})}async _loadDelayedFileAsync(e,t,s){this._delayedFileRequests||(this._delayedFileRequests=new Map);const i=`${e}|${t?"binary":"string"}`;let r=this._delayedFileRequests.get(i);if(!r){r=t?this._loadFileAsync(e,void 0,s,!0):this._loadFileAsync(e,void 0,s,!1);const n=r;(async()=>{try{await n}catch{}this._delayedFileRequests?.delete(i)})(),this._delayedFileRequests.set(i,r)}return await r}_requestFile(e,t,s,i,r,n,a){const o=gs(e,t,s,i?this.offlineProvider:void 0,r,n,a);return this._activeRequests.push(o),o.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),o}async _requestFileAsync(e,t,s,i,r){return await new Promise((n,a)=>{this._requestFile(e,e=>{n(e)},t,s,i,e=>{a(e)},r)})}_readFile(e,t,s,i,r){const n=ps(e,t,s,i,r);return this._activeRequests.push(n),n.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),n}async _readFileAsync(e,t,s){return await new Promise((i,r)=>{this._readFile(e,e=>{i(e)},t,s,e=>{r(e)})})}getPerfCollector(){throw Le("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}Qo.FOGMODE_NONE=dt.FOGMODE_NONE,Qo.FOGMODE_EXP=dt.FOGMODE_EXP,Qo.FOGMODE_EXP2=dt.FOGMODE_EXP2,Qo.FOGMODE_LINEAR=dt.FOGMODE_LINEAR,Qo.MinDeltaTime=1,Qo.MaxDeltaTime=1e3,Qo._OriginalDefaultMaterialFactory=Qo.DefaultMaterialFactory;let Jo=!1;var eh;Qo.prototype.sortActiveAnimatables??=Ne("Scene","sortActiveAnimatables"),Qo.prototype.beginWeightedAnimation??=Ne("Scene","beginWeightedAnimation"),Qo.prototype.beginAnimation??=Ne("Scene","beginAnimation"),Qo.prototype.beginHierarchyAnimation??=Ne("Scene","beginHierarchyAnimation"),Qo.prototype.beginDirectAnimation??=Ne("Scene","beginDirectAnimation"),Qo.prototype.beginDirectHierarchyAnimation??=Ne("Scene","beginDirectHierarchyAnimation"),Qo.prototype.getAnimatableByTarget??=Ne("Scene","getAnimatableByTarget"),Qo.prototype.getAllAnimatablesByTarget??=Ne("Scene","getAllAnimatablesByTarget"),Qo.prototype.stopAllAnimations??=Ne("Scene","stopAllAnimations"),Qo.prototype.getSoundByName??=Ne("Scene","getSoundByName"),Qo.prototype.createOrUpdateSelectionOctree??=Ne("Scene","createOrUpdateSelectionOctree"),Qo.prototype.createDefaultLight??=Ne("Scene","createDefaultLight"),Qo.prototype.createDefaultCamera??=Ne("Scene","createDefaultCamera"),Qo.prototype.createDefaultCameraOrLight??=Ne("Scene","createDefaultCameraOrLight"),Qo.prototype.createDefaultSkybox??=Ne("Scene","createDefaultSkybox"),Qo.prototype.createDefaultEnvironment??=Ne("Scene","createDefaultEnvironment"),Qo.prototype.createDefaultVRExperience??=Ne("Scene","createDefaultVRExperience"),Qo.prototype.createDefaultXRExperienceAsync??=Ne("Scene","createDefaultXRExperienceAsync"),Qo.prototype.getGlowLayerByName??=Ne("Scene","getGlowLayerByName"),Qo.prototype.getHighlightLayerByName??=Ne("Scene","getHighlightLayerByName"),Qo.prototype.getSelectionOutlineLayerByName??=Ne("Scene","getSelectionOutlineLayerByName"),Qo.prototype.removeLensFlareSystem??=Ne("Scene","removeLensFlareSystem"),Qo.prototype.addLensFlareSystem??=Ne("Scene","addLensFlareSystem"),Qo.prototype.getLensFlareSystemByName??=Ne("Scene","getLensFlareSystemByName"),Qo.prototype.getLensFlareSystemByID??=Ne("Scene","getLensFlareSystemByID"),Qo.prototype.getLensFlareSystemById??=Ne("Scene","getLensFlareSystemById"),Qo.prototype.getPhysicsEngine??=Ne("Scene","getPhysicsEngine"),Qo.prototype.enablePhysics??=Ne("Scene","enablePhysics"),Qo.prototype.disablePhysicsEngine??=Ne("Scene","disablePhysicsEngine"),Qo.prototype.isPhysicsEnabled??=Ne("Scene","isPhysicsEnabled"),Qo.prototype.deleteCompoundImpostor??=Ne("Scene","deleteCompoundImpostor"),Qo.prototype.removeReflectionProbe??=Ne("Scene","removeReflectionProbe"),Qo.prototype.addReflectionProbe??=Ne("Scene","addReflectionProbe"),Qo.prototype.getBoundingBoxRenderer??=Ne("Scene","getBoundingBoxRenderer"),Qo.prototype.enableDepthRenderer??=Ne("Scene","enableDepthRenderer"),Qo.prototype.disableDepthRenderer??=Ne("Scene","disableDepthRenderer"),Qo.prototype.enableFluidRenderer??=Ne("Scene","enableFluidRenderer"),Qo.prototype.disableFluidRenderer??=Ne("Scene","disableFluidRenderer"),Qo.prototype.enableGeometryBufferRenderer??=Ne("Scene","enableGeometryBufferRenderer"),Qo.prototype.disableGeometryBufferRenderer??=Ne("Scene","disableGeometryBufferRenderer"),Qo.prototype.enableIblCdfGenerator??=Ne("Scene","enableIblCdfGenerator"),Qo.prototype.disableIblCdfGenerator??=Ne("Scene","disableIblCdfGenerator"),Qo.prototype.getOutlineRenderer??=Ne("Scene","getOutlineRenderer"),Qo.prototype.enablePrePassRenderer??=Ne("Scene","enablePrePassRenderer"),Qo.prototype.disablePrePassRenderer??=Ne("Scene","disablePrePassRenderer"),Qo.prototype.enableSubSurfaceForPrePass??=Ne("Scene","enableSubSurfaceForPrePass"),Qo.prototype.disableSubSurfaceForPrePass??=Ne("Scene","disableSubSurfaceForPrePass"),Qo.prototype.pickSprite??=Ne("Scene","pickSprite"),Qo.prototype.pickSpriteWithRay??=Ne("Scene","pickSpriteWithRay"),Qo.prototype.multiPickSprite??=Ne("Scene","multiPickSprite"),Qo.prototype.multiPickSpriteWithRay??=Ne("Scene","multiPickSpriteWithRay"),Qo.prototype.setPointerOverSprite??=Ne("Scene","setPointerOverSprite"),Qo.prototype.getPointerOverSprite??=Ne("Scene","getPointerOverSprite"),Object.getOwnPropertyDescriptor(Qo.prototype,"mainSoundTrack")||Object.defineProperty(Qo.prototype,"mainSoundTrack",Ue(0,"mainSoundTrack")),Object.getOwnPropertyDescriptor(Qo.prototype,"soundTracks")||Object.defineProperty(Qo.prototype,"soundTracks",Ue(0,"soundTracks")),Object.getOwnPropertyDescriptor(Qo.prototype,"audioEnabled")||Object.defineProperty(Qo.prototype,"audioEnabled",Ue(0,"audioEnabled")),Object.getOwnPropertyDescriptor(Qo.prototype,"headphone")||Object.defineProperty(Qo.prototype,"headphone",Ue(0,"headphone")),Object.getOwnPropertyDescriptor(Qo.prototype,"audioListenerPositionProvider")||Object.defineProperty(Qo.prototype,"audioListenerPositionProvider",Ue(0,"audioListenerPositionProvider")),Object.getOwnPropertyDescriptor(Qo.prototype,"audioListenerRotationProvider")||Object.defineProperty(Qo.prototype,"audioListenerRotationProvider",Ue(0,"audioListenerRotationProvider")),Object.getOwnPropertyDescriptor(Qo.prototype,"audioPositioningRefreshRate")||Object.defineProperty(Qo.prototype,"audioPositioningRefreshRate",Ue(0,"audioPositioningRefreshRate")),Object.getOwnPropertyDescriptor(Qo.prototype,"selectionOctree")||Object.defineProperty(Qo.prototype,"selectionOctree",Ue(0,"selectionOctree")),Object.getOwnPropertyDescriptor(Qo.prototype,"debugLayer")||Object.defineProperty(Qo.prototype,"debugLayer",Ue(0,"debugLayer")),Object.getOwnPropertyDescriptor(Qo.prototype,"gamepadManager")||Object.defineProperty(Qo.prototype,"gamepadManager",Ue(0,"gamepadManager")),Object.getOwnPropertyDescriptor(Qo.prototype,"simplificationQueue")||Object.defineProperty(Qo.prototype,"simplificationQueue",Ue(0,"simplificationQueue")),Object.getOwnPropertyDescriptor(Qo.prototype,"onBeforePhysicsObservable")||Object.defineProperty(Qo.prototype,"onBeforePhysicsObservable",Ue(0,"onBeforePhysicsObservable")),Object.getOwnPropertyDescriptor(Qo.prototype,"onAfterPhysicsObservable")||Object.defineProperty(Qo.prototype,"onAfterPhysicsObservable",Ue(0,"onAfterPhysicsObservable")),Object.getOwnPropertyDescriptor(Qo.prototype,"reflectionProbes")||Object.defineProperty(Qo.prototype,"reflectionProbes",Ue(0,"reflectionProbes")),Object.getOwnPropertyDescriptor(Qo.prototype,"forceShowBoundingBoxes")||Object.defineProperty(Qo.prototype,"forceShowBoundingBoxes",Ue(0,"forceShowBoundingBoxes")),Object.getOwnPropertyDescriptor(Qo.prototype,"depthPeelingRenderer")||Object.defineProperty(Qo.prototype,"depthPeelingRenderer",Ue(0,"depthPeelingRenderer")),Object.getOwnPropertyDescriptor(Qo.prototype,"useOrderIndependentTransparency")||Object.defineProperty(Qo.prototype,"useOrderIndependentTransparency",Ue(0,"useOrderIndependentTransparency")),Object.getOwnPropertyDescriptor(Qo.prototype,"fluidRenderer")||Object.defineProperty(Qo.prototype,"fluidRenderer",Ue(0,"fluidRenderer")),Object.getOwnPropertyDescriptor(Qo.prototype,"geometryBufferRenderer")||Object.defineProperty(Qo.prototype,"geometryBufferRenderer",Ue(0,"geometryBufferRenderer")),Object.getOwnPropertyDescriptor(Qo.prototype,"iblCdfGenerator")||Object.defineProperty(Qo.prototype,"iblCdfGenerator",Ue(0,"iblCdfGenerator")),Object.getOwnPropertyDescriptor(Qo.prototype,"prePassRenderer")||Object.defineProperty(Qo.prototype,"prePassRenderer",Ue(0,"prePassRenderer")),Object.getOwnPropertyDescriptor(Qo.prototype,"subSurfaceConfiguration")||Object.defineProperty(Qo.prototype,"subSurfaceConfiguration",Ue(0,"subSurfaceConfiguration")),Object.getOwnPropertyDescriptor(Qo.prototype,"spriteManagers")||Object.defineProperty(Qo.prototype,"spriteManagers",Ue(0,"spriteManagers")),Object.getOwnPropertyDescriptor(Qo.prototype,"onBeforeSpritesRenderingObservable")||Object.defineProperty(Qo.prototype,"onBeforeSpritesRenderingObservable",Ue(0,"onBeforeSpritesRenderingObservable")),Object.getOwnPropertyDescriptor(Qo.prototype,"onAfterSpritesRenderingObservable")||Object.defineProperty(Qo.prototype,"onAfterSpritesRenderingObservable",Ue(0,"onAfterSpritesRenderingObservable")),function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(eh||(eh={}));const th=new c,sh={};function ih(){return sh[".babylon"]}function rh(e,t){const s=sh[e];return s||(a.Warn("Unable to find a plugin to load "+e+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),t?ih():void 0)}function nh(e,i,r){const n=function(e,t,s){let i="Unable to load from "+(e.rawData?"binary data":e.url);return t?i+=`: ${t}`:s&&(i+=`: ${s}`),i}(e,i,r);return new s(n,t.SceneLoaderError,r)}function ah(e){return e instanceof Error?e.message:String(e)}function oh(e,i){return i instanceof s&&i.errorCode===t.SceneLoaderError?i:nh(e,ah(i),i)}function hh(e,t){if(!function(e){const t=e;return!!t.importMesh||!!t.load||!!t.loadAssetContainer}(e))return e;const s=e=>{let s;const i=e((e,t)=>{s={message:e,exception:t}});if(!i)throw nh(t,s?.message,s?.exception);return i};return{name:e.name,extensions:e.extensions,importMeshAsync:async(t,i,r,n)=>{const a=[],o=[],h=[];return s(s=>e.importMesh(t,i,r,n,a,o,h,s)),{meshes:a,particleSystems:o,skeletons:h,animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}},loadAsync:async(t,i,r)=>{s(s=>e.load(t,i,r,s))},loadAssetContainerAsync:async(t,i,r)=>s(s=>e.loadAssetContainer(t,i,r,s))}}function lh(e){if(e)return t=>{try{e(t)}catch(e){a.Warn("Error in onProgress callback: "+ah(e))}}}async function ch(e,t,s,i,r,n){const a="data:"===(o=e.url).substring(0,5)?o.substring(5):null;var o;if(e.rawData&&!i)throw new Error("When using ArrayBufferView to load data the file extension must be provided.");const h=a||i?"":function(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const s=e.lastIndexOf(".");return e.substring(s,e.length).toLowerCase()}(e.url);let l,c=i?rh(i,!0):a?function(e){for(const t in sh){const s=sh[t].plugin;if(s.canDirectLoad&&s.canDirectLoad(e))return sh[t]}return ih()}(e.url):rh(h,!1);if(!c&&h){if(e.url&&!e.url.startsWith("blob:")){const t=await async function(e,t){const s=t.method||"GET";return await new Promise((i,r)=>{const n=new at;n.addEventListener("readystatechange",()=>{if(4==n.readyState)if(200==n.status){const e={};if(t.responseHeaders)for(const s of t.responseHeaders)e[s]=n.getResponseHeader(s)||"";i({response:n.response,headerValues:e})}else r(`Unable to fetch data from ${e}. Error code: ${n.status}`)}),n.open(s,e),n.send()})}(e.url,{method:"HEAD",responseHeaders:["Content-Type"]}),s=t.headerValues?t.headerValues["Content-Type"]:"";s&&(c=function(e){for(const t in sh){const s=sh[t];if(s.mimeType===e)return s}}(s))}c||(c=ih())}if(!c)throw new Error(`No plugin or fallback for ${i??e.url}`);if(!1===n?.[c.plugin.name]?.enabled)throw new Error(`The '${c.plugin.name}' plugin is disabled via the loader options passed to the loading operation.`);if(e.rawData&&!c.isBinary)throw new Error("Loading from ArrayBufferView can not be used with plugins that don't support binary loading.");if(c.plugin.createPlugin){const t=c.plugin;try{const e=t.createPlugin(n??{});l=e instanceof Promise?await e:e}catch(t){throw nh(e,"Error instantiating plugin.",t)}}else l=c.plugin;if(!l)throw new Error(`The loader plugin corresponding to the '${i}' file type has not been found. If using es6, please import the plugin you wish to use before.`);if(th.notifyObservers(l),a&&(l.canDirectLoad&&l.canDirectLoad(e.url)||!Es(e.url))){if(l.directLoad){let s;try{s=await l.directLoad(t,a)}catch(t){throw nh(e,"Error in directLoad of _loadData: "+t,t)}return{plugin:l,data:s}}return{plugin:l,data:a}}const u=c.isBinary;return await new Promise((i,n)=>{let a=null,o=!1;const h=l.onDisposeObservable?.add(()=>{o=!0,a&&(a.abort(),a=null),d(nh(e,"Loading was aborted because the plugin was disposed."))}),c=()=>{h&&l.onDisposeObservable?.remove(h)},d=e=>{c(),n(e)},_=(s,r)=>{var n;t.isDisposed?d(nh(e,"Scene has been disposed")):(n={plugin:l,data:s,responseURL:r},c(),i(n))},p=()=>{if(o)return;const i=(t,s)=>{d(nh(e,t?.statusText,s))};if(l.loadFile||!e.rawData)try{a=l.loadFile?l.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,_,s,u,i,r):t._loadFile(e.file||e.url,_,s,!0,u,i)}catch(t){d(nh(e,void 0,t))}else d(nh(e,"Plugin does not support loading ArrayBufferView."))},f=t.getEngine();let g=!e.file&&!e.rawData&&f.enableOfflineSupport;if(g){let s=!1;for(const i of t.disableOfflineSupportExceptionRules)if(i.test(e.url)){s=!0;break}g=!s}if(g&&Ti.OfflineProviderFactory)try{t.offlineProvider=Ti.OfflineProviderFactory(e.url,p,f.disableManifestCheck)}catch(t){d(nh(e,void 0,t))}else p()})}function uh(e,t){let s,i,r=null,n=null;if(t)if(t.name)s=`file:${t.name}`,i=t.name,r=t;else if(ArrayBuffer.isView(t))s="",i=vs(),n=t;else if(t.startsWith("data:"))s=t,i="";else if(e){const r=t;if("/"===r.substring(0,1))return Fs.Error("Wrong sceneFilename parameter"),null;s=e+r,i=r}else s=t,i=Fs.GetFilename(t),e=Fs.GetFolderPath(t);else s=e,i=Fs.GetFilename(e),e=Fs.GetFolderPath(e);return{url:s,rootUrl:e,name:i,file:r,rawData:n}}function dh(e){if("string"==typeof e.extensions){const t=e.extensions;sh[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions,s=Object.keys(t);for(const i of s)sh[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary,mimeType:t[i].mimeType}}}async function _h(e,t,s){const{meshNames:i,rootUrl:r="",onProgress:n,pluginExtension:a,name:o,pluginOptions:h}=s??{};return await async function(e,t,s="",i=ee.LastCreatedScene,r,n,a="",o={}){if(!i)throw new Error("No scene available to import mesh to");const h=uh(t,s);if(!h)throw new Error("Cannot load file: a valid scene filename or root url was not provided.");const l={};i.addPendingData(l);const c=lh(r);try{const{plugin:t,data:s,responseURL:r}=await ch(h,i,c,n??null,a,o);let l;t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,r));try{l=await hh(t,h).importMeshAsync(e,i,s,h.rootUrl,c,h.name)}catch(e){throw oh(h,e)}return i.loadingPluginName=t.name,i.importedMeshesFiles.push(h.url),l}finally{i.removePendingData(l)}}(i,r,e,t,n,a,o,h)}async function ph(e,t,s){const{rootUrl:i="",onProgress:r,pluginExtension:n,name:a,pluginOptions:o}=s??{};return await async function(e,t="",s=ee.LastCreatedScene,i,r,n="",a={}){if(!s)throw new Error("No scene available to load asset container to");const o=uh(e,t);if(!o)throw new Error("Cannot load file: a valid scene filename or root url was not provided.");const h={};s.addPendingData(h);const l=lh(i);try{const{plugin:e,data:t}=await ch(o,s,l,r??null,n,a),i=hh(e,o);if(!i.loadAssetContainerAsync)throw nh(o,"LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");let h;try{h=await i.loadAssetContainerAsync(s,t,o.rootUrl,l,o.name)}catch(e){throw oh(o,e)}return h.populateRootNodes(),s.loadingPluginName=e.name,h}finally{s.removePendingData(h)}}(i,e,t,r,n,a,o)}class fh{constructor(e){if(this.VERTEXOUTPUT_INVARIANT=!1,this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)-1===this._keys.indexOf(e)&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;t<this._keys.length;t++){const s=this._keys[t];if(this[s]!==e[s])return!1}return!0}cloneTo(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(let t=0;t<this._keys.length;t++){const s=this._keys[t];e[s]=this[s]}}reset(){for(const e of this._keys)this._setDefaultValue(e)}_setDefaultValue(e){const t=this._externalProperties?.[e]?.type??typeof this[e],s=this._externalProperties?.[e]?.default;switch(t){case"number":this[e]=s??0;break;case"string":this[e]=s??"";break;default:this[e]=s??!1}}toString(){let e="";for(let t=0;t<this._keys.length;t++){const s=this._keys[t],i=this[s];switch(typeof i){case"number":case"string":e+="#define "+s+" "+i+"\n";break;default:i&&(e+="#define "+s+"\n")}}return e}}class gh extends Cn{constructor(e,t,s=!0,i=!1){super(e,t,void 0,i),this._normalMatrix=new Ie,this._storeEffectOnSubMeshes=s}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return!!e&&(!this._storeEffectOnSubMeshes||(!e.subMeshes||0===e.subMeshes.length||this.isReadyForSubMesh(e,e.subMeshes[0],t)))}_isReadyForSubMesh(e){const t=e.materialDefines;return!(this.checkReadyOnEveryCall||!e.effect||!t||t._renderId!==this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,s){super._afterBind(e,t,s),this.getScene()._cachedEffect=t,s?s._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,s,i=1){return s._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,i)}dispose(e,t,s){this._activeEffect=void 0,super.dispose(e,t,s)}}function mh(e){return class extends e{constructor(){super(...arguments),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1}}}class Th{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const s=this._mesh.getScene();for(let e=0;e<s.meshes.length;e++){const i=s.meshes[e];if(i.material){if(i.computeBonesUsingShaders&&0!==i.numBoneInfluencers)if(i.material.getEffect()===t)i.computeBonesUsingShaders=!1;else if(i.subMeshes)for(const e of i.subMeshes){if(e.effect===t){i.computeBonesUsingShaders=!1;break}}}else!this._mesh.material&&i.computeBonesUsingShaders&&i.numBoneInfluencers>0&&(i.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let s=0;s<t.length;s++)e=e.replace("#define "+t[s],"");this._currentRank++}return e}}function Eh(e){return class extends e{constructor(...e){super(...e);const t=new.target;if(!t[Symbol.metadata]){const e=Object.getPrototypeOf(t)?.[Symbol.metadata];t[Symbol.metadata]=e?Object.create(e):{}}const s=C(t[Symbol.metadata]);s._imageProcessingConfiguration||(s._imageProcessingConfiguration={type:9,sourceName:void 0})}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsImageProcessingDirty&&this._markAllSubMeshesAsImageProcessingDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),!e&&this.getScene?this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration:e&&(this._imageProcessingConfiguration=e),this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty&&this._markAllSubMeshesAsImageProcessingDirty()})))}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}}}class Rh extends fh{}class bh extends(mh(Rh)){constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}}class Ah extends(Eh(gh)){}let yh=(()=>{var e,t,s,i,r,n,o,h,l,c,u,d,_,p,f,g,m,T,E;let R,y,S,v,I,P,C,O,D,B,U,G,V,H,z,W,X,K,Y,j,q,$,Z,Q,J,ee,te,se,ie,re,ne,ae,oe,he,le,ce,ue,de,_e,pe=Ah,fe=[],ge=[],me=[],Te=[],Ee=[],Re=[],be=[],Ae=[],ye=[],Me=[],ve=[],Ie=[],Pe=[],Oe=[],De=[],we=[],Le=[],Fe=[],Ne=[],Be=[],Ue=[],ke=[],Ge=[],Ve=[],He=[],ze=[],We=[],Ke=[],Ye=[],je=[],qe=[],Ze=[],Qe=[],Je=[],et=[],tt=[],st=[],it=[],rt=[],nt=[],at=[],ot=[],ht=[],lt=[],ct=[],ut=[],_t=[],pt=[],ft=[],gt=[],mt=[],Tt=[],Et=[],Rt=[],bt=[],At=[],yt=[],Mt=[],xt=[],St=[],vt=[],It=[],Pt=[],Ct=[],Ot=[],Dt=[],wt=[],Lt=[],Ft=[],Nt=[],Bt=[],Ut=[],kt=[],Gt=[],Vt=[],Ht=[],zt=[],Wt=[];return e=class extends pe{get primaryColor(){return M(this,t,"f")}set primaryColor(e){x(this,t,e,"f")}get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get reflectionTexture(){return M(this,s,"f")}set reflectionTexture(e){x(this,s,e,"f")}get reflectionBlur(){return M(this,i,"f")}set reflectionBlur(e){x(this,i,e,"f")}get diffuseTexture(){return M(this,r,"f")}set diffuseTexture(e){x(this,r,e,"f")}get shadowLights(){return M(this,n,"f")}set shadowLights(e){x(this,n,e,"f")}get shadowLevel(){return M(this,o,"f")}set shadowLevel(e){x(this,o,e,"f")}get sceneCenter(){return M(this,h,"f")}set sceneCenter(e){x(this,h,e,"f")}get opacityFresnel(){return M(this,l,"f")}set opacityFresnel(e){x(this,l,e,"f")}get reflectionFresnel(){return M(this,c,"f")}set reflectionFresnel(e){x(this,c,e,"f")}get reflectionFalloffDistance(){return M(this,u,"f")}set reflectionFalloffDistance(e){x(this,u,e,"f")}get reflectionAmount(){return M(this,d,"f")}set reflectionAmount(e){x(this,d,e,"f")}get reflectionReflectance0(){return M(this,_,"f")}set reflectionReflectance0(e){x(this,_,e,"f")}get reflectionReflectance90(){return M(this,p,"f")}set reflectionReflectance90(e){x(this,p,e,"f")}set reflectionStandardFresnelWeight(t){let s=t;s<.5?(s*=2,this.reflectionReflectance0=e.StandardReflectance0*s,this.reflectionReflectance90=e.StandardReflectance90*s):(s=2*s-1,this.reflectionReflectance0=e.StandardReflectance0+(1-e.StandardReflectance0)*s,this.reflectionReflectance90=e.StandardReflectance90+(1-e.StandardReflectance90)*s)}get useRGBColor(){return M(this,f,"f")}set useRGBColor(e){x(this,f,e,"f")}get enableNoise(){return M(this,g,"f")}set enableNoise(e){x(this,g,e,"f")}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}get maxSimultaneousLights(){return M(this,m,"f")}set maxSimultaneousLights(e){x(this,m,e,"f")}get shadowOnly(){return M(this,T,"f")}set shadowOnly(e){x(this,T,e,"f")}get enableGroundProjection(){return M(this,E,"f")}set enableGroundProjection(e){x(this,E,e,"f")}constructor(e,a,R=!1){super(e,a,void 0,R),this._primaryColor=A(this,fe,void 0),t.set(this,(A(this,ge),A(this,me,Xe.White()))),this.__perceptualColor=(A(this,Te),A(this,Ee,void 0)),this._primaryColorShadowLevel=(A(this,Re),A(this,be,0)),this._primaryColorHighlightLevel=(A(this,Ae),A(this,ye,0)),this._reflectionTexture=(A(this,Me),A(this,ve,void 0)),s.set(this,(A(this,Ie),A(this,Pe,null))),this._reflectionBlur=(A(this,Oe),A(this,De,void 0)),i.set(this,(A(this,we),A(this,Le,0))),this._diffuseTexture=(A(this,Fe),A(this,Ne,void 0)),r.set(this,(A(this,Be),A(this,Ue,null))),this._shadowLights=(A(this,ke),null),n.set(this,A(this,Ge,null)),this._shadowLevel=(A(this,Ve),A(this,He,void 0)),o.set(this,(A(this,ze),A(this,We,0))),this._sceneCenter=(A(this,Ke),A(this,Ye,void 0)),h.set(this,(A(this,je),A(this,qe,xe.Zero()))),this._opacityFresnel=(A(this,Ze),A(this,Qe,void 0)),l.set(this,(A(this,Je),A(this,et,!0))),this._reflectionFresnel=(A(this,tt),A(this,st,void 0)),c.set(this,(A(this,it),A(this,rt,!1))),this._reflectionFalloffDistance=(A(this,nt),A(this,at,void 0)),u.set(this,(A(this,ot),A(this,ht,0))),this._reflectionAmount=(A(this,lt),A(this,ct,void 0)),d.set(this,(A(this,ut),A(this,_t,1))),this._reflectionReflectance0=(A(this,pt),A(this,ft,void 0)),_.set(this,(A(this,gt),A(this,mt,.05))),this._reflectionReflectance90=(A(this,Tt),A(this,Et,void 0)),p.set(this,(A(this,Rt),A(this,bt,.5))),this._useRGBColor=(A(this,At),A(this,yt,void 0)),f.set(this,(A(this,Mt),A(this,xt,!0))),this._enableNoise=(A(this,St),A(this,vt,void 0)),g.set(this,(A(this,It),A(this,Pt,!1))),this._fovMultiplier=(A(this,Ct),1),this.useEquirectangularFOV=!1,this._maxSimultaneousLights=A(this,Ot,4),m.set(this,(A(this,Dt),A(this,wt,4))),this._shadowOnly=(A(this,Lt),A(this,Ft,!1)),T.set(this,(A(this,Nt),A(this,Bt,!1))),this.switchToBGR=(A(this,Ut),!1),this._enableGroundProjection=!1,E.set(this,A(this,kt,!1)),this.projectedGroundRadius=(A(this,Gt),A(this,Vt,1e3)),this.projectedGroundHeight=(A(this,Ht),A(this,zt,10)),this._renderTargets=(A(this,Wt),new Ws(16)),this._reflectionControls=Se.Zero(),this._white=Xe.White(),this._primaryShadowColor=Xe.Black(),this._primaryHighlightColor=Xe.Black(),this._shadersLoaded=!1,this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,s=!1){const i=t._drawWrapper;if(i.effect&&this.isFrozen&&i._wasPreviouslyReady&&i._wasPreviouslyUsingInstances===s)return!0;t.materialDefines||(t.materialDefines=new bh);const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(gn(r,e,n,!1,this._maxSimultaneousLights),n._needNormals=!0,!fn(r,e,this._maxSimultaneousLights))return!1;if(yn(r,n),n._areTexturesDirty){if(n._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(n.TEXTURELODSUPPORT=!0),this._diffuseTexture&&Xr.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;rn(this._diffuseTexture,n,"DIFFUSE"),n.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,n.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,n.OPACITYFRESNEL=this._opacityFresnel}else n.DIFFUSE=!1,n.DIFFUSEDIRECTUV=0,n.DIFFUSEHASALPHA=!1,n.GAMMADIFFUSE=!1,n.OPACITYFRESNEL=!1;const e=this._reflectionTexture;if(mn(r,e,n),e&&Xr.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;n.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,n.REFLECTIONBGR=this.switchToBGR,n.REFLECTIONBLUR=this._reflectionBlur>0,this.reflectionFresnel?(n.REFLECTIONFRESNEL=!0,n.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1)}else n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1,n.REFLECTIONBLUR=!1}n.PREMULTIPLYALPHA=this.alphaMode===dt.ALPHA_PREMULTIPLIED||this.alphaMode===dt.ALPHA_PREMULTIPLIED_PORTERDUFF,n.USERGBCOLOR=this._useRGBColor,n.NOISE=this._enableNoise}if(n._areLightsDirty&&(n.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),n.BACKMAT_SHADOWONLY=this._shadowOnly),n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n)}if(n._areMiscDirty&&(n.REFLECTIONMAP_3D&&this._enableGroundProjection?(n.PROJECTED_GROUND=!0,n.REFLECTIONMAP_SKYBOX=!0):n.PROJECTED_GROUND=!1),pn(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this.needAlphaTestingForMesh(e),n,void 0,void 0,void 0,this._isVertexOutputInvariant),En(r,o,this,n,s,null,t.getRenderingMesh().hasThinInstances),An(e,n,!1,!0,!1)&&e&&(r.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(Gi.NormalKind)||(e.createNormals(!0),a.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),n.isDirty){n.markAsProcessed(),r.resetCachedMaterial();const s=new Th;n.FOG&&s.addFallback(0,"FOG"),n.POINTSIZE&&s.addFallback(1,"POINTSIZE"),n.MULTIVIEW&&s.addFallback(0,"MULTIVIEW"),_n(n,s,this._maxSimultaneousLights);const i=[Gi.PositionKind];n.NORMAL&&i.push(Gi.NormalKind),n.UV1&&i.push(Gi.UVKind),n.UV2&&i.push(Gi.UV2Kind),un(i,e,n,s),dn(i,n);const a=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];Vr(a);const h=["diffuseSampler"];vn(a,h,!1);const l=["Material","Scene"];Eo&&(Eo.PrepareUniforms(a,n),Eo.PrepareSamplers(h,n)),In({uniformsNames:a,uniformBuffersNames:l,samplers:h,defines:n,maxSimultaneousLights:this._maxSimultaneousLights,shaderLanguage:this._shaderLanguage});const c=n.toString(),u=r.getEngine().createEffect("background",{attributes:i,uniformsNames:a,uniformBuffersNames:l,samplers:h,defines:c,fallbacks:s,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights},shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{1===this.shaderLanguage?await Promise.all([import("./background.vertex-BLYws9du.esm.min.js"),import("./background.fragment-BKYcxZL9.esm.min.js")]):await Promise.all([import("./background.vertex-CpiwmUIZ.esm.min.js"),import("./background.fragment-D3DnUztw.esm.min.js")]),this._shadersLoaded=!0}},o);t.setEffect(u,n,this._materialContext),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady())&&(n._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,i._wasPreviouslyUsingInstances=s,this._checkScenePerformancePriority(),!0)}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),Pn(this._uniformBuffer,!0,!1,!1),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,s){const i=this.getScene(),r=s.materialDefines;if(!r)return;const n=s.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),on(t,this._activeEffect);const a=this._mustRebind(i,n,s,t.visibility),o=i.getEngine()._features.needToAlwaysBindUniformBuffers;if(a){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);const e=this._reflectionTexture;if(this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync&&!s._drawWrapper._forceRebindOnNextCall||(i.texturesEnabled&&(this._diffuseTexture&&Xr.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),nn(this._diffuseTexture,this._uniformBuffer,"diffuse")),tn(i,r,this._uniformBuffer,Xe.White(),e,!1,!0,!1,!1,!1,!1,this._reflectionBlur)),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),r.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),r.REFLECTIONFRESNEL&&this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w),r.REFLECTIONFRESNEL&&r.REFLECTIONFALLOFF||r.OPACITYFRESNEL){const e=Ce.Vector3[0].copyFrom(this.sceneCenter).subtractInPlace(i.floatingOriginOffset);this._uniformBuffer.updateFloat3("vBackgroundCenter",e.x,e.y,e.z)}i.texturesEnabled&&(this._diffuseTexture&&Xr.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&Xr.ReflectionTextureEnabled&&sn(i,r,this._uniformBuffer,e),r.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),zr(this._activeEffect,this,i),i.bindEyePosition(n)}else o&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);(a||!this.isFrozen||o)&&i.lightsEnabled&&cn(i,t,this._activeEffect,r,this._maxSimultaneousLights),!a&&this.isFrozen||(this.bindView(n),qr(i,t,this._activeEffect,!0),this._useLogarithmicDepth&&Kr(r,n,i),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,s),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||(this._reflectionTexture===e||this._diffuseTexture===e)}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(t){return $e.Clone(()=>new e(t,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(t,s,i){return $e.Parse(()=>new e(t.name,s),t,s,i)}},t=new WeakMap,s=new WeakMap,i=new WeakMap,r=new WeakMap,n=new WeakMap,o=new WeakMap,h=new WeakMap,l=new WeakMap,c=new WeakMap,u=new WeakMap,d=new WeakMap,_=new WeakMap,p=new WeakMap,f=new WeakMap,g=new WeakMap,m=new WeakMap,T=new WeakMap,E=new WeakMap,(()=>{const t="function"==typeof Symbol&&Symbol.metadata?Object.create(pe[Symbol.metadata]??null):void 0;R=[N()],y=[w("_markAllSubMeshesAsLightsDirty")],S=[N()],v=[L()],I=[L()],P=[F()],C=[w("_markAllSubMeshesAsTexturesDirty")],O=[L()],D=[w("_markAllSubMeshesAsTexturesDirty")],B=[F()],U=[w("_markAllSubMeshesAsTexturesDirty")],G=[w("_markAllSubMeshesAsTexturesDirty")],V=[L()],H=[w("_markAllSubMeshesAsTexturesDirty")],z=[k()],W=[w("_markAllSubMeshesAsTexturesDirty")],X=[L()],K=[w("_markAllSubMeshesAsTexturesDirty")],Y=[L()],j=[w("_markAllSubMeshesAsTexturesDirty")],q=[L()],$=[w("_markAllSubMeshesAsTexturesDirty")],Z=[L()],Q=[w("_markAllSubMeshesAsTexturesDirty")],J=[L()],ee=[w("_markAllSubMeshesAsTexturesDirty")],te=[L()],se=[w("_markAllSubMeshesAsTexturesDirty")],ie=[L()],re=[w("_markAllSubMeshesAsTexturesDirty")],ne=[L()],ae=[w("_markAllSubMeshesAsTexturesDirty")],oe=[L()],he=[w("_markAllSubMeshesAsTexturesDirty")],le=[L()],ce=[w("_markAllSubMeshesAsLightsDirty")],ue=[L(),w("_markAllSubMeshesAsMiscDirty")],de=[L()],_e=[L()],b(e,null,y,{kind:"accessor",name:"primaryColor",static:!1,private:!1,access:{has:e=>"primaryColor"in e,get:e=>e.primaryColor,set:(e,t)=>{e.primaryColor=t}},metadata:t},me,Te),b(e,null,C,{kind:"accessor",name:"reflectionTexture",static:!1,private:!1,access:{has:e=>"reflectionTexture"in e,get:e=>e.reflectionTexture,set:(e,t)=>{e.reflectionTexture=t}},metadata:t},Pe,Oe),b(e,null,D,{kind:"accessor",name:"reflectionBlur",static:!1,private:!1,access:{has:e=>"reflectionBlur"in e,get:e=>e.reflectionBlur,set:(e,t)=>{e.reflectionBlur=t}},metadata:t},Le,Fe),b(e,null,U,{kind:"accessor",name:"diffuseTexture",static:!1,private:!1,access:{has:e=>"diffuseTexture"in e,get:e=>e.diffuseTexture,set:(e,t)=>{e.diffuseTexture=t}},metadata:t},Ue,ke),b(e,null,G,{kind:"accessor",name:"shadowLights",static:!1,private:!1,access:{has:e=>"shadowLights"in e,get:e=>e.shadowLights,set:(e,t)=>{e.shadowLights=t}},metadata:t},Ge,Ve),b(e,null,H,{kind:"accessor",name:"shadowLevel",static:!1,private:!1,access:{has:e=>"shadowLevel"in e,get:e=>e.shadowLevel,set:(e,t)=>{e.shadowLevel=t}},metadata:t},We,Ke),b(e,null,W,{kind:"accessor",name:"sceneCenter",static:!1,private:!1,access:{has:e=>"sceneCenter"in e,get:e=>e.sceneCenter,set:(e,t)=>{e.sceneCenter=t}},metadata:t},qe,Ze),b(e,null,K,{kind:"accessor",name:"opacityFresnel",static:!1,private:!1,access:{has:e=>"opacityFresnel"in e,get:e=>e.opacityFresnel,set:(e,t)=>{e.opacityFresnel=t}},metadata:t},et,tt),b(e,null,j,{kind:"accessor",name:"reflectionFresnel",static:!1,private:!1,access:{has:e=>"reflectionFresnel"in e,get:e=>e.reflectionFresnel,set:(e,t)=>{e.reflectionFresnel=t}},metadata:t},rt,nt),b(e,null,$,{kind:"accessor",name:"reflectionFalloffDistance",static:!1,private:!1,access:{has:e=>"reflectionFalloffDistance"in e,get:e=>e.reflectionFalloffDistance,set:(e,t)=>{e.reflectionFalloffDistance=t}},metadata:t},ht,lt),b(e,null,Q,{kind:"accessor",name:"reflectionAmount",static:!1,private:!1,access:{has:e=>"reflectionAmount"in e,get:e=>e.reflectionAmount,set:(e,t)=>{e.reflectionAmount=t}},metadata:t},_t,pt),b(e,null,ee,{kind:"accessor",name:"reflectionReflectance0",static:!1,private:!1,access:{has:e=>"reflectionReflectance0"in e,get:e=>e.reflectionReflectance0,set:(e,t)=>{e.reflectionReflectance0=t}},metadata:t},mt,Tt),b(e,null,se,{kind:"accessor",name:"reflectionReflectance90",static:!1,private:!1,access:{has:e=>"reflectionReflectance90"in e,get:e=>e.reflectionReflectance90,set:(e,t)=>{e.reflectionReflectance90=t}},metadata:t},bt,At),b(e,null,re,{kind:"accessor",name:"useRGBColor",static:!1,private:!1,access:{has:e=>"useRGBColor"in e,get:e=>e.useRGBColor,set:(e,t)=>{e.useRGBColor=t}},metadata:t},xt,St),b(e,null,ae,{kind:"accessor",name:"enableNoise",static:!1,private:!1,access:{has:e=>"enableNoise"in e,get:e=>e.enableNoise,set:(e,t)=>{e.enableNoise=t}},metadata:t},Pt,Ct),b(e,null,he,{kind:"accessor",name:"maxSimultaneousLights",static:!1,private:!1,access:{has:e=>"maxSimultaneousLights"in e,get:e=>e.maxSimultaneousLights,set:(e,t)=>{e.maxSimultaneousLights=t}},metadata:t},wt,Lt),b(e,null,ce,{kind:"accessor",name:"shadowOnly",static:!1,private:!1,access:{has:e=>"shadowOnly"in e,get:e=>e.shadowOnly,set:(e,t)=>{e.shadowOnly=t}},metadata:t},Bt,Ut),b(e,null,ue,{kind:"accessor",name:"enableGroundProjection",static:!1,private:!1,access:{has:e=>"enableGroundProjection"in e,get:e=>e.enableGroundProjection,set:(e,t)=>{e.enableGroundProjection=t}},metadata:t},kt,Gt),b(null,null,R,{kind:"field",name:"_primaryColor",static:!1,private:!1,access:{has:e=>"_primaryColor"in e,get:e=>e._primaryColor,set:(e,t)=>{e._primaryColor=t}},metadata:t},fe,ge),b(null,null,S,{kind:"field",name:"__perceptualColor",static:!1,private:!1,access:{has:e=>"__perceptualColor"in e,get:e=>e.__perceptualColor,set:(e,t)=>{e.__perceptualColor=t}},metadata:t},Ee,Re),b(null,null,v,{kind:"field",name:"_primaryColorShadowLevel",static:!1,private:!1,access:{has:e=>"_primaryColorShadowLevel"in e,get:e=>e._primaryColorShadowLevel,set:(e,t)=>{e._primaryColorShadowLevel=t}},metadata:t},be,Ae),b(null,null,I,{kind:"field",name:"_primaryColorHighlightLevel",static:!1,private:!1,access:{has:e=>"_primaryColorHighlightLevel"in e,get:e=>e._primaryColorHighlightLevel,set:(e,t)=>{e._primaryColorHighlightLevel=t}},metadata:t},ye,Me),b(null,null,P,{kind:"field",name:"_reflectionTexture",static:!1,private:!1,access:{has:e=>"_reflectionTexture"in e,get:e=>e._reflectionTexture,set:(e,t)=>{e._reflectionTexture=t}},metadata:t},ve,Ie),b(null,null,O,{kind:"field",name:"_reflectionBlur",static:!1,private:!1,access:{has:e=>"_reflectionBlur"in e,get:e=>e._reflectionBlur,set:(e,t)=>{e._reflectionBlur=t}},metadata:t},De,we),b(null,null,B,{kind:"field",name:"_diffuseTexture",static:!1,private:!1,access:{has:e=>"_diffuseTexture"in e,get:e=>e._diffuseTexture,set:(e,t)=>{e._diffuseTexture=t}},metadata:t},Ne,Be),b(null,null,V,{kind:"field",name:"_shadowLevel",static:!1,private:!1,access:{has:e=>"_shadowLevel"in e,get:e=>e._shadowLevel,set:(e,t)=>{e._shadowLevel=t}},metadata:t},He,ze),b(null,null,z,{kind:"field",name:"_sceneCenter",static:!1,private:!1,access:{has:e=>"_sceneCenter"in e,get:e=>e._sceneCenter,set:(e,t)=>{e._sceneCenter=t}},metadata:t},Ye,je),b(null,null,X,{kind:"field",name:"_opacityFresnel",static:!1,private:!1,access:{has:e=>"_opacityFresnel"in e,get:e=>e._opacityFresnel,set:(e,t)=>{e._opacityFresnel=t}},metadata:t},Qe,Je),b(null,null,Y,{kind:"field",name:"_reflectionFresnel",static:!1,private:!1,access:{has:e=>"_reflectionFresnel"in e,get:e=>e._reflectionFresnel,set:(e,t)=>{e._reflectionFresnel=t}},metadata:t},st,it),b(null,null,q,{kind:"field",name:"_reflectionFalloffDistance",static:!1,private:!1,access:{has:e=>"_reflectionFalloffDistance"in e,get:e=>e._reflectionFalloffDistance,set:(e,t)=>{e._reflectionFalloffDistance=t}},metadata:t},at,ot),b(null,null,Z,{kind:"field",name:"_reflectionAmount",static:!1,private:!1,access:{has:e=>"_reflectionAmount"in e,get:e=>e._reflectionAmount,set:(e,t)=>{e._reflectionAmount=t}},metadata:t},ct,ut),b(null,null,J,{kind:"field",name:"_reflectionReflectance0",static:!1,private:!1,access:{has:e=>"_reflectionReflectance0"in e,get:e=>e._reflectionReflectance0,set:(e,t)=>{e._reflectionReflectance0=t}},metadata:t},ft,gt),b(null,null,te,{kind:"field",name:"_reflectionReflectance90",static:!1,private:!1,access:{has:e=>"_reflectionReflectance90"in e,get:e=>e._reflectionReflectance90,set:(e,t)=>{e._reflectionReflectance90=t}},metadata:t},Et,Rt),b(null,null,ie,{kind:"field",name:"_useRGBColor",static:!1,private:!1,access:{has:e=>"_useRGBColor"in e,get:e=>e._useRGBColor,set:(e,t)=>{e._useRGBColor=t}},metadata:t},yt,Mt),b(null,null,ne,{kind:"field",name:"_enableNoise",static:!1,private:!1,access:{has:e=>"_enableNoise"in e,get:e=>e._enableNoise,set:(e,t)=>{e._enableNoise=t}},metadata:t},vt,It),b(null,null,oe,{kind:"field",name:"_maxSimultaneousLights",static:!1,private:!1,access:{has:e=>"_maxSimultaneousLights"in e,get:e=>e._maxSimultaneousLights,set:(e,t)=>{e._maxSimultaneousLights=t}},metadata:t},Ot,Dt),b(null,null,le,{kind:"field",name:"_shadowOnly",static:!1,private:!1,access:{has:e=>"_shadowOnly"in e,get:e=>e._shadowOnly,set:(e,t)=>{e._shadowOnly=t}},metadata:t},Ft,Nt),b(null,null,de,{kind:"field",name:"projectedGroundRadius",static:!1,private:!1,access:{has:e=>"projectedGroundRadius"in e,get:e=>e.projectedGroundRadius,set:(e,t)=>{e.projectedGroundRadius=t}},metadata:t},Vt,Ht),b(null,null,_e,{kind:"field",name:"projectedGroundHeight",static:!1,private:!1,access:{has:e=>"projectedGroundHeight"in e,get:e=>e.projectedGroundHeight,set:(e,t)=>{e.projectedGroundHeight=t}},metadata:t},zt,Wt),t&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:t})})(),e.StandardReflectance0=.05,e.StandardReflectance90=.5,e})(),Mh=!1;Mh||(Mh=!0,Ao(),be("BABYLON.BackgroundMaterial",yh)),po||(po=!0,_o.Bind=go,_o.Parse=fo,$e._ColorCurvesParser=fo),Ao();class xh{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return!!this._texture&&this._texture.isCube}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return void 0!==e?.shareDepth}constructor(e){this._wrapU=dt.TEXTURE_WRAP_ADDRESSMODE,this._wrapV=dt.TEXTURE_WRAP_ADDRESSMODE,this.wrapR=dt.TEXTURE_WRAP_ADDRESSMODE,this.anisotropicFilteringLevel=4,this.delayLoadState=dt.DELAYLOADSTATE_NONE,this._texture=null,this._engine=null,this._cachedSize=la.Zero(),this._cachedBaseSize=la.Zero(),this._initialSamplingMode=dt.TEXTURE_BILINEAR_SAMPLINGMODE,this._texture=xh._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine(),this.wrapU=this._texture._cachedWrapU??this.wrapU,this.wrapV=this._texture._cachedWrapV??this.wrapV,this.wrapR=this._texture._cachedWrapR??this.wrapR)}isReady(){return this.delayLoadState===dt.DELAYLOADSTATE_NOTLOADED?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return this.isReady()&&this._texture?this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e,t=!1){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture,this._texture.generateMipMaps&&t)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}let Sh=(()=>{var e;let t,s,i,r,n,a,o,h,l,u,d,_,p,f,g,m,T,E,R,y,M,x,S,v,I,P=xh,C=[],O=[],D=[],w=[],N=[],B=[],U=[],k=[],G=[],V=[],H=[],z=[],W=[],X=[],K=[],Y=[],j=[],q=[],$=[],Z=[],Q=[],J=[],te=[],se=[],ie=[],re=[],ne=[],ae=[],oe=[],he=[],le=[];return e=class extends P{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag,e=>e.hasTexture(this)))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag,e=>e.hasTexture(this)))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag,e=>e.hasTexture(this)))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag,e=>e.hasTexture(this)))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this.getScene()?.markAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag,e=>e.hasTexture(this))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),this.getScene()?.markAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag,e=>e.hasTexture(this)))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return!!this._texture&&this._texture._linearSpecularLOD}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=vs()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(t,s=null){super(null),this.uniqueId=(A(this,C),A(this,O,void 0)),this.name=(A(this,D),A(this,w,void 0)),this.displayName=(A(this,N),A(this,B,void 0)),this.metadata=(A(this,U),A(this,k,null)),this._internalMetadata=A(this,G),this.reservedDataStore=null,this._hasAlpha=A(this,V,!1),this._getAlphaFromRGB=(A(this,H),A(this,z,!1)),this.level=(A(this,W),A(this,X,1)),this._coordinatesIndex=(A(this,K),A(this,Y,0)),this.optimizeUVAllocation=(A(this,j),A(this,q,!0)),this._coordinatesMode=(A(this,$),A(this,Z,dt.TEXTURE_EXPLICIT_MODE)),this.wrapR=(A(this,Q),A(this,J,dt.TEXTURE_WRAP_ADDRESSMODE)),this.anisotropicFilteringLevel=(A(this,te),A(this,se,e.DEFAULT_ANISOTROPIC_FILTERING_LEVEL)),this._isCube=(A(this,ie),!1),this._gammaSpace=!0,this.invertZ=A(this,re,!1),this.lodLevelInAlpha=(A(this,ne),A(this,ae,!1)),this._dominantDirection=(A(this,oe),null),this.isRenderTarget=A(this,he,!1),this._prefiltered=(A(this,le),!1),this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new c,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,t?e._IsScene(t)?this._scene=t:this._engine=t:this._scene=ee.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=s,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return Ie.IdentityReadOnly}getReflectionTextureMatrix(){return Ie.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,s,i,r,n){const a=this._getEngine();if(!a)return null;const o=a._getUseSRGBBuffer(!!r,t),h=a.getLoadedTexturesCache();for(let a=0;a<h.length;a++){const l=h[a];if(!(void 0!==r&&o!==l._useSRGBBuffer||void 0!==i&&i!==l.invertY||l.url!==e||l.generateMipMaps!==!t||s&&s!==l.samplingMode||void 0!==n&&n!==l.isCube))return l.incrementReferences(),l}return null}_rebuild(e=!1){}clone(){return null}get textureType(){return this._texture&&void 0!==this._texture.type?this._texture.type:dt.TEXTURETYPE_UNSIGNED_BYTE}get textureFormat(){return this._texture&&void 0!==this._texture.format?this._texture.format:dt.TEXTUREFORMAT_RGBA}_markAllSubMeshesAsTexturesDirty(){const e=this.getScene();e&&e.markAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag)}readPixels(e=0,t=0,s=null,i=!0,r=!1,n=0,a=0,o=Number.MAX_VALUE,h=Number.MAX_VALUE){if(!this._texture)return null;const l=this._getEngine();if(!l)return null;const c=this.getSize();let u=c.width,d=c.height;0!==t&&(u/=Math.pow(2,t),d/=Math.pow(2,t),u=Math.round(u),d=Math.round(d)),o=Math.min(u,o),h=Math.min(d,h);try{return this._texture.isCube||this._texture.is2DArray?l._readTexturePixels(this._texture,o,h,e,t,s,i,r,n,a):l._readTexturePixels(this._texture,o,h,-1,t,s,i,r,n,a)}catch(e){return null}}_readPixelsSync(e=0,t=0,s=null,i=!0,r=!1){if(!this._texture)return null;const n=this.getSize();let a=n.width,o=n.height;const h=this._getEngine();if(!h)return null;0!=t&&(a/=Math.pow(2,t),o/=Math.pow(2,t),a=Math.round(a),o=Math.round(o));try{return this._texture.isCube?h._readTexturePixelsSync(this._texture,a,o,e,t,s,i,r):h._readTexturePixelsSync(this._texture,a,o,-1,t,s,i,r)}catch(e){return null}}get _lodTextureHigh(){return this._texture?this._texture._lodTextureHigh:null}get _lodTextureMid(){return this._texture?this._texture._lodTextureMid:null}get _lodTextureLow(){return this._texture?this._texture._lodTextureLow:null}dispose(){if(this._scene){this._scene.stopAnimation&&this._scene.stopAnimation(this),this._scene.removePendingData(this);const e=this._scene.textures.indexOf(this);if(e>=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const e=this._parentContainer.textures.indexOf(this);e>-1&&this._parentContainer.textures.splice(e,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=$e.Serialize(this);return $e.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let s=e.length;if(0!==s)for(let i=0;i<e.length;i++){const r=e[i];if(r.isReady())0===--s&&t();else{const e=r.onLoadObservable;e?e.addOnce(()=>{0===--s&&t()}):0===--s&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}},(()=>{const c="function"==typeof Symbol&&Symbol.metadata?Object.create(P[Symbol.metadata]??null):void 0;t=[L()],s=[L()],i=[L()],r=[L()],n=[L("hasAlpha")],a=[L("getAlphaFromRGB")],o=[L()],h=[L("coordinatesIndex")],l=[L()],u=[L("coordinatesMode")],d=[L()],_=[L()],p=[L()],f=[L()],g=[L()],m=[L()],T=[L()],E=[L()],R=[L()],y=[L()],M=[L()],x=[L()],S=[L()],v=[F()],I=[L()],b(e,null,d,{kind:"getter",name:"wrapU",static:!1,private:!1,access:{has:e=>"wrapU"in e,get:e=>e.wrapU},metadata:c},null,C),b(e,null,_,{kind:"getter",name:"wrapV",static:!1,private:!1,access:{has:e=>"wrapV"in e,get:e=>e.wrapV},metadata:c},null,C),b(e,null,g,{kind:"getter",name:"isCube",static:!1,private:!1,access:{has:e=>"isCube"in e,get:e=>e.isCube},metadata:c},null,C),b(e,null,m,{kind:"getter",name:"is3D",static:!1,private:!1,access:{has:e=>"is3D"in e,get:e=>e.is3D},metadata:c},null,C),b(e,null,T,{kind:"getter",name:"is2DArray",static:!1,private:!1,access:{has:e=>"is2DArray"in e,get:e=>e.is2DArray},metadata:c},null,C),b(e,null,E,{kind:"getter",name:"gammaSpace",static:!1,private:!1,access:{has:e=>"gammaSpace"in e,get:e=>e.gammaSpace},metadata:c},null,C),b(e,null,M,{kind:"getter",name:"lodGenerationOffset",static:!1,private:!1,access:{has:e=>"lodGenerationOffset"in e,get:e=>e.lodGenerationOffset},metadata:c},null,C),b(e,null,x,{kind:"getter",name:"lodGenerationScale",static:!1,private:!1,access:{has:e=>"lodGenerationScale"in e,get:e=>e.lodGenerationScale},metadata:c},null,C),b(e,null,S,{kind:"getter",name:"linearSpecularLOD",static:!1,private:!1,access:{has:e=>"linearSpecularLOD"in e,get:e=>e.linearSpecularLOD},metadata:c},null,C),b(e,null,v,{kind:"getter",name:"irradianceTexture",static:!1,private:!1,access:{has:e=>"irradianceTexture"in e,get:e=>e.irradianceTexture},metadata:c},null,C),b(null,null,t,{kind:"field",name:"uniqueId",static:!1,private:!1,access:{has:e=>"uniqueId"in e,get:e=>e.uniqueId,set:(e,t)=>{e.uniqueId=t}},metadata:c},O,D),b(null,null,s,{kind:"field",name:"name",static:!1,private:!1,access:{has:e=>"name"in e,get:e=>e.name,set:(e,t)=>{e.name=t}},metadata:c},w,N),b(null,null,i,{kind:"field",name:"displayName",static:!1,private:!1,access:{has:e=>"displayName"in e,get:e=>e.displayName,set:(e,t)=>{e.displayName=t}},metadata:c},B,U),b(null,null,r,{kind:"field",name:"metadata",static:!1,private:!1,access:{has:e=>"metadata"in e,get:e=>e.metadata,set:(e,t)=>{e.metadata=t}},metadata:c},k,G),b(null,null,n,{kind:"field",name:"_hasAlpha",static:!1,private:!1,access:{has:e=>"_hasAlpha"in e,get:e=>e._hasAlpha,set:(e,t)=>{e._hasAlpha=t}},metadata:c},V,H),b(null,null,a,{kind:"field",name:"_getAlphaFromRGB",static:!1,private:!1,access:{has:e=>"_getAlphaFromRGB"in e,get:e=>e._getAlphaFromRGB,set:(e,t)=>{e._getAlphaFromRGB=t}},metadata:c},z,W),b(null,null,o,{kind:"field",name:"level",static:!1,private:!1,access:{has:e=>"level"in e,get:e=>e.level,set:(e,t)=>{e.level=t}},metadata:c},X,K),b(null,null,h,{kind:"field",name:"_coordinatesIndex",static:!1,private:!1,access:{has:e=>"_coordinatesIndex"in e,get:e=>e._coordinatesIndex,set:(e,t)=>{e._coordinatesIndex=t}},metadata:c},Y,j),b(null,null,l,{kind:"field",name:"optimizeUVAllocation",static:!1,private:!1,access:{has:e=>"optimizeUVAllocation"in e,get:e=>e.optimizeUVAllocation,set:(e,t)=>{e.optimizeUVAllocation=t}},metadata:c},q,$),b(null,null,u,{kind:"field",name:"_coordinatesMode",static:!1,private:!1,access:{has:e=>"_coordinatesMode"in e,get:e=>e._coordinatesMode,set:(e,t)=>{e._coordinatesMode=t}},metadata:c},Z,Q),b(null,null,p,{kind:"field",name:"wrapR",static:!1,private:!1,access:{has:e=>"wrapR"in e,get:e=>e.wrapR,set:(e,t)=>{e.wrapR=t}},metadata:c},J,te),b(null,null,f,{kind:"field",name:"anisotropicFilteringLevel",static:!1,private:!1,access:{has:e=>"anisotropicFilteringLevel"in e,get:e=>e.anisotropicFilteringLevel,set:(e,t)=>{e.anisotropicFilteringLevel=t}},metadata:c},se,ie),b(null,null,R,{kind:"field",name:"invertZ",static:!1,private:!1,access:{has:e=>"invertZ"in e,get:e=>e.invertZ,set:(e,t)=>{e.invertZ=t}},metadata:c},re,ne),b(null,null,y,{kind:"field",name:"lodLevelInAlpha",static:!1,private:!1,access:{has:e=>"lodLevelInAlpha"in e,get:e=>e.lodLevelInAlpha,set:(e,t)=>{e.lodLevelInAlpha=t}},metadata:c},ae,oe),b(null,null,I,{kind:"field",name:"isRenderTarget",static:!1,private:!1,access:{has:e=>"isRenderTarget"in e,get:e=>e.isRenderTarget,set:(e,t)=>{e.isRenderTarget=t}},metadata:c},he,le),c&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:c})})(),e.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,e})();function vh(e,t,s=!1){const i=t.width,r=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const s=new Uint8Array(t);for(;--t>=0;){let i=e[t];i<0?i=0:i>1&&(i=1),s[t]=255*i}e=s}const n=document.createElement("canvas");n.width=i,n.height=r;const a=n.getContext("2d");if(!a)return null;const o=a.createImageData(i,r);if(o.data.set(e),a.putImageData(o,0,0),s){const e=document.createElement("canvas");e.width=i,e.height=r;const t=e.getContext("2d");return t?(t.translate(0,r),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}function Ih(e,t=0,s=0){const i=e.getInternalTexture();if(!i)return null;const r=e._readPixelsSync(t,s);return r?vh(r,e.getSize(),i.invertY):null}async function Ph(e,t=0,s=0){const i=e.getInternalTexture();if(!i)return null;const r=await e.readPixels(t,s);return r?vh(r,e.getSize(),i.invertY):null}Sh.prototype.forceSphericalPolynomialsRecompute??=Ne("BaseTexture","forceSphericalPolynomialsRecompute"),Object.getOwnPropertyDescriptor(Sh.prototype,"sphericalPolynomial")||Object.defineProperty(Sh.prototype,"sphericalPolynomial",Ue(0,"sphericalPolynomial"));let Ch=(()=>{var e;let t,s,i,r,n,a,o,h,l,u,d,_,p,f=Sh,g=[],m=[],T=[],E=[],R=[],y=[],M=[],x=[],S=[],v=[],I=[],P=[],C=[],O=[],D=[],w=[],F=[],N=[],B=[],U=[],k=[],G=[],V=[],H=[],z=[];return e=class extends f{static _CreateVideoTexture(t,s,i,r=!1,n=!1,a=e.TRILINEAR_SAMPLINGMODE,o={},h,l=dt.TEXTUREFORMAT_RGBA){throw Le("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(t,s,i,r,n=e.TRILINEAR_SAMPLINGMODE,a=null,o=null,h=null,l=!1,u,d,_,p,f){let b;super(s),this.url=(A(this,g),A(this,m,null)),this.uOffset=(A(this,T),A(this,E,0)),this.vOffset=(A(this,R),A(this,y,0)),this.uScale=(A(this,M),A(this,x,1)),this.vScale=(A(this,S),A(this,v,1)),this.uAng=(A(this,I),A(this,P,0)),this.vAng=(A(this,C),A(this,O,0)),this.wAng=(A(this,D),A(this,w,0)),this.uRotationCenter=(A(this,F),A(this,N,.5)),this.vRotationCenter=(A(this,B),A(this,U,.5)),this.wRotationCenter=(A(this,k),A(this,G,.5)),this.homogeneousRotationInUVTransform=(A(this,V),A(this,H,!1)),this.inspectableCustomProperties=(A(this,z),null),this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedIdentity3x2=!0,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new c,this._isBlocking=!0,this.name=t||"",this.url=t;let L=!1,W=null,X=!0;"object"==typeof i&&null!==i?(b=i.noMipmap??!1,r=i.invertY??!0,n=i.samplingMode??e.TRILINEAR_SAMPLINGMODE,a=i.onLoad??null,o=i.onError??null,h=i.buffer??null,l=i.deleteBuffer??!1,u=i.format,d=i.mimeType,_=i.loaderOptions,p=i.creationFlags,L=i.useSRGBBuffer??!1,W=i.internalTexture??null,X=i.gammaSpace??X,f=i.forcedExtension??f):b=!!i,this._gammaSpace=X,this._noMipmap=b,this._invertY=void 0===r||r,this._initialSamplingMode=n,this._buffer=h,this._deleteBuffer=l,this._mimeType=d,this._loaderOptions=_,this._creationFlags=p,this._useSRGBBuffer=L,this._forcedExtension=f,void 0!==u&&(this._format=u);const K=this.getScene(),Y=this._getEngine();if(!Y)return;Y.onBeforeTextureInitObservable.notifyObservers(this);const j=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),a&&a(),!this.isBlocking&&K&&K.resetCachedMaterial()},q=(t,s)=>{this._loadingError=!0,this._errorObject={message:t,exception:s},o&&o(t,s),e.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!W)return this._delayedOnLoad=j,void(this._delayedOnError=q);if(this._texture=W??this._getFromCache(this.url,b,n,this._invertY,L,this.isCube),this._texture)if(this._texture.isReady)Xt.SetImmediate(()=>j());else{const e=this._texture.onLoadedObservable.add(j);this._texture.onErrorObservable.add(t=>{q(t.message,t.exception),this._texture?.onLoadedObservable.remove(e)})}else if(K&&K.useDelayedTextureLoading)this.delayLoadState=dt.DELAYLOADSTATE_NOTLOADED,this._delayedOnLoad=j,this._delayedOnError=q;else{try{this._texture=Y.createTexture(this.url,b,this._invertY,K,n,j,q,this._buffer,void 0,this._format,this._forcedExtension,d,_,p,L)}catch(e){throw q("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,s,i){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag,e=>e.hasTexture(this))),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=i,this.delayLoadState=dt.DELAYLOADSTATE_NOTLOADED;const r=this._delayedOnLoad;this._delayedOnLoad=()=>{r?r():this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),s&&s()},this.delayLoad()}delayLoad(){if(this.delayLoadState!==dt.DELAYLOADSTATE_NOTLOADED)return;const e=this.getScene();if(!e)return;let t=this.url;!t&&(this.name.indexOf("://")>0||this.name.startsWith("data:"))&&(t=this.name),this.delayLoadState=dt.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(t,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?Xt.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(t,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null}_prepareRowForTextureGeneration(e,t,s,i){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,s-=this.wRotationCenter,xe.TransformCoordinatesFromFloatsToRef(e,t,s,this._rowGenerationMatrix,i),i.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,i.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,i.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=Ie.Zero(),this._rowGenerationMatrix=new Ie,this._t0=xe.Zero(),this._t1=xe.Zero(),this._t2=xe.Zero()),Ie.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(Ie.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,Ce.Matrix[0]),Ie.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,Ce.Matrix[1]),Ie.ScalingToRef(this._cachedUScale,this._cachedVScale,0,Ce.Matrix[2]),Ie.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,Ce.Matrix[3]),Ce.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(Ce.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(Ce.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(Ce.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),Ie.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));const t=this.getScene();if(!t)return this._cachedTextureMatrix;const s=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&s!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag,e=>e.hasTexture(this)),this._cachedTextureMatrix}getReflectionTextureMatrix(){const t=this.getScene();if(!t)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode){if(this.coordinatesMode!==e.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===t.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=Ie.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=Ie.Zero());const s=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case e.PLANAR_MODE:Ie.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break;case e.PROJECTION_MODE:{Ie.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const e=t.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=e.updateFlag,e.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:Ie.IdentityToRef(this._cachedReflectionTextureMatrix)}return s&&t.markAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag,e=>e.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){const t={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return $e.Clone(()=>new e(this._texture?this._texture.url:null,this.getScene(),t),this)}serialize(){const t=this.name;e.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const s=super.serialize(e._SerializeInternalTextureUniqueId);if(!s)return null;if(e.SerializeBuffers||e.ForceSerializeBuffers)if("string"==typeof this._buffer&&this._buffer.startsWith("data:"))s.base64String=this._buffer,s.name=s.name.replace("data:","");else if(this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array){const e=this.mimeType||"image/png";s.base64String=`data:${e};base64,${lt(this._buffer)}`}else(e.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(s.base64String=!this._engine||this._engine._features.supportSyncTextureRead?Ih(this):Ph(this));return s.invertY=this._invertY,s.samplingMode=this.samplingMode,s._creationFlags=this._creationFlags,s._useSRGBBuffer=this._useSRGBBuffer,e._SerializeInternalTextureUniqueId&&(s.internalTextureUniqueId=this._texture?.uniqueId),s.internalTextureLabel=this._texture?.label,s.noMipmap=this._noMipmap,this.name=t,s}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(t,s,i){if(t.customType){const e=Ss.Instantiate(t.customType).Parse(t,s,i);return t.samplingMode&&e.updateSamplingMode&&e._samplingMode&&e._samplingMode!==t.samplingMode&&e.updateSamplingMode(t.samplingMode),e}if(t.isCube&&!t.isRenderTarget)return e._CubeTextureParser(t,s,i);const r=void 0!==t.internalTextureUniqueId;if(!t.name&&!t.isRenderTarget&&!r)return null;let n;if(r){const e=s.getEngine().getLoadedTexturesCache();for(const s of e)if(s.uniqueId===t.internalTextureUniqueId){n=s;break}}const a=e=>{if(e&&e._texture&&(e._texture._cachedWrapU=null,e._texture._cachedWrapV=null,e._texture._cachedWrapR=null),t.samplingMode){const s=t.samplingMode;e&&e.samplingMode!==s&&e.updateSamplingMode(s)}if(e&&t.animations)for(let s=0;s<t.animations.length;s++){const i=t.animations[s],r=Ae("BABYLON.Animation");r&&e.animations.push(r.Parse(i))}e&&e._texture&&(r&&!n&&e._texture._setUniqueId(t.internalTextureUniqueId),e._texture.label=t.internalTextureLabel)};return $e.Parse(()=>{let r=!0;if(t.noMipmap&&(r=!1),t.mirrorPlane){const i=e._CreateMirror(t.name,t.renderTargetSize,s,r);return i._waitingRenderList=t.renderList,i.mirrorPlane=Ys.FromArray(t.mirrorPlane),a(i),i}if(t.isRenderTarget&&!t.base64String){let i=null;if(t.isCube){if(s.reflectionProbes)for(let e=0;e<s.reflectionProbes.length;e++){const i=s.reflectionProbes[e];if(i.name===t.name)return i.cubeTexture}}else i=e._CreateRenderTargetTexture(t.name,t.renderTargetSize,s,r,t._creationFlags??0),i._waitingRenderList=t.renderList;return a(i),i}if(t.isVideo){const n=e._CreateVideoTexture(i+(t.url||t.name),i+(t.src||t.url),s,r,t.invertY,t.samplingMode,t.settings||{});return a(n),n}{let o;if("string"==typeof t.base64String&&t.base64String&&!n){const i={buffer:t.base64String,noMipmap:!r,invertY:t.invertY,samplingMode:t.samplingMode,useSRGBBuffer:t._useSRGBBuffer??!1,creationFlags:t._creationFlags??0,onLoad:()=>{a(o)}},n=t.base64String,h=n.startsWith("data:")?n.substring(5):n;o=e.CreateFromBase64String("",h,s,i),o.name=t.name}else{let h;h=t.name&&(t.name.indexOf("://")>0||t.name.startsWith("data:"))?t.name:i+t.name,t.url&&(t.url.startsWith("data:")||e.UseSerializedUrlIfAny)&&(h=t.url);const l={noMipmap:!r,invertY:t.invertY,samplingMode:t.samplingMode,useSRGBBuffer:t._useSRGBBuffer??!1,creationFlags:t._creationFlags??0,onLoad:()=>{a(o)},internalTexture:n};o=new e(h,s,l)}return o}},t,s)}static CreateFromBase64String(t,s,i,r,n,a=e.TRILINEAR_SAMPLINGMODE,o=null,h=null,l=dt.TEXTUREFORMAT_RGBA,c,u){return new e("data:"+s,i,r,n,a,o,h,t,!1,l,void 0,void 0,c,u)}static LoadFromDataString(t,s,i,r=!1,n,a=!0,o=e.TRILINEAR_SAMPLINGMODE,h=null,l=null,c=dt.TEXTUREFORMAT_RGBA,u,d){return"data:"!==t.substring(0,5)&&(t="data:"+t),new e(t,i,n,a,o,h,l,s,r,c,void 0,void 0,u,d)}},(()=>{const c="function"==typeof Symbol&&Symbol.metadata?Object.create(f[Symbol.metadata]??null):void 0;t=[L()],s=[L()],i=[L()],r=[L()],n=[L()],a=[L()],o=[L()],h=[L()],l=[L()],u=[L()],d=[L()],_=[L()],p=[L()],b(e,null,p,{kind:"getter",name:"isBlocking",static:!1,private:!1,access:{has:e=>"isBlocking"in e,get:e=>e.isBlocking},metadata:c},null,g),b(null,null,t,{kind:"field",name:"url",static:!1,private:!1,access:{has:e=>"url"in e,get:e=>e.url,set:(e,t)=>{e.url=t}},metadata:c},m,T),b(null,null,s,{kind:"field",name:"uOffset",static:!1,private:!1,access:{has:e=>"uOffset"in e,get:e=>e.uOffset,set:(e,t)=>{e.uOffset=t}},metadata:c},E,R),b(null,null,i,{kind:"field",name:"vOffset",static:!1,private:!1,access:{has:e=>"vOffset"in e,get:e=>e.vOffset,set:(e,t)=>{e.vOffset=t}},metadata:c},y,M),b(null,null,r,{kind:"field",name:"uScale",static:!1,private:!1,access:{has:e=>"uScale"in e,get:e=>e.uScale,set:(e,t)=>{e.uScale=t}},metadata:c},x,S),b(null,null,n,{kind:"field",name:"vScale",static:!1,private:!1,access:{has:e=>"vScale"in e,get:e=>e.vScale,set:(e,t)=>{e.vScale=t}},metadata:c},v,I),b(null,null,a,{kind:"field",name:"uAng",static:!1,private:!1,access:{has:e=>"uAng"in e,get:e=>e.uAng,set:(e,t)=>{e.uAng=t}},metadata:c},P,C),b(null,null,o,{kind:"field",name:"vAng",static:!1,private:!1,access:{has:e=>"vAng"in e,get:e=>e.vAng,set:(e,t)=>{e.vAng=t}},metadata:c},O,D),b(null,null,h,{kind:"field",name:"wAng",static:!1,private:!1,access:{has:e=>"wAng"in e,get:e=>e.wAng,set:(e,t)=>{e.wAng=t}},metadata:c},w,F),b(null,null,l,{kind:"field",name:"uRotationCenter",static:!1,private:!1,access:{has:e=>"uRotationCenter"in e,get:e=>e.uRotationCenter,set:(e,t)=>{e.uRotationCenter=t}},metadata:c},N,B),b(null,null,u,{kind:"field",name:"vRotationCenter",static:!1,private:!1,access:{has:e=>"vRotationCenter"in e,get:e=>e.vRotationCenter,set:(e,t)=>{e.vRotationCenter=t}},metadata:c},U,k),b(null,null,d,{kind:"field",name:"wRotationCenter",static:!1,private:!1,access:{has:e=>"wRotationCenter"in e,get:e=>e.wRotationCenter,set:(e,t)=>{e.wRotationCenter=t}},metadata:c},G,V),b(null,null,_,{kind:"field",name:"homogeneousRotationInUVTransform",static:!1,private:!1,access:{has:e=>"homogeneousRotationInUVTransform"in e,get:e=>e.homogeneousRotationInUVTransform,set:(e,t)=>{e.homogeneousRotationInUVTransform=t}},metadata:c},H,z),c&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:c})})(),e.SerializeBuffers=!0,e.ForceSerializeBuffers=!1,e.OnTextureLoadErrorObservable=new c,e._SerializeInternalTextureUniqueId=!1,e._CubeTextureParser=(e,t,s)=>{throw Le("CubeTexture")},e._CreateMirror=(e,t,s,i)=>{throw Le("MirrorTexture")},e._CreateRenderTargetTexture=(e,t,s,i,r)=>{throw Le("RenderTargetTexture")},e.NEAREST_SAMPLINGMODE=dt.TEXTURE_NEAREST_SAMPLINGMODE,e.NEAREST_NEAREST_MIPLINEAR=dt.TEXTURE_NEAREST_NEAREST_MIPLINEAR,e.BILINEAR_SAMPLINGMODE=dt.TEXTURE_BILINEAR_SAMPLINGMODE,e.LINEAR_LINEAR_MIPNEAREST=dt.TEXTURE_LINEAR_LINEAR_MIPNEAREST,e.TRILINEAR_SAMPLINGMODE=dt.TEXTURE_TRILINEAR_SAMPLINGMODE,e.LINEAR_LINEAR_MIPLINEAR=dt.TEXTURE_LINEAR_LINEAR_MIPLINEAR,e.NEAREST_NEAREST_MIPNEAREST=dt.TEXTURE_NEAREST_NEAREST_MIPNEAREST,e.NEAREST_LINEAR_MIPNEAREST=dt.TEXTURE_NEAREST_LINEAR_MIPNEAREST,e.NEAREST_LINEAR_MIPLINEAR=dt.TEXTURE_NEAREST_LINEAR_MIPLINEAR,e.NEAREST_LINEAR=dt.TEXTURE_NEAREST_LINEAR,e.NEAREST_NEAREST=dt.TEXTURE_NEAREST_NEAREST,e.LINEAR_NEAREST_MIPNEAREST=dt.TEXTURE_LINEAR_NEAREST_MIPNEAREST,e.LINEAR_NEAREST_MIPLINEAR=dt.TEXTURE_LINEAR_NEAREST_MIPLINEAR,e.LINEAR_LINEAR=dt.TEXTURE_LINEAR_LINEAR,e.LINEAR_NEAREST=dt.TEXTURE_LINEAR_NEAREST,e.EXPLICIT_MODE=dt.TEXTURE_EXPLICIT_MODE,e.SPHERICAL_MODE=dt.TEXTURE_SPHERICAL_MODE,e.PLANAR_MODE=dt.TEXTURE_PLANAR_MODE,e.CUBIC_MODE=dt.TEXTURE_CUBIC_MODE,e.PROJECTION_MODE=dt.TEXTURE_PROJECTION_MODE,e.SKYBOX_MODE=dt.TEXTURE_SKYBOX_MODE,e.INVCUBIC_MODE=dt.TEXTURE_INVCUBIC_MODE,e.EQUIRECTANGULAR_MODE=dt.TEXTURE_EQUIRECTANGULAR_MODE,e.FIXED_EQUIRECTANGULAR_MODE=dt.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,e.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=dt.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,e.CLAMP_ADDRESSMODE=dt.TEXTURE_CLAMP_ADDRESSMODE,e.WRAP_ADDRESSMODE=dt.TEXTURE_WRAP_ADDRESSMODE,e.MIRROR_ADDRESSMODE=dt.TEXTURE_MIRROR_ADDRESSMODE,e.UseSerializedUrlIfAny=!1,e})(),Oh=!1;function Dh(e,t,s){const i=e.getVertexBuffer(s);if(!i)return null;const r=i.getData();if(!r)return null;let n;return is(r,i.byteStride*t,i.byteStride,i.getSize(),i.type,1,i.normalized,e=>n=e),n}function wh(e,t,s){const i=Dh(e,t,Gi.PositionKind);if(!i)return!1;if(i.some(e=>isNaN(e??Number.NaN)))return!1;if(e.morphTargetManager){const s=3*t;for(let t=0;t<i.length;t++){let r=i[t];for(let n=0;n<e.morphTargetManager.numTargets;n++){const a=e.morphTargetManager.getTarget(n),o=a.influence;if(0!==o){const e=a.getPositions();e&&(r+=(e[s+t]-i[t])*o)}}i[t]=r}}if(s.fromArray(i),e.skeleton){const r=Dh(e,t,Gi.MatricesIndicesKind),n=Dh(e,t,Gi.MatricesWeightsKind);if(r&&n){const a=e.numBoneInfluencers>4,o=a?Dh(e,t,Gi.MatricesIndicesExtraKind):null,h=a?Dh(e,t,Gi.MatricesWeightsExtraKind):null,l=e.skeleton.getTransformMatrices(e),c=Ce.Matrix[0],u=Ce.Matrix[1];c.reset();for(let e=0;e<n.length;e++){const t=n[e];t>0&&(Ie.FromFloat32ArrayToRefScaled(l,Math.floor(16*r[e]),t,u),c.addToSelf(u))}if(o&&h)for(let e=0;e<h.length;e++){const t=h[e];t>0&&(Ie.FromFloat32ArrayToRefScaled(l,Math.floor(16*o[e]),t,u),c.addToSelf(u))}xe.TransformCoordinatesFromFloatsToRef(i[0],i[1],i[2],c,s)}}return!0}function Lh(e){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const s=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],i=[],r=e.width||e.size||1,n=e.height||e.size||1,a=e.depth||e.size||1,o=e.wrap||!1;let h=void 0===e.topBaseAt?1:e.topBaseAt,l=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,l=(l+4)%4;let c=[2,0,3,1][h],u=[2,0,1,3][l],d=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(o){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],d=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let e=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],s=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const i=[17,18,19,16],r=[22,23,20,21];for(;c>0;)e.unshift(e.pop()),i.unshift(i.pop()),c--;for(;u>0;)s.unshift(s.pop()),r.unshift(r.pop()),u--;e=e.flat(),s=s.flat(),d=d.concat(e).concat(s),t.push(i[0],i[2],i[3],i[0],i[1],i[2]),t.push(r[0],r[2],r[3],r[0],r[1],r[2])}const _=[r/2,n/2,a/2],p=d.reduce((e,t,s)=>e.concat(t*_[s%3]),[]),f=0===e.sideOrientation?0:e.sideOrientation||or.DEFAULTSIDE,g=e.faceUV||new Array(6),m=e.faceColors,T=[];for(let e=0;e<6;e++)void 0===g[e]&&(g[e]=new Se(0,0,1,1)),m&&void 0===m[e]&&(m[e]=new Ke(1,1,1,1));for(let e=0;e<6;e++)if(i.push(g[e].z,g[e].w),i.push(g[e].x,g[e].w),i.push(g[e].x,g[e].y),i.push(g[e].z,g[e].y),m)for(let t=0;t<4;t++)T.push(m[e].r,m[e].g,m[e].b,m[e].a);or._ComputeSides(f,p,t,s,i,e.frontUVs,e.backUVs);const E=new or;if(E.indices=t,E.positions=p,E.normals=s,E.uvs=i,m){const e=f===or.DOUBLESIDE?T.concat(T):T;E.colors=e}return E}function Fh(e,t={},s=null){const i=new Xn(e,s);t.sideOrientation=Xn._GetDefaultSideOrientation(t.sideOrientation),i._originalBuilderSideOrientation=t.sideOrientation;return Lh(t).applyToMesh(i,t.updatable),i}Oh||(Oh=!0,be("BABYLON.Texture",Ch),$e._TextureParser=Ch.Parse),je||(je=!0,Object.defineProperties(Xe.prototype,{dimension:{value:[3]},rank:{value:1}}),Object.defineProperties(Ke.prototype,{dimension:{value:[4]},rank:{value:1}}),be("BABYLON.Color3",Xe),be("BABYLON.Color4",Ke)),De||(De=!0,Object.defineProperties(Me.prototype,{dimension:{value:[2]},rank:{value:1}}),Object.defineProperties(xe.prototype,{dimension:{value:[3]},rank:{value:1}}),Object.defineProperties(Se.prototype,{dimension:{value:[4]},rank:{value:1}}),Object.defineProperties(ve.prototype,{dimension:{value:[4]},rank:{value:1}}),Object.defineProperties(Ie.prototype,{dimension:{value:[4,4]},rank:{value:2}}),be("BABYLON.Vector2",Me),be("BABYLON.Vector3",xe),be("BABYLON.Vector4",Se),be("BABYLON.Matrix",Ie));let Nh=!1;Nh||(Nh=!0,or.CreateBox=Lh,Xn.CreateBox=(e,t,s=null,i,r)=>Fh(e,{size:t,sideOrientation:r,updatable:i},s));class Bh{constructor(){this.mm=new Map}get(e,t){const s=this.mm.get(e);if(void 0!==s)return s.get(t)}set(e,t,s){let i=this.mm.get(e);void 0===i&&this.mm.set(e,i=new Map),i.set(t,s)}}class Uh{get standalone(){return this._options?.standalone??!1}get baseMaterial(){return this._baseMaterial}get doNotInjectCode(){return this._options?.doNotInjectCode??!1}constructor(e,t,s){this._baseMaterial=e,this._scene=t??ee.LastCreatedScene,this._options=s,this._subMeshToEffect=new Map,this._subMeshToDepthWrapper=new Bh,this._meshes=new Map,this._onEffectCreatedObserver=this._baseMaterial.onEffectCreatedObservable.add(e=>{const t=e.subMesh?.getMesh();t&&!this._meshes.has(t)&&this._meshes.set(t,t.onDisposeObservable.add(e=>{const t=this._subMeshToEffect.keys();for(let s=t.next();!0!==s.done;s=t.next()){const t=s.value;t?.getMesh()===e&&(this._subMeshToEffect.delete(t),this._deleteDepthWrapperEffect(t))}})),this._subMeshToEffect.get(e.subMesh)?.[0]!==e.effect&&(this._subMeshToEffect.set(e.subMesh,[e.effect,this._scene.getEngine().currentRenderPassId]),this._deleteDepthWrapperEffect(e.subMesh))})}_deleteDepthWrapperEffect(e){const t=this._subMeshToDepthWrapper.mm.get(e);t&&(t.forEach(e=>{e.mainDrawWrapper.effect?.dispose()}),this._subMeshToDepthWrapper.mm.delete(e))}getEffect(e,t,s){const i=this._subMeshToDepthWrapper.mm.get(e)?.get(t);if(!i)return null;let r=i.drawWrapper[s];return r||(r=i.drawWrapper[s]=new rr(this._scene.getEngine()),r.setEffect(i.mainDrawWrapper.effect,i.mainDrawWrapper.defines)),r}isReadyForSubMesh(e,t,s,i,r){return!(this.standalone&&!this._baseMaterial.isReadyForSubMesh(e.getMesh(),e,i))&&(this._makeEffect(e,t,s,r)?.isReady()??!1)}dispose(){this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver),this._onEffectCreatedObserver=null;const e=this._meshes.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,s]=t.value;e.onDisposeObservable.remove(s)}}_makeEffect(e,t,s,i){const r=this._scene.getEngine(),n=this._subMeshToEffect.get(e);if(!n)return null;const[a,o]=n;if(!a.isReady())return null;let h=this._subMeshToDepthWrapper.get(e,s);if(!h){const t=new rr(r),n=e._getDrawWrapper(o)?.defines;t.defines="string"==typeof n?null:n??null,h={drawWrapper:[],mainDrawWrapper:t,depthDefines:"",token:vs()},h.drawWrapper[i]=t,this._subMeshToDepthWrapper.set(e,s,h)}const l=t.join("\n");if(h.mainDrawWrapper.effect&&l===h.depthDefines)return h.mainDrawWrapper.effect;h.depthDefines=l;const c=a.getUniformNames().slice();let u=a.vertexSourceCodeBeforeMigration,d=a.fragmentSourceCodeBeforeMigration;if(!u&&!d)return null;if(!this.doNotInjectCode){const e=this._options&&this._options.remappedVariables?`#include<shadowMapVertexNormalBias>(${this._options.remappedVariables.join(",")})`:"#include<shadowMapVertexNormalBias>",t=this._options&&this._options.remappedVariables?`#include<shadowMapVertexMetric>(${this._options.remappedVariables.join(",")})`:"#include<shadowMapVertexMetric>",s=this._options&&this._options.remappedVariables?`#include<shadowMapFragmentSoftTransparentShadow>(${this._options.remappedVariables.join(",")})`:"#include<shadowMapFragmentSoftTransparentShadow>",i="#include<shadowMapFragment>",r="#include<shadowMapVertexExtraDeclaration>";u=0===a.shaderLanguage?u.replace(/void\s+?main/g,`\n${r}\nvoid main`):u.replace(/@vertex/g,`\n${r}\n@vertex`),u=u.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,e),u=-1!==u.indexOf("#define SHADOWDEPTH_METRIC")?u.replace(/#define SHADOWDEPTH_METRIC/g,t):u.replace(/}\s*$/g,t+"\n}"),u=u.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");const n=d.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||d.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,o=-1!==d.indexOf("#define SHADOWDEPTH_FRAGMENT");let h="";n?d=d.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,s):h=s+"\n",d=d.replace(/void\s+?main/g,li.IncludesShadersStore.shadowMapFragmentExtraDeclaration+"\nvoid main"),o?d=d.replace(/#define SHADOWDEPTH_FRAGMENT/g,i):h+=i+"\n",h&&(d=d.replace(/}\s*$/g,h+"}")),c.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM")}h.mainDrawWrapper.effect=r.createEffect({vertexSource:u,fragmentSource:d,vertexToken:h.token,fragmentToken:h.token},{attributes:a.getAttributesNames(),uniformsNames:c,uniformBuffersNames:a.getUniformBuffersNames(),samplers:a.getSamplers(),defines:l+"\n"+a.defines.replace("#define SHADOWS","").replace(/#define SHADOW\d/g,""),indexParameters:a.getIndexParameters(),shaderLanguage:a.shaderLanguage},r);for(let e=0;e<h.drawWrapper.length;++e)e!==i&&h.drawWrapper[e]?.setEffect(h.mainDrawWrapper.effect,h.mainDrawWrapper.defines);return h.mainDrawWrapper.effect}}const kh=new WeakMap;function Gh(e){const t=e.getVertexBuffers();if(!t)return null;let s=kh.get(e);if(s){let e=!1;for(const i in t)if(!s.has(i)){e=!0;break}if(!e)return s}else s=new Map,kh.set(e,s);for(const e in t){const i=t[e];if(i){const t=i.byteOffset,r=i.byteStride,n=i.type,a=i.normalized;s.set(e,{offset:t,stride:r,type:n,normalized:a})}}return s}function Vh(e,t){t.forEach((t,s)=>{const i=`vp_${s}_info`;e.setFloat4(i,t.offset,t.stride,t.type,t.normalized?1:0)})}const Hh={effect:null,subMesh:null};class zh extends gh{constructor(e,t,s,i={},r=!0){super(e,t,r),this._textures={},this._internalTextures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new Ie,this._cachedWorldViewProjectionMatrix=new Ie,this._multiview=!1,this._vertexPullingMetadata=null,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=s,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...i}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}setInternalTexture(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._internalTextures[e]=t,this}removeTexture(e){delete this._textures[e]}setTextureArray(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return-1===this._options.externalTextures.indexOf(e)&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((e,t)=>(e.push(t.r,t.g,t.b),e),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce((e,t)=>(e.push(t.r,t.g,t.b,t.a),e),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce((e,t)=>(t.toArray(e,e.length),e),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const s=new Float32Array(16*t.length);for(let e=0;e<t.length;e++){t[e].copyToArray(s,16*e)}return this._matrixArrays[e]=s,this}setMatrix3x3(e,t){return this._checkUniform(e),this._matrices3x3[e]=t,this}setMatrix2x2(e,t){return this._checkUniform(e),this._matrices2x2[e]=t,this}setArray2(e,t){return this._checkUniform(e),this._vectors2Arrays[e]=t,this}setArray3(e,t){return this._checkUniform(e),this._vectors3Arrays[e]=t,this}setArray4(e,t){return this._checkUniform(e),this._vectors4Arrays[e]=t,this}setUniformBuffer(e,t){return-1===this._options.uniformBuffers.indexOf(e)&&this._options.uniformBuffers.push(e),this._uniformBuffers[e]=t,this}setTextureSampler(e,t){return-1===this._options.samplerObjects.indexOf(e)&&this._options.samplerObjects.push(e),this._textureSamplers[e]=t,this}setStorageBuffer(e,t){return-1===this._options.storageBuffers.indexOf(e)&&this._options.storageBuffers.push(e),this._storageBuffers[e]=t,this}setDefine(e,t){const s=e.trimEnd()+" ",i=this.options.defines.findIndex(t=>t===e||t.startsWith(s));return i>=0&&this.options.defines.splice(i,1),("boolean"!=typeof t||t)&&this.options.defines.push(s+t),this}isReadyForSubMesh(e,t,s){return this.isReady(e,s,t)}isReady(e,t,s){const i=s&&this._storeEffectOnSubMeshes;if(this.isFrozen){const e=i?s._drawWrapper:this._drawWrapper;if(e.effect&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}const r=this.getScene(),n=r.getEngine(),a=[],o=[];let h=null,l=this._shaderPath,c=this._options.uniforms,u=this._options.uniformBuffers,d=this._options.samplers;n.getCaps().multiview&&r.activeCamera&&r.activeCamera.outputRenderTarget&&r.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,a.push("#define MULTIVIEW"),-1!==c.indexOf("viewProjection")&&-1===c.indexOf("viewProjectionR")&&c.push("viewProjectionR"));for(let e=0;e<this._options.defines.length;e++){const t=0===this._options.defines[e].indexOf("#define")?this._options.defines[e]:`#define ${this._options.defines[e]}`;a.push(t)}for(let e=0;e<this._options.attributes.length;e++)o.push(this._options.attributes[e]);if(e&&e.isVerticesDataPresent(Gi.ColorKind)&&(-1===o.indexOf(Gi.ColorKind)&&o.push(Gi.ColorKind),a.push("#define VERTEXCOLOR")),t&&(a.push("#define INSTANCES"),Qr(o,this._materialHelperNeedsPreviousMatrices),e?.hasThinInstances&&(a.push("#define THIN_INSTANCES"),e&&e.isVerticesDataPresent(Gi.ColorInstanceKind)&&(o.push(Gi.ColorInstanceKind),a.push("#define INSTANCESCOLOR")))),e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton){o.push(Gi.MatricesIndicesKind),o.push(Gi.MatricesWeightsKind),e.numBoneInfluencers>4&&(o.push(Gi.MatricesIndicesExtraKind),o.push(Gi.MatricesWeightsExtraKind));const t=e.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),h=new Th,h.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(a.push("#define BONETEXTURE"),-1===c.indexOf("boneTextureInfo")&&c.push("boneTextureInfo"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(a.push("#define BonesPerMesh "+(t.bones.length+1)),-1===c.indexOf("mBones")&&c.push("mBones"))}else a.push("#define NUM_BONE_INFLUENCERS 0");let _=0;const p=e?e.morphTargetManager:null;if(p){const t=-1!==a.indexOf("#define UV1"),s=-1!==a.indexOf("#define UV2"),i=-1!==a.indexOf("#define TANGENT"),r=-1!==a.indexOf("#define NORMAL"),n=-1!==a.indexOf("#define VERTEXCOLOR");_=$r(p,a,o,e,!0,r,i,t,s,n),p.isUsingTextureForTargets&&(-1===c.indexOf("morphTargetTextureIndices")&&c.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),_>0&&(c=c.slice(),c.push("morphTargetInfluences"),c.push("morphTargetCount"),c.push("morphTargetTextureInfo"),c.push("morphTargetTextureIndices"))}else a.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const s=e.bakedVertexAnimationManager;s&&s.isEnabled&&(a.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===c.indexOf("bakedVertexAnimationSettings")&&c.push("bakedVertexAnimationSettings"),-1===c.indexOf("bakedVertexAnimationTextureSizeInverted")&&c.push("bakedVertexAnimationTextureSizeInverted"),-1===c.indexOf("bakedVertexAnimationTime")&&c.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture"),t&&o.push("bakedVertexAnimationSettingsInstanced"))}for(const e in this._textures)if(!this._textures[e].isReady())return!1;for(const e in this._internalTextures)if(!this._internalTextures[e].isReady)return!1;e&&this.needAlphaTestingForMesh(e)&&a.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&(Vr(c),Hr(this,r,a)),r.fogEnabled&&e?.applyFog&&r.fogMode!==Qo.FOGMODE_NONE&&(a.push("#define FOG"),-1===c.indexOf("view")&&c.push("view"),-1===c.indexOf("vFogInfos")&&c.push("vFogInfos"),-1===c.indexOf("vFogColor")&&c.push("vFogColor")),this._useLogarithmicDepth&&(a.push("#define LOGARITHMICDEPTH"),-1===c.indexOf("logarithmicDepthConstant")&&c.push("logarithmicDepthConstant"));const f=s?s.getRenderingMesh():e;if(f&&this.useVertexPulling){const e=f.geometry;e&&(this._vertexPullingMetadata=Gh(e),this._vertexPullingMetadata&&this._vertexPullingMetadata.forEach((e,t)=>{c.push(`vp_${t}_info`)})),a.push("#define USE_VERTEX_PULLING");const t=f.geometry?.getIndexBuffer();t&&!f.isUnIndexed&&(a.push("#define VERTEX_PULLING_USE_INDEX_BUFFER"),t.is32Bits&&a.push("#define VERTEX_PULLING_INDEX_BUFFER_32BITS"))}this.customShaderNameResolve&&(c=c.slice(),u=u.slice(),d=d.slice(),l=this.customShaderNameResolve(this.name,c,u,d,a,o));const g=i?s._getDrawWrapper(void 0,!0):this._drawWrapper,m=g?.effect??null,T=g?.defines??null,E=a.join("\n");let R=m;return T!==E&&(R=n.createEffect(l,{attributes:o,uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:E,fallbacks:h,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:_},shaderLanguage:this._options.shaderLanguage,extraInitializationsAsync:this._options.extraInitializationsAsync},n),i?s.setEffect(R,E,this._materialContext):g&&g.setEffect(R,E),this._onEffectCreatedObservable&&(Hh.effect=R,Hh.subMesh=s??e?.subMeshes[0]??null,this._onEffectCreatedObservable.notifyObservers(Hh))),g._wasPreviouslyUsingInstances=!!t,!!R?.isReady()&&(m!==R&&r.resetCachedMaterial(),g._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const s=t??this.getEffect();if(!s)return;const i=this._options.uniforms;-1!==i.indexOf("world")&&s.setMatrix("world",e);const r=this.getScene();-1!==i.indexOf("worldView")&&(e.multiplyToRef(r.getViewMatrix(),this._cachedWorldViewMatrix),s.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==i.indexOf("worldViewProjection")&&(e.multiplyToRef(r.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),s.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),-1!==i.indexOf("view")&&s.setMatrix("view",r.getViewMatrix())}bindForSubMesh(e,t,s){this.bind(e,t,s._drawWrapperOverride?.effect,s)}bind(e,t,s,i){const r=i&&this._storeEffectOnSubMeshes,n=s??(r?i.effect:this.getEffect());if(!n)return;const a=this.getScene();this._activeEffect=n,this.bindOnlyWorldMatrix(e,s);const o=this._options.uniformBuffers;let h=!1;if(n&&o&&o.length>0&&a.getEngine().supportsUniformBuffers)for(let s=0;s<o.length;++s){switch(o[s]){case"Mesh":t&&(t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e));break;case"Scene":en(n,a.getSceneUniformBuffer()),a.finalizeSceneUbo(),h=!0}}const l=t&&r?this._mustRebind(a,n,i,t.visibility):a.getCachedMaterial()!==this;if(n&&l){let e;for(e in h||-1===this._options.uniforms.indexOf("view")||n.setMatrix("view",a.getViewMatrix()),h||-1===this._options.uniforms.indexOf("projection")||n.setMatrix("projection",a.getProjectionMatrix()),h||-1===this._options.uniforms.indexOf("viewProjection")||(n.setMatrix("viewProjection",a.getTransformMatrix()),this._multiview&&n.setMatrix("viewProjectionR",a._transformMatrixR)),a.activeCamera&&-1!==this._options.uniforms.indexOf("cameraPosition")&&n.setVector3("cameraPosition",a.activeCamera.globalPosition),on(t,n),zr(n,this,a),this._vertexPullingMetadata&&Vh(n,this._vertexPullingMetadata),this._useLogarithmicDepth&&Kr(r?i.materialDefines:n.defines,n,a),t&&qr(a,t,n),this._textures)n.setTexture(e,this._textures[e]);for(e in this._internalTextures)n._bindTexture(e,this._internalTextures[e]);for(e in this._textureArrays)n.setTextureArray(e,this._textureArrays[e]);for(e in this._ints)n.setInt(e,this._ints[e]);for(e in this._uints)n.setUInt(e,this._uints[e]);for(e in this._floats)n.setFloat(e,this._floats[e]);for(e in this._floatsArrays)n.setArray(e,this._floatsArrays[e]);for(e in this._colors3)n.setColor3(e,this._colors3[e]);for(e in this._colors3Arrays)n.setArray3(e,this._colors3Arrays[e]);for(e in this._colors4){const t=this._colors4[e];n.setFloat4(e,t.r,t.g,t.b,t.a)}for(e in this._colors4Arrays)n.setArray4(e,this._colors4Arrays[e]);for(e in this._vectors2)n.setVector2(e,this._vectors2[e]);for(e in this._vectors3)n.setVector3(e,this._vectors3[e]);for(e in this._vectors4)n.setVector4(e,this._vectors4[e]);for(e in this._quaternions)n.setQuaternion(e,this._quaternions[e]);for(e in this._matrices)n.setMatrix(e,this._matrices[e]);for(e in this._matrixArrays)n.setMatrices(e,this._matrixArrays[e]);for(e in this._matrices3x3)n.setMatrix3x3(e,this._matrices3x3[e]);for(e in this._matrices2x2)n.setMatrix2x2(e,this._matrices2x2[e]);for(e in this._vectors2Arrays)n.setArray2(e,this._vectors2Arrays[e]);for(e in this._vectors3Arrays)n.setArray3(e,this._vectors3Arrays[e]);for(e in this._vectors4Arrays)n.setArray4(e,this._vectors4Arrays[e]);for(e in this._quaternionsArrays)n.setArray4(e,this._quaternionsArrays[e]);for(e in this._uniformBuffers){const t=this._uniformBuffers[e].getBuffer();t&&n.bindUniformBuffer(t,e)}const s=a.getEngine(),o=s.setExternalTexture;if(o)for(e in this._externalTextures)o.call(s,e,this._externalTextures[e]);const l=s.setTextureSampler;if(l)for(e in this._textureSamplers)l.call(s,e,this._textureSamplers[e]);const c=s.setStorageBuffer;if(c)for(e in this._storageBuffers)c.call(s,e,this._storageBuffers[e])}if(n&&t&&(l||!this.isFrozen)){Jr(t,n),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(n);const e=t.bakedVertexAnimationManager;if(e&&e.isEnabled){const e=r?i._drawWrapper:this._drawWrapper;t.bakedVertexAnimationManager?.bind(n,!!e._wasPreviouslyUsingInstances)}}this._afterBind(t,n,i)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const s=this._textureArrays[t];for(let t=0;t<s.length;t++)e.push(s[t])}return e}hasTexture(e){if(super.hasTexture(e))return!0;for(const t in this._textures)if(this._textures[t]===e)return!0;const t=e.getInternalTexture();for(const e in this._internalTextures)if(this._internalTextures[e]===t)return!0;for(const t in this._textureArrays){const s=this._textureArrays[t];for(let t=0;t<s.length;t++)if(s[t]===e)return!0}return!1}clone(e){const t=$e.Clone(()=>new zh(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath={...t._shaderPath}),this._options={...this._options};const s=Object.keys(this._options);for(const e of s){const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))}this.stencil.copyTo(t.stencil);for(const e in this._textures)t.setTexture(e,this._textures[e]);for(const e in this._internalTextures)t.setInternalTexture(e,this._internalTextures[e]);for(const e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(const e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(const e in this._ints)t.setInt(e,this._ints[e]);for(const e in this._uints)t.setUInt(e,this._uints[e]);for(const e in this._floats)t.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(const e in this._colors3)t.setColor3(e,this._colors3[e]);for(const e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(const e in this._colors4)t.setColor4(e,this._colors4[e]);for(const e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(const e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(const e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(const e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(const e in this._matrices)t.setMatrix(e,this._matrices[e]);for(const e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(const e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(const e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(const e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(const e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(const e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(const e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(const e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(const e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,s){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._internalTextures)this._internalTextures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;e<t.length;e++)t[e].dispose()}}this._textures={},this._internalTextures={},super.dispose(e,t,s)}serialize(){const e=$e.Serialize(this);let t;for(t in e.customType="BABYLON.ShaderMaterial",e.uniqueId=this.uniqueId,e.options=this._options,e.shaderPath=this._shaderPath,e.storeEffectOnSubMeshes=this._storeEffectOnSubMeshes,e.stencil=this.stencil.serialize(),e.textures={},this._textures)e.textures[t]=this._textures[t].serialize();for(t in e.textureArrays={},this._textureArrays){e.textureArrays[t]=[];const s=this._textureArrays[t];for(let i=0;i<s.length;i++)e.textureArrays[t].push(s[i].serialize())}for(t in e.ints={},this._ints)e.ints[t]=this._ints[t];for(t in e.uints={},this._uints)e.uints[t]=this._uints[t];for(t in e.floats={},this._floats)e.floats[t]=this._floats[t];for(t in e.floatsArrays={},this._floatsArrays)e.floatsArrays[t]=this._floatsArrays[t];for(t in e.colors3={},this._colors3){const s=this._colors3[t];e.colors3[t]=[s.r,s.g,s.b]}for(t in e.colors3Arrays={},this._colors3Arrays)e.colors3Arrays[t]=this._colors3Arrays[t];for(t in e.colors4={},this._colors4){const s=this._colors4[t];e.colors4[t]=[s.r,s.g,s.b,s.a]}for(t in e.colors4Arrays={},this._colors4Arrays)e.colors4Arrays[t]=this._colors4Arrays[t];for(t in e.vectors2={},this._vectors2){const s=this._vectors2[t];e.vectors2[t]=[s.x,s.y]}for(t in e.vectors3={},this._vectors3){const s=this._vectors3[t];e.vectors3[t]=[s.x,s.y,s.z]}for(t in e.vectors4={},this._vectors4){const s=this._vectors4[t];e.vectors4[t]=[s.x,s.y,s.z,s.w]}for(t in e.quaternions={},this._quaternions)e.quaternions[t]=this._quaternions[t].asArray();for(t in e.matrices={},this._matrices)e.matrices[t]=this._matrices[t].asArray();for(t in e.matrixArray={},this._matrixArrays)e.matrixArray[t]=this._matrixArrays[t];for(t in e.matrices3x3={},this._matrices3x3)e.matrices3x3[t]=this._matrices3x3[t];for(t in e.matrices2x2={},this._matrices2x2)e.matrices2x2[t]=this._matrices2x2[t];for(t in e.vectors2Arrays={},this._vectors2Arrays)e.vectors2Arrays[t]=this._vectors2Arrays[t];for(t in e.vectors3Arrays={},this._vectors3Arrays)e.vectors3Arrays[t]=this._vectors3Arrays[t];for(t in e.vectors4Arrays={},this._vectors4Arrays)e.vectors4Arrays[t]=this._vectors4Arrays[t];for(t in e.quaternionsArrays={},this._quaternionsArrays)e.quaternionsArrays[t]=this._quaternionsArrays[t];return e}}function Wh(e,t,s){const i=$e.Parse(()=>new zh(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,s);let r;for(r in e.stencil&&i.stencil.parse(e.stencil,t,s),e.textures)i.setTexture(r,Ch.Parse(e.textures[r],t,s));for(r in e.textureArrays){const n=e.textureArrays[r],a=[];for(let e=0;e<n.length;e++)a.push(Ch.Parse(n[e],t,s));i.setTextureArray(r,a)}for(r in e.ints)i.setInt(r,e.ints[r]);for(r in e.uints)i.setUInt(r,e.uints[r]);for(r in e.floats)i.setFloat(r,e.floats[r]);for(r in e.floatsArrays)i.setFloats(r,e.floatsArrays[r]);for(r in e.colors3){const t=e.colors3[r];i.setColor3(r,{r:t[0],g:t[1],b:t[2]})}for(r in e.colors3Arrays){const t=e.colors3Arrays[r].reduce((e,t,s)=>(s%3==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>({r:e[0],g:e[1],b:e[2]}));i.setColor3Array(r,t)}for(r in e.colors4){const t=e.colors4[r];i.setColor4(r,{r:t[0],g:t[1],b:t[2],a:t[3]})}for(r in e.colors4Arrays){const t=e.colors4Arrays[r].reduce((e,t,s)=>(s%4==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>({r:e[0],g:e[1],b:e[2],a:e[3]}));i.setColor4Array(r,t)}for(r in e.vectors2){const t=e.vectors2[r];i.setVector2(r,{x:t[0],y:t[1]})}for(r in e.vectors3){const t=e.vectors3[r];i.setVector3(r,{x:t[0],y:t[1],z:t[2]})}for(r in e.vectors4){const t=e.vectors4[r];i.setVector4(r,{x:t[0],y:t[1],z:t[2],w:t[3]})}for(r in e.quaternions)i.setQuaternion(r,ve.FromArray(e.quaternions[r]));for(r in e.matrices)i.setMatrix(r,Ie.FromArray(e.matrices[r]));const n=i;for(r in e.matrixArray)n._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)i.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)i.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)i.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)i.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)i.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)i.setArray4(r,e.quaternionsArrays[r]);return i}async function Xh(e,t,s,i=""){return await new Promise((r,n)=>{const a=new at;a.addEventListener("readystatechange",()=>{if(4==a.readyState)if(200==a.status){const t=Wh(JSON.parse(a.responseText),s||ee.LastCreatedScene,i);e&&(t.name=e),r(t)}else n("Unable to load the ShaderMaterial")}),a.open("GET",t),a.send()})}async function Kh(e,t,s=""){const i=this?.SnippetUrl??zh.SnippetUrl;return await new Promise((r,n)=>{const a=new at;a.addEventListener("readystatechange",()=>{if(4==a.readyState)if(200==a.status){const i=JSON.parse(JSON.parse(a.responseText).jsonPayload),n=Wh(JSON.parse(i.shaderMaterial),t||ee.LastCreatedScene,s);n.snippetId=e,r(n)}else n("Unable to load the snippet "+e)}),a.open("GET",i+"/"+e.replace(/#/g,"/")),a.send()})}zh.SnippetUrl=dt.SnippetUrl;const Yh=Kh;let jh=!1;function qh(){jh||(jh=!0,zh.Parse=Wh,zh.ParseFromFileAsync=Xh,zh.ParseFromSnippetAsync=Kh,zh.CreateFromSnippetAsync=Yh,be("BABYLON.ShaderMaterial",zh))}class $h{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new Zh(e)}sampleFrame(e=nt.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){const t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){const e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}}class Zh{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const e=this._samples[this._pos];t=e-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(e-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;const t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){const t=this._samples.length;return(e%t+t)%t}}function Qh(e,t,s){e._onCanvasFocus=()=>{e.onCanvasFocusObservable.notifyObservers(e)},e._onCanvasBlur=()=>{e.onCanvasBlurObservable.notifyObservers(e)},e._onCanvasContextMenu=t=>{e.disableContextMenu&&t.preventDefault()},t.addEventListener("focus",e._onCanvasFocus),t.addEventListener("blur",e._onCanvasBlur),t.addEventListener("contextmenu",e._onCanvasContextMenu),e._onBlur=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.disable(),e._windowIsBackground=!0},e._onFocus=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.enable(),e._windowIsBackground=!1},e._onCanvasPointerOut=s=>{document.elementFromPoint(s.clientX,s.clientY)!==t&&e.onCanvasPointerOutObservable.notifyObservers(s)};const i=e.getHostWindow();i&&"function"==typeof i.addEventListener&&(i.addEventListener("blur",e._onBlur),i.addEventListener("focus",e._onFocus)),t.addEventListener("pointerout",e._onCanvasPointerOut),s.doNotHandleTouchAction||function(e){e&&e.setAttribute&&(e.setAttribute("touch-action","none"),e.style.touchAction="none",e.style.webkitTapHighlightColor="transparent")}(t),!Ti.audioEngine&&s.audioEngine&&Ti.AudioEngineFactory&&(Ti.audioEngine=Ti.AudioEngineFactory(e.getRenderingCanvas(),e.getAudioContext(),e.getAudioDestination())),tt()&&(e._onFullscreenChange=()=>{e.isFullscreen=!!document.fullscreenElement,e.isFullscreen&&e._pointerLockRequested&&t&&al(t)},document.addEventListener("fullscreenchange",e._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",e._onFullscreenChange,!1),e._onPointerLockChange=()=>{e.isPointerLock=document.pointerLockElement===t},document.addEventListener("pointerlockchange",e._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",e._onPointerLockChange,!1)),e.enableOfflineSupport=void 0!==Ti.OfflineProviderFactory,e._deterministicLockstep=!!s.deterministicLockstep,e._lockstepMaxSteps=s.lockstepMaxSteps||0,e._timeStep=s.timeStep||1/60}function Jh(e,t){1===ee.Instances.length&&Ti.audioEngine&&(Ti.audioEngine.dispose(),Ti.audioEngine=null);const s=e.getHostWindow();s&&"function"==typeof s.removeEventListener&&(s.removeEventListener("blur",e._onBlur),s.removeEventListener("focus",e._onFocus)),t&&(t.removeEventListener("focus",e._onCanvasFocus),t.removeEventListener("blur",e._onCanvasBlur),t.removeEventListener("pointerout",e._onCanvasPointerOut),t.removeEventListener("contextmenu",e._onCanvasContextMenu)),tt()&&(document.removeEventListener("fullscreenchange",e._onFullscreenChange),document.removeEventListener("mozfullscreenchange",e._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",e._onFullscreenChange),document.removeEventListener("msfullscreenchange",e._onFullscreenChange),document.removeEventListener("pointerlockchange",e._onPointerLockChange),document.removeEventListener("mspointerlockchange",e._onPointerLockChange),document.removeEventListener("mozpointerlockchange",e._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",e._onPointerLockChange))}function el(e){const t=function(e){if(!tt()||!document.body)return null;const t=document.createElement("span");t.textContent="Hg",t.style.font=e;const s=document.createElement("div");s.style.display="inline-block",s.style.width="1px",s.style.height="0px",s.style.verticalAlign="bottom";const i=document.createElement("div");let r,n;i.style.whiteSpace="nowrap",i.appendChild(t),i.appendChild(s),document.body.appendChild(i);try{n=s.getBoundingClientRect().top-t.getBoundingClientRect().top,s.style.verticalAlign="baseline",r=s.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(i)}const a={ascent:r,height:n,descent:n-r};return tl(a)?a:null}(e);if(t)return t;const s=function(e){let t=null;try{"undefined"!=typeof OffscreenCanvas?t=new OffscreenCanvas(64,64):tt()&&"function"==typeof document.createElement&&(t=document.createElement("canvas"),t.width=64,t.height=64);const s=t?.getContext("2d");if(!s)return null;s.font=e;const i=s.measureText("Hg"),r=Number(i.actualBoundingBoxAscent??i.fontBoundingBoxAscent),n=Number(i.actualBoundingBoxDescent??i.fontBoundingBoxDescent),a={ascent:r,height:r+n,descent:n};return tl(a)?a:null}catch{return null}finally{const e=t;"function"==typeof e?.dispose&&e.dispose()}}(e);return s||function(e){const t=Math.max(1,function(e){const t=/(?:^|\s)([0-9]+(?:\.[0-9]+)?)px(?:\/|\s|$)/.exec(String(e||""));return t?Number(t[1]):16}(e)),s=.8*t,i=.2*t;return{ascent:s,height:s+i,descent:i}}(e)}function tl(e){return Number.isFinite(e.ascent)&&Number.isFinite(e.height)&&Number.isFinite(e.descent)&&e.height>0}async function sl(e,t,s){return await new Promise((i,r)=>{const n=new Image;n.onload=()=>{n.decode().then(()=>{e.createImageBitmap(n,s).then(e=>{i(e)})})},n.onerror=()=>{r(`Error loading image ${n.src}`)},n.src=t})}function il(e,t,s,i){const r=e.createCanvas(s,i).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");r.drawImage(t,0,0);return r.getImageData(0,0,s,i).data}function rl(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}function nl(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}function al(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then(()=>{e.focus()}).catch(()=>{}):e.focus()}}function ol(){document.exitPointerLock&&document.exitPointerLock()}let hl=!1;function ll(){hl||(hl=!0,Ti.prototype.getInputElement=function(){return this._renderingCanvas},Ti.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},Ti.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},Ti.prototype.getAspectRatio=function(e,t=!1){const s=e.viewport;return this.getRenderWidth(t)*s.width/(this.getRenderHeight(t)*s.height)},Ti.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},Ti.prototype._verifyPointerLock=function(){this._onPointerLockChange?.()})}class cl extends Ni{static get NpmPackage(){return Ti.NpmPackage}static get Version(){return Ti.Version}static get Instances(){return ee.Instances}static get LastCreatedEngine(){return ee.LastCreatedEngine}static get LastCreatedScene(){return ee.LastCreatedScene}static DefaultLoadingScreenFactory(e){return Ti.DefaultLoadingScreenFactory(e)}get _supportsHardwareTextureRescaling(){return!!cl._RescalePostProcessFactory}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}get performanceMonitor(){return this._performanceMonitor}constructor(e,t,s,i=!1){ll(),Ri(),super(e,t,s,i),this._performanceMonitor=new $h,this._drawCalls=new Ko,e&&(this._features.supportRenderPasses=!0)}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),Qh(this,e,this._creationOptions)}resizeImageBitmap(e,t,s){return il(this,e,t,s)}async _createImageBitmapFromSource(e,t){return await sl(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&rl(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&nl()}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}setDirectViewport(e,t,s,i){const r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,s,i),r}scissorClear(e,t,s,i,r){this.enableScissor(e,t,s,i),this.clear(r,!0,!0,!0),this.disableScissor()}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return el(e)}enterPointerlock(){this._renderingCanvas&&al(this._renderingCanvas)}exitPointerlock(){ol()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){const t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,s,i,r,n=null){r=r||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const a=super.createShaderProgram(e,t,s,i,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),a}_createShaderProgram(e,t,s,i,r=null){const n=i.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");if(i.attachShader(n,t),i.attachShader(n,s),this.webGLVersion>1&&r){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=t}return i.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=i,e.vertexShader=t,e.fragmentShader=s,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e);for(const t of this.scenes){for(const s of t.postProcesses)s._outputTexture===e&&(s._outputTexture=null);for(const s of t.cameras)for(const t of s._postProcesses)t&&t._outputTexture===e&&(t._outputTexture=null)}}_rescaleTexture(e,t,s,i,r){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:dt.TEXTURETYPE_UNSIGNED_INT,samplingMode:dt.TEXTURE_BILINEAR_SAMPLINGMODE,generateDepthBuffer:!1,generateStencilBuffer:!1});if(!this._rescalePostProcess&&cl._RescalePostProcessFactory&&(this._rescalePostProcess=cl._RescalePostProcessFactory(this)),this._rescalePostProcess){this._rescalePostProcess.externalTextureSamplerBinding=!0;const a=()=>{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let a=s;a||(a=this.scenes[this.scenes.length-1]),a.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,i,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()},o=this._rescalePostProcess.getEffect();o?o.executeWhenCompiled(a):this._rescalePostProcess.onEffectCreatedObservable.addOnce(e=>{e.executeWhenCompiled(a)})}}wrapWebGLTexture(e,t=!1,s=dt.TEXTURE_TRILINEAR_SAMPLINGMODE,i=0,r=0){const n=new Oi(e,this._gl),a=new gi(this,15,!0);return a._hardwareTexture=n,a.baseWidth=i,a.baseHeight=r,a.width=i,a.height=r,a.isReady=!0,a.useMipMaps=t,this.updateTextureSamplingMode(s,a),a}updateWrappedWebGLTexture(e,t){if(15!==e.source)throw new Error("updateWrappedWebGLTexture: target InternalTexture was not produced by wrapWebGLTexture.");for(const t of this._renderTargetWrapperCache)if(t.textures?.includes(e)){if(t.isMulti)throw new Error("updateWrappedWebGLTexture: wrapped texture is part of a multi render-target; not supported. Dispose and re-wrap.");if(t._depthStencilTexture)throw new Error("updateWrappedWebGLTexture: wrapped texture's render-target wrapper has a depth/stencil texture; not supported. Dispose and re-wrap.")}e._hardwareTexture=new Oi(t,this._gl),e.isReady=!0,e._cachedCoordinatesMode=null,e._cachedWrapU=null,e._cachedWrapV=null,e._cachedWrapR=null,e._cachedAnisotropicFilteringLevel=null;for(const t in this._boundTexturesCache)this._boundTexturesCache[t]===e&&(this._boundTexturesCache[t]=null);this.updateTextureSamplingMode(e.samplingMode,e);const s=this._gl;for(const i of this._renderTargetWrapperCache){if(i.texture!==e)continue;const r=i,n=i.samples,a=n>1;r._framebuffer&&s.deleteFramebuffer(r._framebuffer),!a&&r._depthStencilBuffer&&(s.deleteRenderbuffer(r._depthStencilBuffer),r._depthStencilBuffer=null);const o=this._currentFramebuffer,h=s.createFramebuffer();this._bindUnboundFramebuffer(h),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,t,0),a||(r._depthStencilBuffer=this._setupFramebufferDepthAttachments(i._generateStencilBuffer,i._generateDepthBuffer,i.width,i.height)),this._bindUnboundFramebuffer(o),r._framebuffer=h,a&&(i._samples=1,this.updateRenderTargetTextureSampleCount(r,n))}}_uploadImageToTexture(e,t,s=0,i=0){const r=this._gl,n=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,a),h=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(h,e,!0),this._unpackFlipY(e.invertY);let l=r.TEXTURE_2D;e.isCube&&(l=r.TEXTURE_CUBE_MAP_POSITIVE_X+s),r.texImage2D(l,i,o,a,n,t),this._bindTextureDirectly(h,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void a.Error("WebGL 1 does not support texture comparison.");const s=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_COMPARE_FUNC,dt.LEQUAL),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_COMPARE_MODE,s.NONE)):(s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_COMPARE_FUNC,t),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_COMPARE_FUNC,dt.LEQUAL),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_COMPARE_MODE,s.NONE)):(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_COMPARE_FUNC,t),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");const s=new Ci(t);return s.capacity=e,this.bindArrayBuffer(s),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),s.references=1,s}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}async _clientWaitAsync(e,t=0,s=10){const i=this._gl;return await new Promise((r,n)=>{Yt(()=>{const s=i.clientWaitSync(e,t,0);if(s==i.WAIT_FAILED)throw new Error("clientWaitSync failed");return s!=i.TIMEOUT_EXPIRED},r,n,s)})}_readPixelsAsync(e,t,s,i,r,n,a){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const o=this._gl,h=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,h),o.bufferData(o.PIXEL_PACK_BUFFER,a.byteLength,o.STREAM_READ),o.readPixels(e,t,s,i,r,n,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);const l=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return l?(o.flush(),this._clientWaitAsync(l,0,10).then(()=>(o.deleteSync(l),o.bindBuffer(o.PIXEL_PACK_BUFFER,h),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,a),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(h),a))):null}dispose(){this.hideLoadingUI?.(),this._rescalePostProcess&&this._rescalePostProcess.dispose(),Jh(this,this._renderingCanvas),super.dispose()}}function ul(e){const t=e.getCaps().maxVertexUniformVectors,s=Math.max(t-40,0),i=Math.floor(s/5);return Math.min(Math.max(i,1),256)}cl.ALPHA_DISABLE=dt.ALPHA_DISABLE,cl.ALPHA_ADD=dt.ALPHA_ADD,cl.ALPHA_COMBINE=dt.ALPHA_COMBINE,cl.ALPHA_SUBTRACT=dt.ALPHA_SUBTRACT,cl.ALPHA_MULTIPLY=dt.ALPHA_MULTIPLY,cl.ALPHA_MAXIMIZED=dt.ALPHA_MAXIMIZED,cl.ALPHA_ONEONE=dt.ALPHA_ONEONE,cl.ALPHA_PREMULTIPLIED=dt.ALPHA_PREMULTIPLIED,cl.ALPHA_PREMULTIPLIED_PORTERDUFF=dt.ALPHA_PREMULTIPLIED_PORTERDUFF,cl.ALPHA_INTERPOLATE=dt.ALPHA_INTERPOLATE,cl.ALPHA_SCREENMODE=dt.ALPHA_SCREENMODE,cl.DELAYLOADSTATE_NONE=dt.DELAYLOADSTATE_NONE,cl.DELAYLOADSTATE_LOADED=dt.DELAYLOADSTATE_LOADED,cl.DELAYLOADSTATE_LOADING=dt.DELAYLOADSTATE_LOADING,cl.DELAYLOADSTATE_NOTLOADED=dt.DELAYLOADSTATE_NOTLOADED,cl.NEVER=dt.NEVER,cl.ALWAYS=dt.ALWAYS,cl.LESS=dt.LESS,cl.EQUAL=dt.EQUAL,cl.LEQUAL=dt.LEQUAL,cl.GREATER=dt.GREATER,cl.GEQUAL=dt.GEQUAL,cl.NOTEQUAL=dt.NOTEQUAL,cl.KEEP=dt.KEEP,cl.REPLACE=dt.REPLACE,cl.INCR=dt.INCR,cl.DECR=dt.DECR,cl.INVERT=dt.INVERT,cl.INCR_WRAP=dt.INCR_WRAP,cl.DECR_WRAP=dt.DECR_WRAP,cl.TEXTURE_CLAMP_ADDRESSMODE=dt.TEXTURE_CLAMP_ADDRESSMODE,cl.TEXTURE_WRAP_ADDRESSMODE=dt.TEXTURE_WRAP_ADDRESSMODE,cl.TEXTURE_MIRROR_ADDRESSMODE=dt.TEXTURE_MIRROR_ADDRESSMODE,cl.TEXTUREFORMAT_ALPHA=dt.TEXTUREFORMAT_ALPHA,cl.TEXTUREFORMAT_LUMINANCE=dt.TEXTUREFORMAT_LUMINANCE,cl.TEXTUREFORMAT_LUMINANCE_ALPHA=dt.TEXTUREFORMAT_LUMINANCE_ALPHA,cl.TEXTUREFORMAT_RGB=dt.TEXTUREFORMAT_RGB,cl.TEXTUREFORMAT_RGBA=dt.TEXTUREFORMAT_RGBA,cl.TEXTUREFORMAT_RED=dt.TEXTUREFORMAT_RED,cl.TEXTUREFORMAT_R=dt.TEXTUREFORMAT_R,cl.TEXTUREFORMAT_R16_UNORM=dt.TEXTUREFORMAT_R16_UNORM,cl.TEXTUREFORMAT_RG16_UNORM=dt.TEXTUREFORMAT_RG16_UNORM,cl.TEXTUREFORMAT_RGB16_UNORM=dt.TEXTUREFORMAT_RGB16_UNORM,cl.TEXTUREFORMAT_RGBA16_UNORM=dt.TEXTUREFORMAT_RGBA16_UNORM,cl.TEXTUREFORMAT_R16_SNORM=dt.TEXTUREFORMAT_R16_SNORM,cl.TEXTUREFORMAT_RG16_SNORM=dt.TEXTUREFORMAT_RG16_SNORM,cl.TEXTUREFORMAT_RGB16_SNORM=dt.TEXTUREFORMAT_RGB16_SNORM,cl.TEXTUREFORMAT_RGBA16_SNORM=dt.TEXTUREFORMAT_RGBA16_SNORM,cl.TEXTUREFORMAT_RG=dt.TEXTUREFORMAT_RG,cl.TEXTUREFORMAT_RED_INTEGER=dt.TEXTUREFORMAT_RED_INTEGER,cl.TEXTUREFORMAT_R_INTEGER=dt.TEXTUREFORMAT_R_INTEGER,cl.TEXTUREFORMAT_RG_INTEGER=dt.TEXTUREFORMAT_RG_INTEGER,cl.TEXTUREFORMAT_RGB_INTEGER=dt.TEXTUREFORMAT_RGB_INTEGER,cl.TEXTUREFORMAT_RGBA_INTEGER=dt.TEXTUREFORMAT_RGBA_INTEGER,cl.TEXTURETYPE_UNSIGNED_BYTE=dt.TEXTURETYPE_UNSIGNED_BYTE,cl.TEXTURETYPE_UNSIGNED_INT=dt.TEXTURETYPE_UNSIGNED_INT,cl.TEXTURETYPE_FLOAT=dt.TEXTURETYPE_FLOAT,cl.TEXTURETYPE_HALF_FLOAT=dt.TEXTURETYPE_HALF_FLOAT,cl.TEXTURETYPE_BYTE=dt.TEXTURETYPE_BYTE,cl.TEXTURETYPE_SHORT=dt.TEXTURETYPE_SHORT,cl.TEXTURETYPE_UNSIGNED_SHORT=dt.TEXTURETYPE_UNSIGNED_SHORT,cl.TEXTURETYPE_INT=dt.TEXTURETYPE_INT,cl.TEXTURETYPE_UNSIGNED_INTEGER=dt.TEXTURETYPE_UNSIGNED_INTEGER,cl.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=dt.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4,cl.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=dt.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1,cl.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=dt.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,cl.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=dt.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV,cl.TEXTURETYPE_UNSIGNED_INT_24_8=dt.TEXTURETYPE_UNSIGNED_INT_24_8,cl.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=dt.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV,cl.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=dt.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV,cl.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=dt.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV,cl.TEXTURE_NEAREST_SAMPLINGMODE=dt.TEXTURE_NEAREST_SAMPLINGMODE,cl.TEXTURE_BILINEAR_SAMPLINGMODE=dt.TEXTURE_BILINEAR_SAMPLINGMODE,cl.TEXTURE_TRILINEAR_SAMPLINGMODE=dt.TEXTURE_TRILINEAR_SAMPLINGMODE,cl.TEXTURE_NEAREST_NEAREST_MIPLINEAR=dt.TEXTURE_NEAREST_NEAREST_MIPLINEAR,cl.TEXTURE_LINEAR_LINEAR_MIPNEAREST=dt.TEXTURE_LINEAR_LINEAR_MIPNEAREST,cl.TEXTURE_LINEAR_LINEAR_MIPLINEAR=dt.TEXTURE_LINEAR_LINEAR_MIPLINEAR,cl.TEXTURE_NEAREST_NEAREST_MIPNEAREST=dt.TEXTURE_NEAREST_NEAREST_MIPNEAREST,cl.TEXTURE_NEAREST_LINEAR_MIPNEAREST=dt.TEXTURE_NEAREST_LINEAR_MIPNEAREST,cl.TEXTURE_NEAREST_LINEAR_MIPLINEAR=dt.TEXTURE_NEAREST_LINEAR_MIPLINEAR,cl.TEXTURE_NEAREST_LINEAR=dt.TEXTURE_NEAREST_LINEAR,cl.TEXTURE_NEAREST_NEAREST=dt.TEXTURE_NEAREST_NEAREST,cl.TEXTURE_LINEAR_NEAREST_MIPNEAREST=dt.TEXTURE_LINEAR_NEAREST_MIPNEAREST,cl.TEXTURE_LINEAR_NEAREST_MIPLINEAR=dt.TEXTURE_LINEAR_NEAREST_MIPLINEAR,cl.TEXTURE_LINEAR_LINEAR=dt.TEXTURE_LINEAR_LINEAR,cl.TEXTURE_LINEAR_NEAREST=dt.TEXTURE_LINEAR_NEAREST,cl.TEXTURE_EXPLICIT_MODE=dt.TEXTURE_EXPLICIT_MODE,cl.TEXTURE_SPHERICAL_MODE=dt.TEXTURE_SPHERICAL_MODE,cl.TEXTURE_PLANAR_MODE=dt.TEXTURE_PLANAR_MODE,cl.TEXTURE_CUBIC_MODE=dt.TEXTURE_CUBIC_MODE,cl.TEXTURE_PROJECTION_MODE=dt.TEXTURE_PROJECTION_MODE,cl.TEXTURE_SKYBOX_MODE=dt.TEXTURE_SKYBOX_MODE,cl.TEXTURE_INVCUBIC_MODE=dt.TEXTURE_INVCUBIC_MODE,cl.TEXTURE_EQUIRECTANGULAR_MODE=dt.TEXTURE_EQUIRECTANGULAR_MODE,cl.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=dt.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,cl.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=dt.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,cl.SCALEMODE_FLOOR=dt.SCALEMODE_FLOOR,cl.SCALEMODE_NEAREST=dt.SCALEMODE_NEAREST,cl.SCALEMODE_CEILING=dt.SCALEMODE_CEILING;class dl extends fh{constructor(e){super(e),this.FOG=!1,this.THIN_INSTANCES=!0,this.LOGARITHMICDEPTH=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.SH_DEGREE=0,this.COMPENSATION=!1,this.IS_COMPOUND=!1,this.MAX_PART_COUNT=128,this.USE_SOG=!1,this.USE_SOG_V2=!1,this.rebuild()}hasDefine(e){return-1!==this._keys.indexOf(e)}}class _l extends gh{constructor(e,t){super(e,t),this.kernelSize=_l.KernelSize,this.minPixelSize=_l.MinPixelSize,this._compensation=_l.Compensation,this._isDirty=!1,this._sourceMesh=null,this._voxelMissingTextureWarned=new Set,this._voxelPartWorldData=new Float32Array(0),this._voxelPartVisibilityData=[],this.backFaceCulling=!1,this.shadowDepthWrapper=_l._MakeGaussianSplattingShadowDepthWrapper(t,this.shaderLanguage)}set compensation(e){this._isDirty=this._isDirty!=e,this._compensation=e}get compensation(){return this._compensation}get hasRenderTargetTextures(){return!1}needAlphaTesting(){return!1}needAlphaBlending(){return!0}isReadyForSubMesh(e,t){const s=!0,i=t._drawWrapper;let r=t.materialDefines;if(r&&this._isDirty&&r.markAsUnprocessed(),i.effect&&this.isFrozen&&i._wasPreviouslyReady&&i._wasPreviouslyUsingInstances===s)return!0;if(!t.materialDefines||this.pluginManager){this._callbackPluginEventGeneric(4,this._eventInfo);const e=this._eventInfo.defineNames;(!t.materialDefines||e&&Object.keys(e).some(e=>!r.hasDefine(e)))&&(r=t.materialDefines=new dl(e))}const n=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(!this._sourceMesh)return!1;const a=n.getEngine(),o=this._sourceMesh;pn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,r,void 0,void 0,void 0,this._isVertexOutputInvariant),En(n,a,this,r,s,null,!0),this._eventInfo.defines=r,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),An(e,r,!1,!1),this._callbackPluginEventPrepareDefines(this._eventInfo),(a.version>1||a.isWebGPU)&&(r.SH_DEGREE=o.shDegree),r.IS_COMPOUND=o.isCompound,r.MAX_PART_COUNT=ul(a),r.USE_SOG=o.useSog,r.USE_SOG_V2=o.useSog&&2===o.sogParams?.version;const h=o.material;if(r.COMPENSATION=h&&h.compensation?h.compensation:_l.Compensation,r.isDirty){r.markAsProcessed(),n.resetCachedMaterial(),dn(_l._Attribs,r);const s=_l._Attribs.slice(),i=_l._Uniforms.slice(),o=_l._Samplers.slice(),h=_l._UniformBuffers.slice();In({uniformsNames:i,uniformBuffersNames:h,samplers:o,defines:r}),Vr(i),this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._eventInfo.fallbackRank=0,this._eventInfo.defines=r,this._eventInfo.attributes=s,this._eventInfo.uniforms=i,this._eventInfo.samplers=o,this._eventInfo.uniformBuffersNames=h,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._callbackPluginEventGeneric(128,this._eventInfo);const l=r.toString(),c=n.getEngine().createEffect("gaussianSplatting",{attributes:s,uniformsNames:i,uniformBuffersNames:h,samplers:o,defines:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{},processCodeAfterIncludes:this._eventInfo.customCode,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.all([import("./gaussianSplatting.fragment-D_3hxYZc.esm.min.js"),import("./gaussianSplatting.vertex-CEgaKrG6.esm.min.js")]):await Promise.all([import("./gaussianSplatting.fragment-DTMkFTQD.esm.min.js"),import("./gaussianSplatting.vertex-aXl0JvSj.esm.min.js")])}},a);t.setEffect(c,r,this._materialContext)}return!(!t.effect||!t.effect.isReady())&&(r._renderId=n.getRenderId(),i._wasPreviouslyReady=!0,i._wasPreviouslyUsingInstances=s,this._isDirty=!1,!0)}setSourceMesh(e){this._sourceMesh=e}getSourceMesh(){return this._sourceMesh}static BindEffect(e,t,s){const i=s.getEngine(),r=s.activeCamera,n=i.getRenderWidth()*r.viewport.width,a=i.getRenderHeight()*r.viewport.height,o=e.material;if(!o._sourceMesh)return;const h=o._sourceMesh,l=r?.rigParent?.rigCameras.length||1;t.setFloat2("invViewport",1/(n/l),1/a);let c=1e3;if(r){const e=r.getProjectionMatrix().m[5];c=r.fovMode==bi.FOVMODE_VERTICAL_FIXED?a*e/2:n*e/2}if(t.setFloat2("focal",c,c),t.setFloat("kernelSize",o&&o.kernelSize?o.kernelSize:_l.KernelSize),t.setFloat("minPixelSize",o?o.minPixelSize:_l.MinPixelSize),t.setFloat("alpha",o.alpha),s.bindEyePosition(t,"eyePosition",!0),h.covariancesATexture){const e=h.covariancesATexture.getSize();if(t.setFloat2("dataTextureSize",e.width,e.height),t.setTexture("covariancesATexture",h.covariancesATexture),t.setTexture("covariancesBTexture",h.covariancesBTexture),t.setTexture("centersTexture",h.centersTexture),t.setTexture("colorsTexture",h.colorsTexture),h.useSog)_l._BindSogUniforms(h,t);else if(h.shTextures)for(let e=0;e<h.shTextures.length;e++)t.setTexture(`shTexture${e}`,h.shTextures[e]);h.bindExtraEffectUniforms(t)}}static _BindSogUniforms(e,t){const s=e.sogParams;s&&(t.setTexture("sogQuatsTexture",e.rotationsATexture),e.shTextures&&e.shTextures.length>=2&&(t.setTexture("sogShNCentroidsTexture",e.shTextures[0]),t.setTexture("sogShNLabelsTexture",e.shTextures[1])),s.codebookTexture&&t.setTexture("sogCodebookTexture",s.codebookTexture),t.setFloat3("sogMeansMin",s.meansMin[0],s.meansMin[1],s.meansMin[2]),t.setFloat3("sogMeansMax",s.meansMax[0],s.meansMax[1],s.meansMax[2]),s.scalesMin&&s.scalesMax&&(t.setFloat3("sogScalesMin",s.scalesMin[0],s.scalesMin[1],s.scalesMin[2]),t.setFloat3("sogScalesMax",s.scalesMax[0],s.scalesMax[1],s.scalesMax[2])),s.sh0Min&&s.sh0Max&&(t.setFloat4("sogSh0Min",s.sh0Min[0],s.sh0Min[1],s.sh0Min[2],s.sh0Min[3]),t.setFloat4("sogSh0Max",s.sh0Max[0],s.sh0Max[1],s.sh0Max[2],s.sh0Max[3])),t.setFloat("sogShnMin",s.shnMin??0),t.setFloat("sogShnMax",s.shnMax??0),t.setFloat("sogShCoeffCount",s.shCoeffCount??0))}bindForSubMesh(e,t,s){const i=this.getScene(),r=s.materialDefines;if(!r)return;const n=s.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e);this._mustRebind(i,n,s,t.visibility)?(this.bindView(n),this.bindViewProjection(n),_l.BindEffect(t,this._activeEffect,i),zr(n,this,i)):i.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0),qr(i,t,n),this.useLogarithmicDepth&&Kr(r,n,i),this._eventInfo.subMesh=s,this._callbackPluginEventBindForSubMesh(this._eventInfo),this._afterBind(t,this._activeEffect,s)}static _BindEffectUniforms(e,t,s,i){const r=i.getEngine(),n=s.getEffect(),a=i.activeCamera;if(!a)return;e.getMeshUniformBuffer().bindToEffect(n,"Mesh"),s.bindView(n),s.bindViewProjection(n);const o=r.getRenderWidth()*a.viewport.width,h=r.getRenderHeight()*a.viewport.height;n.setFloat2("invViewport",1/o,1/h);let l,c,u=1e3;if(a){const e=a.getProjectionMatrix().m[5];u=a.fovMode==bi.FOVMODE_VERTICAL_FIXED?h*e/2:o*e/2}n.setFloat2("focal",u,u),n.setFloat("kernelSize",t&&t.kernelSize?t.kernelSize:_l.KernelSize),n.setFloat("minPixelSize",t?t.minPixelSize:_l.MinPixelSize),n.setFloat("alpha",t.alpha);if(a.mode===bi.ORTHOGRAPHIC_CAMERA?(l=!r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1,c=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1):(l=r.useReverseDepthBuffer&&r.isNDCHalfZRange?a.minZ:r.isNDCHalfZRange?0:a.minZ,c=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:a.maxZ),n.setFloat2("depthValues",l,l+c),e.covariancesATexture){const t=e.covariancesATexture.getSize();n.setFloat2("dataTextureSize",t.width,t.height),n.setTexture("covariancesATexture",e.covariancesATexture),n.setTexture("covariancesBTexture",e.covariancesBTexture),n.setTexture("centersTexture",e.centersTexture),n.setTexture("colorsTexture",e.colorsTexture),e.bindExtraEffectUniforms(n)}}_bindVoxelEffectUniforms(e,t,s){if(!e.rotationsATexture&&(e.needsRotationScaleTextures=!0,!e.rotationsATexture))return!e.centersTexture||e.splatsData||this._voxelMissingTextureWarned.has(e.uniqueId)||(this._voxelMissingTextureWarned.add(e.uniqueId),a.Error("IBL voxelization: GaussianSplattingMesh rotation/scale textures are not available. Create the mesh either with keepInRam=true or needsRotationScaleTextures=true to enable IBL shadow voxelization.")),!1;this._voxelMissingTextureWarned.delete(e.uniqueId);const i=s.getEffect();e.getMeshUniformBuffer().bindToEffect(i,"Mesh");const r=e.rotationsATexture.getSize();if(i.setFloat("alpha",t.alpha),i.setFloat2("dataTextureSize",r.width,r.height),i.setTexture("rotationsATexture",e.rotationsATexture),i.setTexture("rotationsBTexture",e.rotationsBTexture),i.setTexture("rotationScaleTexture",e.rotationScaleTexture),i.setTexture("centersTexture",e.centersTexture),i.setTexture("colorsTexture",e.colorsTexture),e.partIndicesTexture){i.setTexture("partIndicesTexture",e.partIndicesTexture);const t=16*e.partCount;this._voxelPartWorldData.length!==t&&(this._voxelPartWorldData=new Float32Array(t));const s=this._voxelPartWorldData;for(let t=0;t<e.partCount;t++)e.getWorldMatrixForPart(t).toArray(s,16*t);i.setMatrices("partWorld",s);const r=this._voxelPartVisibilityData;r.length=e.partCount;for(let t=0;t<e.partCount;t++)r[t]=e.partVisibility[t]??1;i.setArray("partVisibility",r)}return!0}makeVoxelRenderingMaterial(e,t,s,i=!1){const r=[`#define MAX_DRAW_BUFFERS ${s}`];r.push("#define IS_FOR_VOXELIZATION"),i&&(r.push("#define IS_COMPOUND 1"),r.push(`#define MAX_PART_COUNT ${ul(e.getEngine())}`));const n=new zh("gaussianSplattingVoxelRender",e,{vertex:"gaussianSplattingVoxel",fragment:"gaussianSplattingVoxel"},{attributes:_l._Attribs,uniforms:_l._VoxelUniforms,samplers:_l._VoxelSamplers,uniformBuffers:_l._UniformBuffers,shaderLanguage:t,defines:r,needAlphaBlending:!1,extraInitializationsAsync:async()=>{1===t?await Promise.all([import("./gaussianSplattingVoxel.vertex-Vktj5LFD.esm.min.js"),import("./gaussianSplattingVoxel.fragment-BcZyXS4z.esm.min.js")]):await Promise.all([import("./gaussianSplattingVoxel.vertex-Bs6J3-l7.esm.min.js"),import("./gaussianSplattingVoxel.fragment-BRQliipZ.esm.min.js")])}});return n.cullBackFaces=!1,n.backFaceCulling=!1,n.depthFunction=cl.ALWAYS,n.onBindObservable.add(e=>{const t=e.material,s=e;this._bindVoxelEffectUniforms(s,t,n)}),n}makeDepthRenderingMaterial(e,t,s=!1,i=!1){const r=["#define DEPTH_RENDER"];s&&r.push("#define ALPHA_BLENDED_DEPTH"),i&&(r.push("#define IS_COMPOUND 1"),r.push(`#define MAX_PART_COUNT ${ul(e.getEngine())}`));const n=new zh("gaussianSplattingDepthRender",e,{vertex:"gaussianSplattingDepth",fragment:"gaussianSplattingDepth"},{attributes:_l._Attribs,uniforms:_l._Uniforms,samplers:_l._Samplers,uniformBuffers:_l._UniformBuffers,shaderLanguage:t,defines:r,needAlphaBlending:s});return n.doNotSerialize=!0,n.backFaceCulling=!1,n.onBindObservable.add(t=>{const s=t.material,i=s?.getSourceMesh()??t;_l._BindEffectUniforms(i,s,n,e)}),n}static _MakeGaussianSplattingShadowDepthWrapper(e,t){const s=new zh("gaussianSplattingDepth",e,{vertex:"gaussianSplattingDepth",fragment:"gaussianSplattingDepth"},{attributes:_l._Attribs,uniforms:_l._Uniforms,samplers:_l._Samplers,uniformBuffers:_l._UniformBuffers,shaderLanguage:t});s.doNotSerialize=!0,s.backFaceCulling=!1;const i=new Uh(s,e,{standalone:!0});return s.onBindObservable.add(t=>{const i=t.material,r=i?.getSourceMesh()??t;_l._BindEffectUniforms(r,i,s,e)}),i}clone(e){const t=$e.Clone(()=>new _l(e,this.getScene()),this);return t.id=e,t.name=e,this._clonePlugins(t,""),t}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,t,s){const i=$e.Parse(()=>new _l(e.name,t),e,t,s);return Cn._ParsePlugins(e,i,t,s),i}}_l.KernelSize=.3,_l.Compensation=!1,_l.MinPixelSize=0,_l._Attribs=[Gi.PositionKind,"splatIndex0","splatIndex1","splatIndex2","splatIndex3"],_l._Samplers=["covariancesATexture","covariancesBTexture","centersTexture","colorsTexture","shTexture0","shTexture1","shTexture2","shTexture3","shTexture4","partIndicesTexture","sogQuatsTexture","sogShNCentroidsTexture","sogShNLabelsTexture","sogCodebookTexture"],_l._UniformBuffers=["Scene","Mesh"],_l._VoxelUniforms=["world","dataTextureSize","alpha","invWorldScale","viewMatrix","nearPlane","farPlane","stepSize","partWorld","partVisibility","axis"],_l._VoxelSamplers=["rotationsATexture","rotationsBTexture","rotationScaleTexture","centersTexture","colorsTexture","partIndicesTexture"],_l._Uniforms=["world","view","projection","vFogInfos","vFogColor","logarithmicDepthConstant","invViewport","dataTextureSize","focal","eyePosition","kernelSize","minPixelSize","alpha","depthValues","partWorld","partVisibility","sogMeansMin","sogMeansMax","sogScalesMin","sogScalesMax","sogSh0Min","sogSh0Max","sogShnMin","sogShnMax","sogShCoeffCount"];class pl extends Ch{constructor(e,t,s,i,r,n=!0,a=!1,o=dt.TEXTURE_TRILINEAR_SAMPLINGMODE,h=dt.TEXTURETYPE_UNSIGNED_BYTE,l,c,u,d){super(null,r,!n,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,l),this.format=i,this._engine&&(this._engine._caps.textureFloatLinearFiltering||h!==dt.TEXTURETYPE_FLOAT||(o=dt.TEXTURE_NEAREST_SAMPLINGMODE),this._engine._caps.textureHalfFloatLinearFiltering||h!==dt.TEXTURETYPE_HALF_FLOAT||(o=dt.TEXTURE_NEAREST_SAMPLINGMODE),this._texture=this._engine.createRawTexture(e,t,s,i,n,a,o,null,h,l??0,c??!1,d),this.wrapU=Ch.CLAMP_ADDRESSMODE,this.wrapV=Ch.CLAMP_ADDRESSMODE,this._waitingForData=!!u&&!e)}update(e){this.updateMipLevel(e,0)}updateMipLevel(e,t){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer,t),this._waitingForData=!1}clone(){if(!this._texture)return super.clone();const e=new pl(null,this.getSize().width,this.getSize().height,this.format,this.getScene(),this._texture.generateMipMaps,this._invertY,this.samplingMode,this._texture.type,this._texture._creationFlags,this._useSRGBBuffer);return e._texture=this._texture,this._texture.incrementReferences(),e}isReady(){return super.isReady()&&!this._waitingForData}static CreateLuminanceTexture(e,t,s,i,r=!0,n=!1,a=dt.TEXTURE_TRILINEAR_SAMPLINGMODE){return new pl(e,t,s,dt.TEXTUREFORMAT_LUMINANCE,i,r,n,a)}static CreateLuminanceAlphaTexture(e,t,s,i,r=!0,n=!1,a=dt.TEXTURE_TRILINEAR_SAMPLINGMODE){return new pl(e,t,s,dt.TEXTUREFORMAT_LUMINANCE_ALPHA,i,r,n,a)}static CreateAlphaTexture(e,t,s,i,r=!0,n=!1,a=dt.TEXTURE_TRILINEAR_SAMPLINGMODE){return new pl(e,t,s,dt.TEXTUREFORMAT_ALPHA,i,r,n,a)}static CreateRGBTexture(e,t,s,i,r=!0,n=!1,a=dt.TEXTURE_TRILINEAR_SAMPLINGMODE,o=dt.TEXTURETYPE_UNSIGNED_BYTE,h=0,l=!1){return new pl(e,t,s,dt.TEXTUREFORMAT_RGB,i,r,n,a,o,h,l)}static CreateRGBATexture(e,t,s,i,r=!0,n=!1,a=dt.TEXTURE_TRILINEAR_SAMPLINGMODE,o=dt.TEXTURETYPE_UNSIGNED_BYTE,h=0,l=!1,c=!1){return new pl(e,t,s,dt.TEXTUREFORMAT_RGBA,i,r,n,a,o,h,l,c)}static CreateRGBAStorageTexture(e,t,s,i,r=!0,n=!1,a=dt.TEXTURE_TRILINEAR_SAMPLINGMODE,o=dt.TEXTURETYPE_UNSIGNED_BYTE,h=!1){return new pl(e,t,s,dt.TEXTUREFORMAT_RGBA,i,r,n,a,o,dt.TEXTURE_CREATIONFLAG_STORAGE,h)}static CreateRTexture(e,t,s,i,r=!0,n=!1,a=Ch.TRILINEAR_SAMPLINGMODE,o=dt.TEXTURETYPE_FLOAT){return new pl(e,t,s,dt.TEXTUREFORMAT_R,i,r,n,a,o)}static CreateRStorageTexture(e,t,s,i,r=!0,n=!1,a=Ch.TRILINEAR_SAMPLINGMODE,o=dt.TEXTURETYPE_FLOAT){return new pl(e,t,s,dt.TEXTUREFORMAT_R,i,r,n,a,o,dt.TEXTURE_CREATIONFLAG_STORAGE)}}let fl=!1;function gl(){fl||(fl=!0,Ti.prototype.createDepthStencilTexture=function(e,t,s){if(t.isCube){const s=e.width||e;return this._createDepthStencilCubeTexture(s,t)}return this._createDepthStencilTexture(e,t,s)})}class ml{get renderList(){return this._renderList}set renderList(e){this._renderList!==e&&(this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=Q(e,this._renderListHasChanged)),this._renderList=e)}get disableImageProcessing(){return this._disableImageProcessing}set disableImageProcessing(e){e!==this._disableImageProcessing&&(this._disableImageProcessing=e,this._scene.markAllMaterialsAsDirty(dt.MATERIAL_ImageProcessingDirtyFlag))}get disableDepthPrePass(){return this._disableDepthPrePass}set disableDepthPrePass(e){this._disableDepthPrePass=e,this._renderingManager.disableDepthPrePass=e}get name(){return this._name}set name(e){if(this._name!==e){if(this._name=e,this._sceneUBOs)for(let e=0;e<this._sceneUBOs.length;++e)this._sceneUBOs[e].name=`Scene ubo #${e} for ${this.name}`;if(this._scene)for(let e=0;e<this._renderPassIds.length;++e){const t=this._renderPassIds[e];this._engine._renderPassNames[t]=`${this._name}#${e}`}}}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}getActiveMeshes(){return this._activeMeshes}setMaterialForRendering(e,t){let s;s=Array.isArray(e)?e:[e];for(let e=0;e<s.length;++e)for(let i=0;i<this.options.numPasses;++i){let r=s[e];s[e].isAnInstance&&(r=s[e].sourceMesh),r.setMaterialForRenderPass(this._renderPassIds[i],void 0!==t?Array.isArray(t)?t[i]:t:void 0)}}_freezeActiveMeshes(e){this._freezeActiveMeshesCancel=Yt(()=>this._checkReadiness(),()=>{if(this._freezeActiveMeshesCancel=null,e)for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._freeze();this._prepareRenderingManager(0,!0),this._isFrozen=!0},(e,t)=>{this._freezeActiveMeshesCancel=null,t?(a.Error("ObjectRenderer: Timeout while waiting for the renderer to be ready."),e&&a.Error(e)):(a.Error("ObjectRenderer: An unexpected error occurred while waiting for the renderer to be ready."),e&&(a.Error(e),e.stack&&a.Error(e.stack)))})}_unfreezeActiveMeshes(){this._freezeActiveMeshesCancel?.(),this._freezeActiveMeshesCancel=null;for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._unFreeze();this._isFrozen=!1}constructor(e,t,s){this._unObserveRenderList=null,this._renderListHasChanged=(e,t)=>{const s=this._renderList?this._renderList.length:0;if(0===t&&s>0||0===s)for(const e of this._scene.meshes)e._markSubMeshesAsLightDirty()},this.particleSystemList=null,this.getCustomRenderList=null,this.renderMeshes=!0,this.renderDepthOnlyMeshes=!0,this.renderOpaqueMeshes=!0,this.renderAlphaTestMeshes=!0,this.renderTransparentMeshes=!0,this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.enableBoundingBoxRendering=!1,this.enableOutlineRendering=!0,this._disableImageProcessing=!1,this.dontSetTransformationMatrix=!1,this._disableDepthPrePass=!1,this.onBeforeRenderObservable=new c,this.onAfterRenderObservable=new c,this.onBeforeRenderingManagerRenderObservable=new c,this.onAfterRenderingManagerRenderObservable=new c,this.onInitRenderingObservable=new c,this.onFinishRenderingObservable=new c,this.onFastPathRenderObservable=new c,this._currentRefreshId=-1,this._refreshRate=1,this._currentApplyByPostProcessSetting=!1,this._activeMeshes=new Ws(256),this._activeBoundingBoxes=new Ws(32),this._currentFrameId=-1,this._currentSceneUBOIndex=0,this._isFrozen=!1,this._freezeActiveMeshesCancel=null,this._currentSceneCamera=null,this.name=e,this._scene=t,this._engine=this._scene.getEngine(),this._useUBO=this._engine.supportsUniformBuffers,this.renderList=[],this._renderPassIds=[],this.options={numPasses:1,doNotChangeAspectRatio:!0,enableClusteredLights:!1,...s},this._createRenderPassId(),this.renderPassId=this._renderPassIds[0],this._renderingManager=new vo(t),this._renderingManager._useSceneAutoClearSetup=!0,this.options.enableClusteredLights&&this.onInitRenderingObservable.add(()=>{for(const e of this._scene.lights)e.getTypeID()===Mr.LIGHTTYPEID_CLUSTERED_CONTAINER&&e.isSupported&&e._updateBatches(this.activeCamera).render()}),this._scene.addObjectRenderer(this)}_releaseRenderPassId(){for(let e=0;e<this.options.numPasses;++e)this._engine.releaseRenderPassId(this._renderPassIds[e]);this._renderPassIds.length=0}_createRenderPassId(){this._releaseRenderPassId();for(let e=0;e<this.options.numPasses;++e)this._renderPassIds[e]=this._engine.createRenderPassId(`${this.name}#${e}`)}_createSceneUBO(e,t){const s=this._scene.getEngine(),i=new dr(s,void 0,t,e,void 0,!1);return i.addUniform("viewProjection",16),t&&i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i.addUniform("inverseProjection",16),i}_getSceneUBO(){this._currentFrameId!==this._engine.frameId&&(this._currentSceneUBOIndex=0,this._currentFrameId=this._engine.frameId),this._sceneUBOs||(this._sceneUBOs=[],this._sceneUBOIsMultiview=[]);const e=this._engine._currentRenderTarget,t=!(!e||!e.texture?.isMultiview)||!!this._scene._multiviewSceneUboIsActive;if(this._currentSceneUBOIndex>=this._sceneUBOs.length){const e=this._sceneUBOs.length;this._sceneUBOs.push(this._createSceneUBO(`Scene ubo #${e} for ${this.name}`,t)),this._sceneUBOIsMultiview.push(t)}else this._sceneUBOIsMultiview[this._currentSceneUBOIndex]!==t&&(this._sceneUBOs[this._currentSceneUBOIndex].dispose(),this._sceneUBOs[this._currentSceneUBOIndex]=this._createSceneUBO(`Scene ubo #${this._currentSceneUBOIndex} for ${this.name}`,t),this._sceneUBOIsMultiview[this._currentSceneUBOIndex]=t);const s=this._sceneUBOs[this._currentSceneUBOIndex++];return s.unbindEffect(),s}resetRefreshCounter(){this._currentRefreshId=-1}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}shouldRender(){return!!this._engine.snapshotRendering||(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1))}isReadyForRendering(e,t){this.prepareRenderList(),this.initRender(e,t);const s=this._checkReadiness();return this.finishRender(),s}prepareRenderList(){const e=this._scene;if(this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let t=0;t<this._waitingRenderList.length;t++){const s=this._waitingRenderList[t],i=e.getMeshById(s);i&&this.renderList.push(i)}}this._waitingRenderList=void 0}if(this.renderListPredicate){this.renderList?this.renderList.length=0:this.renderList=[];const e=this._scene.meshes;for(let t=0;t<e.length;t++){const s=e[t];this.renderListPredicate(s)&&this.renderList.push(s)}}this._currentApplyByPostProcessSetting=this._scene.imageProcessingConfiguration.applyByPostProcess,this._disableImageProcessing&&(this._scene.imageProcessingConfiguration._applyByPostProcess=this._disableImageProcessing)}initRender(e,t){const s=this.activeCamera??this._scene.activeCamera;this._currentSceneCamera=this._scene.activeCamera,this._useUBO&&(this._currentSceneUBO=this._scene.getSceneUniformBuffer(),this._currentSceneUBO.unbindEffect(),this._scene.setSceneUniformBuffer(this._getSceneUBO())),this.onInitRenderingObservable.notifyObservers(this),s&&(this.dontSetTransformationMatrix||this._scene.setTransformMatrix(s.getViewMatrix(),s.getProjectionMatrix(!0)),this._scene._activeCamera=s,this._engine.setViewport(s.rigParent?s.rigParent.viewport:s.viewport,e,t)),this._useUBO&&this._scene.finalizeSceneUbo(),this._defaultRenderListPrepared=!1}finishRender(){const e=this._scene;this._useUBO&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._disableImageProcessing&&(e.imageProcessingConfiguration._applyByPostProcess=this._currentApplyByPostProcessSetting),e._activeCamera=this._currentSceneCamera,this._currentSceneCamera&&(this.activeCamera&&this.activeCamera!==e.activeCamera&&e.setTransformMatrix(this._currentSceneCamera.getViewMatrix(),this._currentSceneCamera.getProjectionMatrix(!0)),this._engine.setViewport(this._currentSceneCamera.viewport)),e.resetCachedMaterial(),this.onFinishRenderingObservable.notifyObservers(this)}render(e=0,t=!1){const s=this._engine.currentRenderPassId;this._engine.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e);if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===dt.SNAPSHOTRENDERING_FAST)this.onFastPathRenderObservable.notifyObservers(e);else{const t=this._prepareRenderingManager(e),s=this._scene.getOutlineRenderer?.(),i=s?.enabled;s&&(s.enabled=this.enableOutlineRendering),this.onBeforeRenderingManagerRenderObservable.notifyObservers(e),this._renderingManager.render(this.customRenderFunction,t,this.renderParticles,this.renderSprites,this.renderDepthOnlyMeshes,this.renderOpaqueMeshes,this.renderAlphaTestMeshes,this.renderTransparentMeshes,this.customRenderTransparentSubMeshes),this.onAfterRenderingManagerRenderObservable.notifyObservers(e),s&&(s.enabled=i)}t||this.onAfterRenderObservable.notifyObservers(e),this._engine.currentRenderPassId=s}_checkReadiness(){const e=this._scene,t=this._engine.currentRenderPassId;let s=!0;e.getViewMatrix()||e.updateTransformMatrix();const i=this.options.numPasses;for(let t=0;t<i&&s;t++){const r=this.renderList?this.renderList:e.frameGraph?e.meshes:e.getActiveMeshes().data,n=this.renderList||e.frameGraph?r.length:e.getActiveMeshes().length;this._engine.currentRenderPassId=this._renderPassIds[t],this.onBeforeRenderObservable.notifyObservers(t);let a=null,o=n;this.getCustomRenderList&&(a=this.getCustomRenderList(t,r,n),a&&(o=a.length)),a||(a=r),this.options.doNotChangeAspectRatio||e.updateTransformMatrix(!0);for(let e=0;e<o&&s;++e){const t=a[e];if(t.isEnabled()&&!t.isBlocked&&t.isVisible&&t.subMeshes)if(this.customIsReadyFunction){if(!this.customIsReadyFunction(t,this.refreshRate,!0)){s=!1;continue}}else if(!t.isReady(!0)){s=!1;continue}}this.onAfterRenderObservable.notifyObservers(t),i>1&&(e.incrementRenderId(),e.resetCachedMaterial())}const r=this.particleSystemList||e.particleSystems;for(const e of r)e.isReady()||(s=!1);return this._engine.currentRenderPassId=t,s}_prepareRenderingManager(e=0,t=!1){const s=this._scene;let i,r,n=null;const a=this.renderList?this.renderList:s.frameGraph?s.meshes:s.getActiveMeshes().data,o=this.renderList||s.frameGraph?a.length:s.getActiveMeshes().length;if(this.getCustomRenderList&&(n=this.getCustomRenderList(e,a,o)),n)i=n.length,r=this.forceLayerMaskCheck;else{if(this._defaultRenderListPrepared&&!t&&!this._engine.isWebGPU)return a;this._defaultRenderListPrepared=!0,n=a,i=o,r=!this.renderList||this.forceLayerMaskCheck}const h=s.activeCamera,l=this.cameraForLOD??h,c=s.getBoundingBoxRenderer?.();if(s._activeMeshesFrozen&&this._isFrozen){if(this._renderingManager.resetSprites(),this.enableBoundingBoxRendering&&c){c.reset();for(let e=0;e<this._activeBoundingBoxes.length;e++){const t=this._activeBoundingBoxes.data[e];c.renderList.push(t)}}return n}if(this._renderingManager.reset(),this._activeMeshes.reset(),this._activeBoundingBoxes.reset(),c&&c.reset(),this.renderMeshes){const e=s.getRenderId(),t=s.getFrameId();for(let a=0;a<i;a++){const i=n[a];if(i&&!i.isBlocked){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(i,this.refreshRate,!1)){this.resetRefreshCounter();continue}}else if(!i.isReady(0===this.refreshRate)){this.resetRefreshCounter();continue}let n,a;if(l){const e=i._internalAbstractMeshDataInfo._currentLOD.get(l);e&&e[1]===t?n=e[0]:(n=s.customLODSelector?s.customLODSelector(i,l):i.getLOD(l),e?(e[0]=n,e[1]=t):i._internalAbstractMeshDataInfo._currentLOD.set(l,[n,t]))}else n=i;if(!n)continue;if(n!==i&&0!==n.billboardMode&&n.computeWorldMatrix(),n._preActivateForIntermediateRendering(e),a=!(!r||!h)&&0===(i.layerMask&h.layerMask),i.isEnabled()&&i.isVisible&&i.subMeshes&&!a){if(this._activeMeshes.push(i),n._internalAbstractMeshDataInfo._wasActiveLastFrame=!0,n!==i&&n._activate(e,!0),this.enableBoundingBoxRendering&&c&&c._preActiveMesh(i),i._activate(e,!0)&&i.subMeshes.length){i.isAnInstance?i._internalAbstractMeshDataInfo._actAsRegularMesh&&(n=i):n._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!1,n._internalAbstractMeshDataInfo._isActiveIntermediate=!0,s._prepareSkeleton(n);for(let e=0;e<n.subMeshes.length;e++){const t=n.subMeshes[e];this.enableBoundingBoxRendering&&c&&c._evaluateSubMesh(i,t),this._renderingManager.dispatch(t,n)}}i._postActivate()}}}}if(this.enableBoundingBoxRendering&&c&&t)for(let e=0;e<c.renderList.length;e++){const t=c.renderList.data[e];this._activeBoundingBoxes.push(t)}if(this._scene.particlesEnabled&&this.renderParticles){this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);const e=this.particleSystemList||s.particleSystems;for(let t=0;t<e.length;t++){const s=e[t],i=s.emitter;s.isStarted()&&i&&(!i.position||i.isEnabled())&&this._renderingManager.dispatchParticles(s)}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}return n}get renderingManager(){return this._renderingManager}setRenderingOrder(e,t=null,s=null,i=null){this._renderingManager.setRenderingOrder(e,t,s,i)}setRenderingAutoClearDepthStencil(e,t,s=!0,i=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,s,i),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=new ml(this.name,this._scene,this.options);return this.renderList&&(e.renderList=this.renderList.slice(0)),e}dispose(){const e=this.renderList?this.renderList:this._scene.getActiveMeshes().data,t=this.renderList?this.renderList.length:this._scene.getActiveMeshes().length;for(let s=0;s<t;s++){const t=e[s];t&&void 0!==t.getMaterialForRenderPass(this.renderPassId)&&t.setMaterialForRenderPass(this.renderPassId,void 0)}if(this.onInitRenderingObservable.clear(),this.onFinishRenderingObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderingManagerRenderObservable.clear(),this.onAfterRenderingManagerRenderObservable.clear(),this.onFastPathRenderObservable.clear(),this._releaseRenderPassId(),this.renderList=null,this._sceneUBOs)for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=void 0,this._scene.removeObjectRenderer(this)}_rebuild(){this.refreshRate===ml.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=ml.REFRESHRATE_RENDER_ONCE)}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}}ml.REFRESHRATE_RENDER_ONCE=0,ml.REFRESHRATE_RENDER_ONEVERYFRAME=1,ml.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2;class Tl extends Ch{get renderListPredicate(){return this._objectRenderer.renderListPredicate}set renderListPredicate(e){this._objectRenderer.renderListPredicate=e}get renderList(){return this._objectRenderer.renderList}set renderList(e){this._objectRenderer.renderList=e}get particleSystemList(){return this._objectRenderer.particleSystemList}set particleSystemList(e){this._objectRenderer.particleSystemList=e}get getCustomRenderList(){return this._objectRenderer.getCustomRenderList}set getCustomRenderList(e){this._objectRenderer.getCustomRenderList=e}get renderParticles(){return this._objectRenderer.renderParticles}set renderParticles(e){this._objectRenderer.renderParticles=e}get renderSprites(){return this._objectRenderer.renderSprites}set renderSprites(e){this._objectRenderer.renderSprites=e}get enableBoundingBoxRendering(){return this._objectRenderer.enableBoundingBoxRendering}set enableBoundingBoxRendering(e){this._objectRenderer.enableBoundingBoxRendering=e}get enableOutlineRendering(){return this._objectRenderer.enableOutlineRendering}set enableOutlineRendering(e){this._objectRenderer.enableOutlineRendering=e}get forceLayerMaskCheck(){return this._objectRenderer.forceLayerMaskCheck}set forceLayerMaskCheck(e){this._objectRenderer.forceLayerMaskCheck=e}get activeCamera(){return this._objectRenderer.activeCamera}set activeCamera(e){this._objectRenderer.activeCamera=e}get cameraForLOD(){return this._objectRenderer.cameraForLOD}set cameraForLOD(e){this._objectRenderer.cameraForLOD=e}get disableImageProcessing(){return this._objectRenderer.disableImageProcessing}set disableImageProcessing(e){this._objectRenderer.disableImageProcessing=e}get customIsReadyFunction(){return this._objectRenderer.customIsReadyFunction}set customIsReadyFunction(e){this._objectRenderer.customIsReadyFunction=e}get customRenderFunction(){return this._objectRenderer.customRenderFunction}set customRenderFunction(e){this._objectRenderer.customRenderFunction=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}get onBeforeRenderObservable(){return this._objectRenderer.onBeforeRenderObservable}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}get onAfterRenderObservable(){return this._objectRenderer.onAfterRenderObservable}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get _waitingRenderList(){return this._objectRenderer._waitingRenderList}set _waitingRenderList(e){this._objectRenderer._waitingRenderList=e}get renderPassId(){return this._objectRenderer.renderPassId}get renderPassIds(){return this._objectRenderer.renderPassIds}get currentRefreshId(){return this._objectRenderer.currentRefreshId}setMaterialForRendering(e,t){this._objectRenderer.setMaterialForRendering(e,t)}get isMulti(){return this._renderTarget?.isMulti??!1}get renderTargetOptions(){return this._renderTargetOptions}get renderTarget(){return this._renderTarget}_onRatioRescale(){this._sizeRatio&&this.resize(this._initialSizeParameter)}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(dt.MATERIAL_TextureDirtyFlag)}get boundingBoxSize(){return this._boundingBoxSize}get depthStencilTexture(){return this._renderTarget?._depthStencilTexture??null}constructor(e,t,s,i=!1,r=!0,n=dt.TEXTURETYPE_UNSIGNED_BYTE,o=!1,h=Ch.TRILINEAR_SAMPLINGMODE,l=!0,u=!1,d=!1,_=dt.TEXTUREFORMAT_RGBA,p=!1,f,g,m=!1,T=!1){let E,R,b=!0,A=!1;if("object"==typeof i){const e=i;i=!!e.generateMipMaps,r=e.doNotChangeAspectRatio??!0,n=e.type??dt.TEXTURETYPE_UNSIGNED_BYTE,o=!!e.isCube,h=e.samplingMode??Ch.TRILINEAR_SAMPLINGMODE,l=e.generateDepthBuffer??!0,u=!!e.generateStencilBuffer,d=!!e.isMulti,_=e.format??dt.TEXTUREFORMAT_RGBA,p=!!e.delayAllocation,f=e.samples,g=e.creationFlags,m=!!e.noColorAttachment,T=!!e.useSRGBBuffer,E=e.colorAttachment,b=e.gammaSpace??b,R=e.existingObjectRenderer,A=!!e.enableClusteredLights}if(super(null,s,!i,void 0,h,void 0,void 0,void 0,void 0,_),this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new c,this.onAfterUnbindObservable=new c,this.onClearObservable=new c,this.onResizeObservable=new c,this._cleared=!1,this.skipInitialClear=!1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this._dontDisposeObjectRenderer=!1,this.boundingBoxPosition=xe.Zero(),this._disableEngineStages=!1,this._dumpToolsLoading=!1,!(s=this.getScene()))return;const y=this.getScene().getEngine();this._gammaSpace=b,this._coordinatesMode=Ch.PROJECTION_MODE,this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._dontDisposeObjectRenderer=!!R,this._processSizeParameter(t),this._objectRenderer=R??new ml(e,s,{numPasses:o?6:this.getRenderLayers()||1,doNotChangeAspectRatio:r,enableClusteredLights:A}),this._onBeforeRenderingManagerRenderObserver=this._objectRenderer.onBeforeRenderingManagerRenderObservable.add(()=>{const e=this._scene;if(!this._disableEngineStages)for(const t of e._beforeRenderTargetClearStage)t.action(this,this._currentFaceIndex,this._currentLayer);if(this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(y):this.skipInitialClear||y.clear(this.clearColor??e.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||e.updateTransformMatrix(!0),!this._disableEngineStages)for(const t of e._beforeRenderTargetDrawStage)t.action(this,this._currentFaceIndex,this._currentLayer);y._debugPushGroup&&y._debugPushGroup(`Render to ${this.name} (face #${this._currentFaceIndex} layer #${this._currentLayer})`)}),this._onAfterRenderingManagerRenderObserver=this._objectRenderer.onAfterRenderingManagerRenderObservable.add(()=>{if(y._debugPopGroup&&y._debugPopGroup(),!this._disableEngineStages)for(const e of this._scene._afterRenderTargetDrawStage)e.action(this,this._currentFaceIndex,this._currentLayer);const e=this._texture?.generateMipMaps??!1;if(this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,this._currentFaceIndex,this._postProcesses,this.ignoreCameraViewport):this._currentUseCameraPostProcess&&this._scene.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,this._currentFaceIndex),!this._disableEngineStages)for(const e of this._scene._afterRenderTargetPostProcessStage)e.action(this,this._currentFaceIndex,this._currentLayer);this._texture&&(this._texture.generateMipMaps=e),this._doNotChangeAspectRatio||this._scene.updateTransformMatrix(!0),this._currentDumpForDebug&&(this._dumpTools?this._dumpTools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),y):a.Error("dumpTools module is still being loaded. To speed up the process import dump tools directly in your project"))}),this._onFastPathRenderObserver=this._objectRenderer.onFastPathRenderObservable.add(()=>{this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(y):this.skipInitialClear||y.clear(this.clearColor||this._scene.clearColor,!0,!0,!0)}),this._resizeObserver=y.onResizeObservable.add(()=>{}),this._generateMipMaps=!!i,this._doNotChangeAspectRatio=r,d||(this._renderTargetOptions={generateMipMaps:i,type:n,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:u,samples:f,creationFlags:g,noColorAttachment:m,useSRGBBuffer:T,colorAttachment:E,label:this.name},this.samplingMode===Ch.NEAREST_SAMPLINGMODE&&(this.wrapU=Ch.CLAMP_ADDRESSMODE,this.wrapV=Ch.CLAMP_ADDRESSMODE),p||(o?(this._renderTarget=s.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=Ch.INVCUBIC_MODE,this._textureMatrix=Ie.Identity()):this._renderTarget=s.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==f&&(this.samples=f)))}createDepthStencilTexture(e=0,t=!0,s=!1,i=1,r=dt.TEXTUREFORMAT_DEPTH32_FLOAT,n){this._renderTarget?.createDepthStencilTexture(e,t,s,i,r,n)}_processSizeParameter(e){if(e.ratio){this._sizeRatio=e.ratio;const t=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(t.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(t.getRenderHeight(),this._sizeRatio)}}else this._size=e}get samples(){return this._renderTarget?.samples??this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}addPostProcess(e){if(!this._postProcessManager){const e=this.getScene();if(!e)return;this._postProcessManager=new Mo(e),this._postProcesses=new Array}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1}clearPostProcesses(e=!1){if(this._postProcesses){if(e)for(const e of this._postProcesses)e.dispose();this._postProcesses=[]}}removePostProcess(e){if(!this._postProcesses)return;const t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}resetRefreshCounter(){this._objectRenderer.resetRefreshCounter()}get refreshRate(){return this._objectRenderer.refreshRate}set refreshRate(e){this._objectRenderer.refreshRate=e}_shouldRender(){return this._objectRenderer.shouldRender()}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;if(e)return e;const t=this._size.depth;return t||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){const t=this.isCube;this._renderTarget?.dispose(),this._renderTarget=null;const s=this.getScene();s&&(this._processSizeParameter(e),this._renderTarget=t?s.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):s.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==this._renderTargetOptions.samples&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){this._dumpToolsLoading||(this._dumpToolsLoading=!0,import("./dumpTools-DGzCZDqL.esm.min.js").then(e=>this._dumpTools=e)),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight());const e=this._objectRenderer._checkReadiness();return this.onAfterUnbindObservable.notifyObservers(this),this._objectRenderer.finishRender(),e}_render(e=!1,t=!1){const s=this.getScene();if(!s)return;void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses);const i=s.getEngine();if(i._debugPushGroup&&i._debugPushGroup(`Render to ${this.name}`),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight()),!this.is2DArray&&!this.is3D||this.isMulti)if(this.isCube&&!this.isMulti)for(let i=0;i<6;i++)this._renderToTarget(i,e,t),s.incrementRenderId(),s.resetCachedMaterial();else this._renderToTarget(0,e,t);else for(let i=0;i<this.getRenderLayers();i++)this._renderToTarget(0,e,t,i),s.incrementRenderId(),s.resetCachedMaterial();this.onAfterUnbindObservable.notifyObservers(this),this._objectRenderer.finishRender(),i._debugPopGroup&&i._debugPopGroup()}_bestReflectionRenderTargetDimension(e,t){const s=e*t,i=Cs(s+16384/(128+s));return Math.min(Ds(e),i)}_bindFrameBuffer(e=0,t=0){const s=this.getScene();if(!s)return;const i=s.getEngine();this._renderTarget&&i.bindFramebuffer(this._renderTarget,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,t)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindFramebuffer(this._renderTarget,this.isCube,()=>{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,s,i){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses)||this._bindFrameBuffer(t,s):i&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,s)}_renderToTarget(e,t,s,i=0){const r=this.getScene();if(!r)return;const n=r.getEngine();this._currentFaceIndex=e,this._currentLayer=i,this._currentUseCameraPostProcess=t,this._currentDumpForDebug=s,this._prepareFrame(r,e,i,t),this._objectRenderer.render(e+i,!0),this._unbindFrameBuffer(n,e),this._texture&&this.isCube&&5===e&&n.generateMipMapsForCubemap(this._texture,!0)}setRenderingOrder(e,t=null,s=null,i=null){this._objectRenderer.setRenderingOrder(e,t,s,i)}setRenderingAutoClearDepthStencil(e,t){this._objectRenderer.setRenderingAutoClearDepthStencil(e,t)}clone(){const e=this.getSize(),t=new Tl(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t<this.renderList.length;t++)e.renderList.push(this.renderList[t].id);return e}disposeFramebufferObjects(){this._renderTarget?.dispose(!0)}releaseInternalTexture(){this._renderTarget?.releaseTextures(),this._texture=null}dispose(){this.onResizeObservable.clear(),this.onClearObservable.clear(),this.onAfterUnbindObservable.clear(),this.onBeforeBindObservable.clear(),this._postProcessManager&&(this._postProcessManager.dispose(),this._postProcessManager=null),this._prePassRenderTarget&&this._prePassRenderTarget.dispose(),this._objectRenderer.onBeforeRenderingManagerRenderObservable.remove(this._onBeforeRenderingManagerRenderObserver),this._objectRenderer.onAfterRenderingManagerRenderObservable.remove(this._onAfterRenderingManagerRenderObserver),this._objectRenderer.onFastPathRenderObservable.remove(this._onFastPathRenderObserver),this._dontDisposeObjectRenderer||this._objectRenderer.dispose(),this.clearPostProcesses(!0),this._resizeObserver&&(this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null);const e=this.getScene();if(!e)return;let t=e.customRenderTargets.indexOf(this);t>=0&&e.customRenderTargets.splice(t,1);for(const s of e.cameras)t=s.customRenderTargets.indexOf(this),t>=0&&s.customRenderTargets.splice(t,1);this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this._objectRenderer._rebuild(),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._objectRenderer.freeRenderingGroups()}getViewCount(){return 1}}Tl.REFRESHRATE_RENDER_ONCE=ml.REFRESHRATE_RENDER_ONCE,Tl.REFRESHRATE_RENDER_ONEVERYFRAME=ml.REFRESHRATE_RENDER_ONEVERYFRAME,Tl.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=ml.REFRESHRATE_RENDER_ONEVERYTWOFRAMES;let El=!1;function Rl(){El||(El=!0,gl(),li.prototype.setDepthStencilTexture=function(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)},Ch._CreateRenderTargetTexture=(e,t,s,i,r)=>new Tl(e,t,s,i))}Object.getOwnPropertyDescriptor(Tl.prototype,"noPrePassRenderer")||Object.defineProperty(Tl.prototype,"noPrePassRenderer",Ue(0,"noPrePassRenderer"));let bl=!1;function Al(){bl||(bl=!0,Ni.prototype.restoreSingleAttachment=function(){const e=this._gl;this.bindAttachments([e.BACK])},Ni.prototype.restoreSingleAttachmentForRenderTarget=function(){const e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},Ni.prototype.buildTextureLayout=function(e,t=!1){const s=this._gl,i=[];if(t)i.push(s.BACK);else for(let t=0;t<e.length;t++)e[t]?i.push(s["COLOR_ATTACHMENT"+t]):i.push(s.NONE);return i},Ni.prototype.bindAttachments=function(e){this._gl.drawBuffers(e)},Ni.prototype.unBindMultiColorAttachmentFramebuffer=function(e,t=!1,s){this._currentRenderTarget=null,e.disableAutomaticMSAAResolve||this.resolveMultiFramebuffer(e),t||this.generateMipMapsMultiFramebuffer(e),s&&(e._MSAAFramebuffer&&this._bindUnboundFramebuffer(e._framebuffer),s()),this._bindUnboundFramebuffer(null)},Ni.prototype.createMultipleRenderTarget=function(e,t,s=!0){let i,r=!1,n=!0,o=!1,h=!1,l=1,c=1;const u=dt.TEXTURETYPE_UNSIGNED_BYTE,d=dt.TEXTURE_TRILINEAR_SAMPLINGMODE,_=dt.TEXTUREFORMAT_RGBA,p=dt.TEXTURE_2D;let f=[],g=[],m=[],T=[],E=[],R=[],b=[],A=[],y=[],M=!1;const x=this._createHardwareRenderTargetWrapper(!0,!1,e);void 0!==t&&(r=void 0!==t.generateMipMaps&&t.generateMipMaps,n=void 0===t.generateDepthBuffer||t.generateDepthBuffer,o=void 0!==t.generateStencilBuffer&&t.generateStencilBuffer,h=void 0!==t.generateDepthTexture&&t.generateDepthTexture,l=t.textureCount??1,c=t.samples??c,f=t.types||f,g=t.samplingModes||g,m=t.useSRGBBuffers||m,T=t.formats||T,E=t.targetTypes||E,R=t.faceIndex||R,b=t.layerIndex||b,A=t.layerCounts||A,y=t.labels||y,M=t.dontCreateTextures??!1,this.webGLVersion>1&&(t.depthTextureFormat===dt.TEXTUREFORMAT_DEPTH24_STENCIL8||t.depthTextureFormat===dt.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||t.depthTextureFormat===dt.TEXTUREFORMAT_DEPTH24||t.depthTextureFormat===dt.TEXTUREFORMAT_DEPTH32_FLOAT||t.depthTextureFormat===dt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8)&&(i=t.depthTextureFormat)),void 0===i&&(i=o?dt.TEXTUREFORMAT_DEPTH24_STENCIL8:dt.TEXTUREFORMAT_DEPTH32_FLOAT);const S=this._gl,v=this._currentFramebuffer,I=S.createFramebuffer();this._bindUnboundFramebuffer(I);const P=e.width??e,C=e.height??e,O=[],D=[],w=this.webGLVersion>1&&(i===dt.TEXTUREFORMAT_DEPTH24_STENCIL8||i===dt.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||i===dt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8);x.label=t?.label??"MultiRenderTargetWrapper",x._framebuffer=I,x._generateDepthBuffer=h||n,x._generateStencilBuffer=h?w:o,x._depthStencilBuffer=this._setupFramebufferDepthAttachments(x._generateStencilBuffer,x._generateDepthBuffer,P,C,1,i),x._attachments=D;for(let e=0;e<l;e++){let t=g[e]||d,s=f[e]||u,i=m[e]||false;const n=T[e]||_,o=E[e]||p,h=A[e]??1;(s!==dt.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(s!==dt.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(t=dt.TEXTURE_NEAREST_SAMPLINGMODE);const l=this._getSamplingParameters(t,r);s!==dt.TEXTURETYPE_FLOAT||this._caps.textureFloat||(s=dt.TEXTURETYPE_UNSIGNED_BYTE,a.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),i=i&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU);const c=this.webGLVersion>1,R=S[c?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(D.push(R),-1===o||M)continue;const b=new gi(this,6);O[e]=b,S.activeTexture(S["TEXTURE"+e]),S.bindTexture(o,b._hardwareTexture.underlyingResource),S.texParameteri(o,S.TEXTURE_MAG_FILTER,l.mag),S.texParameteri(o,S.TEXTURE_MIN_FILTER,l.min),S.texParameteri(o,S.TEXTURE_WRAP_S,S.CLAMP_TO_EDGE),S.texParameteri(o,S.TEXTURE_WRAP_T,S.CLAMP_TO_EDGE);const v=this._getRGBABufferInternalSizedFormat(s,n,i),I=this._getInternalFormat(n),w=this._getWebGLTextureType(s);if(!c||o!==dt.TEXTURE_2D_ARRAY&&o!==dt.TEXTURE_3D)if(o===dt.TEXTURE_CUBE_MAP){for(let e=0;e<6;e++)S.texImage2D(S.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,v,P,C,0,I,w,null);b.isCube=!0}else S.texImage2D(S.TEXTURE_2D,0,v,P,C,0,I,w,null);else o===dt.TEXTURE_2D_ARRAY?b.is2DArray=!0:b.is3D=!0,b.baseDepth=b.depth=h,S.texImage3D(o,0,v,P,C,h,0,I,w,null);r&&S.generateMipmap(o),this._bindTextureDirectly(o,null),b.baseWidth=P,b.baseHeight=C,b.width=P,b.height=C,b.isReady=!0,b.samples=1,b.generateMipMaps=r,b.samplingMode=t,b.type=s,b._useSRGBBuffer=i,b.format=n,b.label=y[e]??x.label+"-Texture"+e,this._internalTexturesCache.push(b)}if(h&&this._caps.depthTextureExtension&&!M){const e=new gi(this,14);let t=dt.TEXTURETYPE_UNSIGNED_SHORT,s=S.DEPTH_COMPONENT16,n=S.DEPTH_COMPONENT,a=S.UNSIGNED_SHORT,o=S.DEPTH_ATTACHMENT;this.webGLVersion<2?s=S.DEPTH_COMPONENT:i===dt.TEXTUREFORMAT_DEPTH32_FLOAT?(t=dt.TEXTURETYPE_FLOAT,a=S.FLOAT,s=S.DEPTH_COMPONENT32F):i===dt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8?(t=dt.TEXTURETYPE_UNSIGNED_BYTE,a=S.FLOAT_32_UNSIGNED_INT_24_8_REV,s=S.DEPTH32F_STENCIL8,n=S.DEPTH_STENCIL,o=S.DEPTH_STENCIL_ATTACHMENT):i===dt.TEXTUREFORMAT_DEPTH24?(t=dt.TEXTURETYPE_UNSIGNED_BYTE,a=S.UNSIGNED_INT,s=S.DEPTH_COMPONENT24,o=S.DEPTH_ATTACHMENT):i!==dt.TEXTUREFORMAT_DEPTH24_STENCIL8&&i!==dt.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||(t=dt.TEXTURETYPE_UNSIGNED_INT_24_8,a=S.UNSIGNED_INT_24_8,s=S.DEPTH24_STENCIL8,n=S.DEPTH_STENCIL,o=S.DEPTH_STENCIL_ATTACHMENT),this._bindTextureDirectly(S.TEXTURE_2D,e,!0),S.texParameteri(S.TEXTURE_2D,S.TEXTURE_MAG_FILTER,S.NEAREST),S.texParameteri(S.TEXTURE_2D,S.TEXTURE_MIN_FILTER,S.NEAREST),S.texParameteri(S.TEXTURE_2D,S.TEXTURE_WRAP_S,S.CLAMP_TO_EDGE),S.texParameteri(S.TEXTURE_2D,S.TEXTURE_WRAP_T,S.CLAMP_TO_EDGE),S.texImage2D(S.TEXTURE_2D,0,s,P,C,0,n,a,null),S.framebufferTexture2D(S.FRAMEBUFFER,o,S.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),this._bindTextureDirectly(S.TEXTURE_2D,null),x._depthStencilTexture=e,x._depthStencilTextureWithStencil=w,e.baseWidth=P,e.baseHeight=C,e.width=P,e.height=C,e.isReady=!0,e.samples=1,e.generateMipMaps=r,e.samplingMode=dt.TEXTURE_NEAREST_SAMPLINGMODE,e.format=i,e.type=t,e.label=x.label+"-DepthStencil",O[l]=e,this._internalTexturesCache.push(e)}if(x.setTextures(O),s&&S.drawBuffers(D),this._bindUnboundFramebuffer(v),x.setLayerAndFaceIndices(b,R),this.resetTextureCache(),M){if(c>1){const e=S.createFramebuffer();if(!e)throw new Error("Unable to create multi sampled framebuffer");x._samples=c,x._MSAAFramebuffer=e,l>0&&s&&(this._bindUnboundFramebuffer(e),S.drawBuffers(D),this._bindUnboundFramebuffer(v))}}else this.updateMultipleRenderTargetTextureSampleCount(x,c,s);return x},Ni.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,s=!0){if(this.webGLVersion<2||!e)return 1;if(e.samples===t)return t;const i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const r=e._attachments.length;for(let t=0;t<r;t++){const s=e.textures[t]._hardwareTexture;s?.releaseMSAARenderBuffers()}if(t>1&&"function"==typeof i.renderbufferStorageMultisample){const n=i.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);const a=[];for(let s=0;s<r;s++){const r=e.textures[s],n=r._hardwareTexture,o=i[this.webGLVersion>1?"COLOR_ATTACHMENT"+s:"COLOR_ATTACHMENT"+s+"_WEBGL"],h=this._createRenderBuffer(r.width,r.height,t,-1,this._getRGBABufferInternalSizedFormat(r.type,r.format,r._useSRGBBuffer),o);if(!h)throw new Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(h),r.samples=t,a.push(o)}s&&i.drawBuffers(a)}else this._bindUnboundFramebuffer(e._framebuffer);const n=e._depthStencilTexture?e._depthStencilTexture.format:void 0;return e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.width,e.height,t,n),this._bindUnboundFramebuffer(null),e._samples=t,t},Ni.prototype.generateMipMapsMultiFramebuffer=function(e){const t=e,s=this._gl;if(t.isMulti)for(let e=0;e<t._attachments.length;e++){const i=t.textures[e];!i?.generateMipMaps||i?.isCube||i?.is3D||(this._bindTextureDirectly(s.TEXTURE_2D,i,!0),s.generateMipmap(s.TEXTURE_2D),this._bindTextureDirectly(s.TEXTURE_2D,null))}},Ni.prototype.resolveMultiFramebuffer=function(e){const t=e,s=this._gl;if(!t._MSAAFramebuffer||!t.isMulti)return;let i=t.resolveMSAAColors?s.COLOR_BUFFER_BIT:0;i|=t._generateDepthBuffer&&t.resolveMSAADepth?s.DEPTH_BUFFER_BIT:0,i|=t._generateStencilBuffer&&t.resolveMSAAStencil?s.STENCIL_BUFFER_BIT:0;const r=t._attachments,n=r.length;s.bindFramebuffer(s.READ_FRAMEBUFFER,t._MSAAFramebuffer),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,t._framebuffer);for(let e=0;e<n;e++){const a=t.textures[e];for(let e=0;e<n;e++)r[e]=s.NONE;r[e]=s[this.webGLVersion>1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"],s.readBuffer(r[e]),s.drawBuffers(r),s.blitFramebuffer(0,0,a.width,a.height,0,0,a.width,a.height,i,s.NEAREST)}for(let e=0;e<n;e++)r[e]=s[this.webGLVersion>1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];s.drawBuffers(r),s.bindFramebuffer(this._gl.FRAMEBUFFER,t._MSAAFramebuffer)})}class yl extends Tl{get isSupported(){return this._engine?.getCaps().drawBuffersExtension??!1}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t<this._textures.length;t++)this._textures[t].wrapU=e}set wrapV(e){if(this._textures)for(let t=0;t<this._textures.length;t++)this._textures[t].wrapV=e}constructor(e,t,s,i,r,n){const a=!(!r||!r.generateMipMaps)&&r.generateMipMaps,o=!(!r||!r.generateDepthTexture)&&r.generateDepthTexture,h=r&&r.depthTextureFormat?r.depthTextureFormat:dt.TEXTUREFORMAT_DEPTH16,l=!r||void 0===r.doNotChangeAspectRatio||r.doNotChangeAspectRatio,c=!(!r||!r.drawOnlyOnFirstAttachmentByDefault)&&r.drawOnlyOnFirstAttachmentByDefault;if(super(e,t,i,a,l,void 0,void 0,void 0,void 0,void 0,void 0,void 0,!0),Al(),!this.isSupported)return void this.dispose();this._textureNames=n;const u=[],d=[],_=[],p=[],f=[],g=[],m=[],T=[];this._initTypes(s,u,d,_,p,f,g,m,T,r);const E=!r||void 0===r.generateDepthBuffer||r.generateDepthBuffer,R=!(!r||void 0===r.generateStencilBuffer)&&r.generateStencilBuffer,b=r&&r.samples?r.samples:1;this._multiRenderTargetOptions={samplingModes:d,generateMipMaps:a,generateDepthBuffer:E,generateStencilBuffer:R,generateDepthTexture:o,depthTextureFormat:h,types:u,textureCount:s,useSRGBBuffers:_,samples:b,formats:p,targetTypes:f,faceIndex:g,layerIndex:m,layerCounts:T,labels:n,label:e},this._count=s,this._drawOnlyOnFirstAttachmentByDefault=c,s>0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,s,i,r,n,a,o,h,l){for(let c=0;c<e;c++)l&&l.types&&void 0!==l.types[c]?t.push(l.types[c]):t.push(l&&l.defaultType?l.defaultType:dt.TEXTURETYPE_UNSIGNED_BYTE),l&&l.samplingModes&&void 0!==l.samplingModes[c]?s.push(l.samplingModes[c]):s.push(Ch.BILINEAR_SAMPLINGMODE),l&&l.useSRGBBuffers&&void 0!==l.useSRGBBuffers[c]?i.push(l.useSRGBBuffers[c]):i.push(!1),l&&l.formats&&void 0!==l.formats[c]?r.push(l.formats[c]):r.push(dt.TEXTUREFORMAT_RGBA),l&&l.targetTypes&&void 0!==l.targetTypes[c]?n.push(l.targetTypes[c]):n.push(dt.TEXTURE_2D),l&&l.faceIndex&&void 0!==l.faceIndex[c]?a.push(l.faceIndex[c]):a.push(0),l&&l.layerIndex&&void 0!==l.layerIndex[c]?o.push(l.layerIndex[c]):o.push(0),l&&l.layerCounts&&void 0!==l.layerCounts[c]?h.push(l.layerCounts[c]):h.push(1)}_createInternaTextureIndexMapping(){const e={},t=[];if(!this._renderTarget)return t;const s=this._renderTarget.textures;for(let i=0;i<s.length;i++){const r=s[i];if(!r)continue;const n=e[r.uniqueId];void 0!==n?t[i]=n:e[r.uniqueId]=i}return t}_rebuild(e=!1,t=!1,s){if(this._count<1||e)return;const i=this._createInternaTextureIndexMapping();this.releaseInternalTextures(),this._createInternalTextures(),t&&(this._releaseTextures(),this._createTextures(s));const r=this._renderTarget.textures;for(let e=0;e<r.length;e++){const t=this._textures[e];void 0!==i[e]&&this._renderTarget.setTexture(r[i[e]],e),t._texture=r[e],t._texture&&(t._noMipmap=!t._texture.useMipMaps,t._useSRGBBuffer=t._texture._useSRGBBuffer)}1!==this.samples&&this._renderTarget.setSamples(this.samples,!this._drawOnlyOnFirstAttachmentByDefault,!0)}_createInternalTextures(){this._renderTarget=this._getEngine().createMultipleRenderTarget(this._size,this._multiRenderTargetOptions,!this._drawOnlyOnFirstAttachmentByDefault),this._texture=this._renderTarget.texture}_releaseTextures(){if(this._textures)for(let e=0;e<this._textures.length;e++)this._textures[e]._texture=null,this._textures[e].dispose()}_createTextures(e){const t=this._renderTarget.textures;this._textures=[];for(let s=0;s<t.length;s++){const i=new Ch(null,this.getScene());e?.[s]&&(i.name=e[s]),i._texture=t[s],i._texture&&(i._noMipmap=!i._texture.useMipMaps,i._useSRGBBuffer=i._texture._useSRGBBuffer),this._textures.push(i)}}setInternalTexture(e,t,s=!0){if(this.renderTarget&&(0===t&&(this._texture=e),this.renderTarget.setTexture(e,t,s),this.textures[t]||(this.textures[t]=new Ch(null,this.getScene()),this.textures[t].name=this._textureNames?.[t]??this.textures[t].name),this.textures[t]._texture=e,this.textures[t]._noMipmap=!e.useMipMaps,this.textures[t]._useSRGBBuffer=e._useSRGBBuffer,this._count=this.renderTarget.textures?this.renderTarget.textures.length:0,this._multiRenderTargetOptions.types&&(this._multiRenderTargetOptions.types[t]=e.type),this._multiRenderTargetOptions.samplingModes&&(this._multiRenderTargetOptions.samplingModes[t]=e.samplingMode),this._multiRenderTargetOptions.useSRGBBuffers&&(this._multiRenderTargetOptions.useSRGBBuffers[t]=e._useSRGBBuffer),this._multiRenderTargetOptions.targetTypes&&-1!==this._multiRenderTargetOptions.targetTypes[t])){let s;s=e.is2DArray?dt.TEXTURE_2D_ARRAY:e.isCube?dt.TEXTURE_CUBE_MAP:e.is3D?dt.TEXTURE_3D:dt.TEXTURE_2D,this._multiRenderTargetOptions.targetTypes[t]=s}}setLayerAndFaceIndex(e,t=-1,s=-1){this.textures[e]&&this.renderTarget&&(this._multiRenderTargetOptions.layerIndex&&(this._multiRenderTargetOptions.layerIndex[e]=t),this._multiRenderTargetOptions.faceIndex&&(this._multiRenderTargetOptions.faceIndex[e]=s),this.renderTarget.setLayerAndFaceIndex(e,t,s))}setLayerAndFaceIndices(e,t){this.renderTarget&&(this._multiRenderTargetOptions.layerIndex=e,this._multiRenderTargetOptions.faceIndex=t,this.renderTarget.setLayerAndFaceIndices(e,t))}get samples(){return this._samples}set samples(e){this._renderTarget?this._samples=this._renderTarget.setSamples(e):this._samples=e}resize(e){this._processSizeParameter(e),this._rebuild(!1,void 0,this._textureNames)}updateCount(e,t,s){this._multiRenderTargetOptions.textureCount=e,this._count=e;const i=[],r=[],n=[],a=[],o=[],h=[],l=[],c=[];this._textureNames=s,this._initTypes(e,i,r,n,a,o,h,l,c,t),this._multiRenderTargetOptions.types=i,this._multiRenderTargetOptions.samplingModes=r,this._multiRenderTargetOptions.useSRGBBuffers=n,this._multiRenderTargetOptions.formats=a,this._multiRenderTargetOptions.targetTypes=o,this._multiRenderTargetOptions.faceIndex=h,this._multiRenderTargetOptions.layerIndex=l,this._multiRenderTargetOptions.layerCounts=c,this._multiRenderTargetOptions.labels=s,this._rebuild(!1,!0,s)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindMultiColorAttachmentFramebuffer(this._renderTarget,this.isCube,()=>{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){const e=this._renderTarget?.textures;if(e){for(let t=e.length-1;t>=0;t--)this._textures[t]._texture=null;this._renderTarget?.dispose(),this._renderTarget=null}}}const Ml={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class xl{constructor(e,t=Ml){this._fullscreenViewport=new Ks(0,0,1,1);const s=t.positions??Ml.positions,i=t.indices??Ml.indices;this.engine=e,this._vertexBuffers={[Gi.PositionKind]:new Gi(e,s,Gi.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(i),this._indexBufferLength=i.length,this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(i);for(const e in this._vertexBuffers){this._vertexBuffers[e]._rebuild()}})}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e,t=!1,s=!1){this.engine.setState(!0),this.engine.depthCullingState.depthTest=t,this.engine.stencilState.stencilTest=s,this.engine.enableEffect(e.drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(dt.MATERIAL_TriangleFillMode,0,this._indexBufferLength)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const s=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;s&&this.engine.bindFramebuffer(s),this.applyEffectWrapper(e),this.draw(),s&&this.engine.unBindFramebuffer(s),this.restoreStates()}dispose(){const e=this._vertexBuffers[Gi.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[Gi.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class Sl{static RegisterShaderCodeProcessing(e,t){t?Sl._CustomShaderCodeProcessing[e??""]=t:delete Sl._CustomShaderCodeProcessing[e??""]}static _GetShaderCodeProcessing(e){return Sl._CustomShaderCodeProcessing[e]??Sl._CustomShaderCodeProcessing[""]}get name(){return this.options.name}set name(e){this.options.name=e}isReady(){return this._drawWrapper.effect?.isReady()??!1}get drawWrapper(){return this._drawWrapper}get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){this.alphaMode=dt.ALPHA_DISABLE,this.onEffectCreatedObservable=new c(void 0,!0),this.onApplyObservable=new c,this._shadersLoaded=!1,this._webGPUReady=!1,this._importPromises=[],this.options={...e,name:e.name||"effectWrapper",engine:e.engine,uniforms:e.uniforms||e.uniformNames||[],uniformNames:void 0,samplers:e.samplers||e.samplerNames||[],samplerNames:void 0,attributeNames:e.attributeNames||["position"],uniformBuffers:e.uniformBuffers||[],defines:e.defines||"",useShaderStore:e.useShaderStore||!1,vertexUrl:e.vertexUrl||e.vertexShader||"postprocess",vertexShader:void 0,fragmentShader:e.fragmentShader||"pass",indexParameters:e.indexParameters,blockCompilation:e.blockCompilation||!1,shaderLanguage:e.shaderLanguage||0,onCompiled:e.onCompiled||void 0,extraInitializations:e.extraInitializations||void 0,extraInitializationsAsync:e.extraInitializationsAsync||void 0,useAsPostProcess:e.useAsPostProcess??!1,allowEmptySourceTexture:e.allowEmptySourceTexture??!1},this.options.uniformNames=this.options.uniforms,this.options.samplerNames=this.options.samplers,this.options.vertexShader=this.options.vertexUrl,this.options.useAsPostProcess&&(this.options.allowEmptySourceTexture||-1!==this.options.samplers.indexOf("textureSampler")||this.options.samplers.push("textureSampler"),-1===this.options.uniforms.indexOf("scale")&&this.options.uniforms.push("scale")),e.vertexUrl||e.vertexShader?this._shaderPath={vertexSource:this.options.vertexShader}:(this.options.useAsPostProcess||(this.options.uniforms.push("scale"),this.onApplyObservable.add(()=>{this.effect.setFloat2("scale",1,1)})),this._shaderPath={vertex:this.options.vertexShader}),this._shaderPath.fragmentSource=this.options.fragmentShader,this._shaderPath.spectorName=this.options.name,this.options.useShaderStore&&(this._shaderPath.fragment=this._shaderPath.fragmentSource,this._shaderPath.vertex||(this._shaderPath.vertex=this._shaderPath.vertexSource),delete this._shaderPath.fragmentSource,delete this._shaderPath.vertexSource),this.onApplyObservable.add(()=>{this.bind()}),this.options.useShaderStore||(this._onContextRestoredObserver=this.options.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})),this._drawWrapper=new rr(this.options.engine),this._webGPUReady=1===this.options.shaderLanguage;const t=Array.isArray(this.options.defines)?this.options.defines.join("\n"):this.options.defines;this._postConstructor(this.options.blockCompilation,t,this.options.extraInitializations)}_gatherImports(e=!1,t){}_postConstructor(e,t=null,s,i){this._importPromises.length=0,i&&this._importPromises.push(...i);const r=this.options.engine.isWebGPU&&!Sl.ForceGLSL;this._gatherImports(r,this._importPromises),this.options.useShaderStore&&"postprocess"===this._shaderPath.vertex&&this._importPromises.push(r&&this._webGPUReady?import("./postprocess.vertex-BraBtVHc.esm.min.js"):import("./postprocess.vertex-cg5rO15y.esm.min.js")),void 0!==s&&s(r,this._importPromises),r&&this._webGPUReady&&(this.options.shaderLanguage=1),e||this.updateEffect(t)}updateEffect(e=null,t=null,s=null,i,r,n,a,o){const h=Sl._GetShaderCodeProcessing(this.name);if(h?.defineCustomBindings){const i=t?.slice()??[];i.push(...this.options.uniforms);const r=s?.slice()??[];r.push(...this.options.samplers),e=h.defineCustomBindings(this.name,e,i,r),t=i,s=r}this.options.defines=e||"";const l=this._shadersLoaded||0===this._importPromises.length?void 0:async()=>{await Promise.all(this._importPromises),this._shadersLoaded=!0};let c;c=this.options.extraInitializationsAsync?async()=>{await(l?.()),await this.options.extraInitializationsAsync()}:l,this.options.useShaderStore?this._drawWrapper.effect=this.options.engine.createEffect({vertex:a??this._shaderPath.vertex,fragment:o??this._shaderPath.fragment},{attributes:this.options.attributeNames,uniformsNames:t||this.options.uniforms,uniformBuffersNames:this.options.uniformBuffers,samplers:s||this.options.samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:r??this.options.onCompiled,onError:n??null,indexParameters:i||this.options.indexParameters,processCodeAfterIncludes:h?.processCodeAfterIncludes?(e,t)=>h.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:h?.processFinalCode?(e,t)=>h.processFinalCode(this.name,e,t):null,shaderLanguage:this.options.shaderLanguage,extraInitializationsAsync:c},this.options.engine):this._drawWrapper.effect=new li(this._shaderPath,this.options.attributeNames,t||this.options.uniforms,s||this.options.samplerNames,this.options.engine,e,void 0,r||this.options.onCompiled,void 0,void 0,void 0,this.options.shaderLanguage,c),this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect)}bind(e=!1){this.options.useAsPostProcess&&!e&&(this.options.engine.setAlphaMode(this.alphaMode),this.drawWrapper.effect.setFloat2("scale",1,1)),Sl._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect)}dispose(e=!1){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.onEffectCreatedObservable.clear(),this._drawWrapper.dispose(!0)}}Sl.ForceGLSL=!1,Sl._CustomShaderCodeProcessing={};let vl=(()=>{var e;let t,s,i,r,n,a,o,h,l,u,d,_,p,f,g,m,T=[],E=[],R=[],y=[],M=[],x=[],S=[],v=[],I=[],P=[],C=[],O=[],D=[],w=[],F=[],N=[],B=[],U=[],k=[],G=[],H=[],z=[],W=[],X=[],K=[],Y=[],j=[],q=[],$=[];return e=class{static get ForceGLSL(){return Sl.ForceGLSL}static set ForceGLSL(e){Sl.ForceGLSL=e}static RegisterShaderCodeProcessing(e,t){Sl.RegisterShaderCodeProcessing(e,t)}get name(){return this._effectWrapper.name}set name(e){this._effectWrapper.name=e}get alphaMode(){return this._effectWrapper.alphaMode}set alphaMode(e){this._effectWrapper.alphaMode=e}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach(e=>{e.setSamples(this._samples)})}get shaderLanguage(){return this._shaderLanguage}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(t,s,i,r,n,a,o=dt.TEXTURE_NEAREST_SAMPLINGMODE,h,l,u=null,d=dt.TEXTURETYPE_UNSIGNED_BYTE,_="postprocess",p,f=!1,g=dt.TEXTUREFORMAT_RGBA,m,b){this._parentContainer=(A(this,T),null),this.uniqueId=A(this,E,void 0),this.width=(A(this,R),A(this,y,-1)),this.height=(A(this,M),A(this,x,-1)),this.nodeMaterialSource=(A(this,S),null),this._outputTexture=null,this.renderTargetSamplingMode=A(this,v,void 0),this.clearColor=(A(this,I),A(this,P,void 0)),this.autoClear=(A(this,C),A(this,O,!0)),this.forceAutoClearInAlphaMode=(A(this,D),A(this,w,!1)),this.alphaConstants=(A(this,F),A(this,N,void 0)),this.animations=(A(this,B),[]),this.enablePixelPerfectMode=A(this,U,!1),this.forceFullscreenViewport=(A(this,k),A(this,G,!0)),this.inspectableCustomProperties=A(this,H),this.scaleMode=A(this,z,dt.SCALEMODE_FLOOR),this.alwaysForcePOT=(A(this,W),A(this,X,!1)),this._samples=(A(this,K),A(this,Y,1)),this.adaptScaleToCurrentViewport=(A(this,j),A(this,q,!1)),this.doNotSerialize=(A(this,$),!1),this._webGPUReady=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Ws(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new Me(1,1),this._texelSize=Me.Zero(),this.onActivateObservable=new c,this.onSizeChangedObservable=new c,this.onApplyObservable=new c,this.onBeforeRenderObservable=new c,this.onAfterRenderObservable=new c,this.onDisposeObservable=new c,Pl();let L,V=1,Z=null;if(i&&!Array.isArray(i)){const e=i;i=e.uniforms??null,r=e.samplers??null,V=e.size??1,a=e.camera??null,o=e.samplingMode??dt.TEXTURE_NEAREST_SAMPLINGMODE,h=e.engine,l=e.reusable,u=Array.isArray(e.defines)?e.defines.join("\n"):e.defines??null,d=e.textureType??dt.TEXTURETYPE_UNSIGNED_BYTE,_=e.vertexUrl??"postprocess",p=e.indexParameters,f=e.blockCompilation??!1,g=e.textureFormat??dt.TEXTUREFORMAT_RGBA,m=e.shaderLanguage??0,Z=e.uniformBuffers??null,b=e.extraInitializations,L=e.effectWrapper}else n&&(V="number"==typeof n?n:{width:n.width,height:n.height});if(this._useExistingThinPostProcess=!!L,this._effectWrapper=L??new Sl({name:t,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:s,engine:h||a?.getScene().getEngine(),uniforms:i,samplers:r,uniformBuffers:Z,defines:u,vertexUrl:_,indexParameters:p,blockCompilation:!0,shaderLanguage:m,extraInitializations:void 0}),this.name=t,this.onEffectCreatedObservable=this._effectWrapper.onEffectCreatedObservable,null!=a?(this._camera=a,this._scene=a.getScene(),a.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.addPostProcess(this),this.uniqueId=this._scene.getUniqueId()):h&&(this._engine=h,this._engine.postProcesses.push(this)),this._options=V,this.renderTargetSamplingMode=o||dt.TEXTURE_NEAREST_SAMPLINGMODE,this._reusable=l||!1,this._textureType=d,this._textureFormat=g,this._shaderLanguage=m||0,this._samplers=r||[],-1===this._samplers.indexOf("textureSampler")&&this._samplers.push("textureSampler"),this._fragmentUrl=s,this._vertexUrl=_,this._parameters=i||[],-1===this._parameters.indexOf("scale")&&this._parameters.push("scale"),this._uniformBuffers=Z||[],this._indexParameters=p,!this._useExistingThinPostProcess){this._webGPUReady=1===this._shaderLanguage;const t=[];this._gatherImports(this._engine.isWebGPU&&!e.ForceGLSL,t),this._effectWrapper._webGPUReady=this._webGPUReady,this._effectWrapper._postConstructor(f,u,b,t)}}_gatherImports(e=!1,t){e&&this._webGPUReady?t.push(Promise.all([import("./postprocess.vertex-BraBtVHc.esm.min.js")])):t.push(Promise.all([import("./postprocess.vertex-cg5rO15y.esm.min.js")]))}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._effectWrapper.drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new Ws(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,s=null,i,r,n,a,o){this._effectWrapper.updateEffect(e,t,s,i,r,n,a,o),this._postProcessDefines=Array.isArray(this._effectWrapper.options.defines)?this._effectWrapper.options.defines.join("\n"):this._effectWrapper.options.defines}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,s=0){for(let i=0;i<this._textureCache.length;i++)if(this._textureCache[i].texture.width===e.width&&this._textureCache[i].texture.height===e.height&&this._textureCache[i].postProcessChannel===s&&this._textureCache[i].texture._generateDepthBuffer===t.generateDepthBuffer&&this._textureCache[i].texture.samples===t.samples)return this._textureCache[i].texture;const i=this._engine.createRenderTargetTexture(e,t);return this._textureCache.push({texture:i,postProcessChannel:s,lastUsedRenderId:-1}),i}_flushTextureCache(){const e=this._renderId;for(let t=this._textureCache.length-1;t>=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let s=0;s<this._textures.length;s++)if(this._textures.data[s]===this._textureCache[t].texture){e=!0;break}e||(this._textureCache[t].texture.dispose(),this._textureCache.splice(t,1))}}resize(e,t,s=null,i=!1,r=!1){this._textures.length>0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(s)for(let e=0;e<s._postProcesses.length;e++)if(null!==s._postProcesses[e]){n=s._postProcesses[e];break}const a={width:this.width,height:this.height},o={generateMipMaps:i,generateDepthBuffer:r||n===this,generateStencilBuffer:(r||n===this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType,format:this._textureFormat,samples:this._samples,label:"PostProcessRTT-"+this.name};this._textures.push(this._createRenderTargetTexture(a,o,0)),this._reusable&&this._textures.push(this._createRenderTargetTexture(a,o,1)),this._texelSize.copyFromFloats(1/this.width,1/this.height),this.onSizeChangedObservable.notifyObservers(this)}_getTarget(){let e;if(this._shareOutputWithPostProcess)e=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)e=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{let t;e=this.inputTexture;for(let s=0;s<this._textureCache.length;s++)if(this._textureCache[s].texture===e){t=this._textureCache[s];break}t&&(t.lastUsedRenderId=this._renderId)}return e}activate(e,t=null,s){const i=null===e||void 0!==e.cameraRigMode?e||this._camera:null,r=i?.getScene()??e,n=r.getEngine(),a=n.getCaps().maxTextureSize,o=(t?t.width:this._engine.getRenderWidth(!0))*this._options|0,h=(t?t.height:this._engine.getRenderHeight(!0))*this._options|0;let l=this._options.width||o,c=this._options.height||h;const u=this.renderTargetSamplingMode!==dt.TEXTURE_NEAREST_LINEAR&&this.renderTargetSamplingMode!==dt.TEXTURE_NEAREST_NEAREST&&this.renderTargetSamplingMode!==dt.TEXTURE_LINEAR_LINEAR;let d=null;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){const e=n.currentViewport;e&&(l*=e.width,c*=e.height)}(u||this.alwaysForcePOT)&&(this._options.width||(l=n.needPOTTextures?ws(l,a,this.scaleMode):l),this._options.height||(c=n.needPOTTextures?ws(c,a,this.scaleMode):c)),this.width===l&&this.height===c&&(d=this._getTarget())||this.resize(l,c,i,u,s),this._textures.forEach(e=>{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)}),this._flushTextureCache(),this._renderId++}return d||(d=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/l,h/c),this._engine.bindFramebuffer(d,0,o,h,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(d,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(i),this.autoClear&&(this.alphaMode===dt.ALPHA_DISABLE||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:r.clearColor,r._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),d}get isSupported(){return this._effectWrapper.drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._effectWrapper.isReady()}apply(){if(!this._effectWrapper.isReady())return null;let e;return this._engine.enableEffect(this._effectWrapper.drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),this._engine.setAlphaMode(this.alphaMode),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._effectWrapper.drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._effectWrapper.drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._effectWrapper.drawWrapper.effect),this._effectWrapper.bind(!0),this._effectWrapper.drawWrapper.effect}_disposeTextures(){this._shareOutputWithPostProcess||this._forcedOutputTexture?this._disposeTextureCache():(this._disposeTextureCache(),this._textures.dispose())}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return!!this._prePassEffectConfiguration&&(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0)}dispose(e){let t;if(e=e||this._camera,this._useExistingThinPostProcess||this._effectWrapper.dispose(),this._disposeTextures(),this._scene&&this._scene.removePostProcess(this),this._parentContainer&&(t=this._parentContainer.postProcesses.indexOf(this),t>-1&&this._parentContainer.postProcesses.splice(t,1),this._parentContainer=null),t=this._engine.postProcesses.indexOf(this),-1!==t&&this._engine.postProcesses.splice(t,1),this.onDisposeObservable.notifyObservers(),e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),0===t&&e._postProcesses.length>0){const e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear(),this.onEffectCreatedObservable.clear()}}serialize(){const e=$e.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.uniformBuffers=this._uniformBuffers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const t=this.serialize();t._engine=this._engine,t.cameraId=null;const s=e.Parse(t,this._scene,"");return s?(s.onActivateObservable=this.onActivateObservable.clone(),s.onSizeChangedObservable=this.onSizeChangedObservable.clone(),s.onApplyObservable=this.onApplyObservable.clone(),s.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),s.onAfterRenderObservable=this.onAfterRenderObservable.clone(),s._prePassEffectConfiguration=this._prePassEffectConfiguration,s):null}static Parse(e,t,s){const i=Ae(e.customType);if(!i||!i._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return i._Parse(e,r,t,s)}static _Parse(t,s,i,r){return $e.Parse(()=>new e(t.name,t.fragmentUrl,t.parameters,t.samplers,t.options,s,t.renderTargetSamplingMode,t._engine,t.reusable,t.defines,t.textureType,t.vertexUrl,t.indexParameters,!1,t.textureFormat),t,i,r)}},(()=>{const c="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;t=[L()],s=[L()],i=[L()],r=[L()],n=[L()],a=[V()],o=[L()],h=[L()],l=[L()],u=[L()],d=[L()],_=[L()],p=[L()],f=[L()],g=[L("samples")],m=[L()],b(e,null,s,{kind:"getter",name:"name",static:!1,private:!1,access:{has:e=>"name"in e,get:e=>e.name},metadata:c},null,T),b(e,null,l,{kind:"getter",name:"alphaMode",static:!1,private:!1,access:{has:e=>"alphaMode"in e,get:e=>e.alphaMode},metadata:c},null,T),b(null,null,t,{kind:"field",name:"uniqueId",static:!1,private:!1,access:{has:e=>"uniqueId"in e,get:e=>e.uniqueId,set:(e,t)=>{e.uniqueId=t}},metadata:c},E,R),b(null,null,i,{kind:"field",name:"width",static:!1,private:!1,access:{has:e=>"width"in e,get:e=>e.width,set:(e,t)=>{e.width=t}},metadata:c},y,M),b(null,null,r,{kind:"field",name:"height",static:!1,private:!1,access:{has:e=>"height"in e,get:e=>e.height,set:(e,t)=>{e.height=t}},metadata:c},x,S),b(null,null,n,{kind:"field",name:"renderTargetSamplingMode",static:!1,private:!1,access:{has:e=>"renderTargetSamplingMode"in e,get:e=>e.renderTargetSamplingMode,set:(e,t)=>{e.renderTargetSamplingMode=t}},metadata:c},v,I),b(null,null,a,{kind:"field",name:"clearColor",static:!1,private:!1,access:{has:e=>"clearColor"in e,get:e=>e.clearColor,set:(e,t)=>{e.clearColor=t}},metadata:c},P,C),b(null,null,o,{kind:"field",name:"autoClear",static:!1,private:!1,access:{has:e=>"autoClear"in e,get:e=>e.autoClear,set:(e,t)=>{e.autoClear=t}},metadata:c},O,D),b(null,null,h,{kind:"field",name:"forceAutoClearInAlphaMode",static:!1,private:!1,access:{has:e=>"forceAutoClearInAlphaMode"in e,get:e=>e.forceAutoClearInAlphaMode,set:(e,t)=>{e.forceAutoClearInAlphaMode=t}},metadata:c},w,F),b(null,null,u,{kind:"field",name:"alphaConstants",static:!1,private:!1,access:{has:e=>"alphaConstants"in e,get:e=>e.alphaConstants,set:(e,t)=>{e.alphaConstants=t}},metadata:c},N,B),b(null,null,d,{kind:"field",name:"enablePixelPerfectMode",static:!1,private:!1,access:{has:e=>"enablePixelPerfectMode"in e,get:e=>e.enablePixelPerfectMode,set:(e,t)=>{e.enablePixelPerfectMode=t}},metadata:c},U,k),b(null,null,_,{kind:"field",name:"forceFullscreenViewport",static:!1,private:!1,access:{has:e=>"forceFullscreenViewport"in e,get:e=>e.forceFullscreenViewport,set:(e,t)=>{e.forceFullscreenViewport=t}},metadata:c},G,H),b(null,null,p,{kind:"field",name:"scaleMode",static:!1,private:!1,access:{has:e=>"scaleMode"in e,get:e=>e.scaleMode,set:(e,t)=>{e.scaleMode=t}},metadata:c},z,W),b(null,null,f,{kind:"field",name:"alwaysForcePOT",static:!1,private:!1,access:{has:e=>"alwaysForcePOT"in e,get:e=>e.alwaysForcePOT,set:(e,t)=>{e.alwaysForcePOT=t}},metadata:c},X,K),b(null,null,g,{kind:"field",name:"_samples",static:!1,private:!1,access:{has:e=>"_samples"in e,get:e=>e._samples,set:(e,t)=>{e._samples=t}},metadata:c},Y,j),b(null,null,m,{kind:"field",name:"adaptScaleToCurrentViewport",static:!1,private:!1,access:{has:e=>"adaptScaleToCurrentViewport"in e,get:e=>e.adaptScaleToCurrentViewport,set:(e,t)=>{e.adaptScaleToCurrentViewport=t}},metadata:c},q,$),c&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:c})})(),e})(),Il=!1;function Pl(){Il||(Il=!0,Ti.prototype.setTextureFromPostProcess=function(e,t,s){let i=null;t&&(t._forcedOutputTexture?i=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(i=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,i?.texture??null,s)},Ti.prototype.setTextureFromPostProcessOutput=function(e,t,s){this._bindTexture(e,t?._outputTexture?.texture??null,s)},li.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)},li.prototype.setTextureFromPostProcessOutput=function(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)},be("BABYLON.PostProcess",vl))}class Cl extends Sl{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([import("./pass.fragment-Dh9qe60n.esm.min.js")]))):t.push(Promise.all([import("./pass.fragment-C0dNPHFu.esm.min.js")])),super._gatherImports(e,t)}constructor(e,t=null,s){const i={name:e,engine:t||ee.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:Cl.FragmentUrl,...s};i.engine||(i.engine=ee.LastCreatedEngine),super(i)}}Cl.FragmentUrl="pass";class Ol extends Sl{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([import("./passCube.fragment-uqemK-hD.esm.min.js")]))):t.push(Promise.all([import("./passCube.fragment-xROFffBg.esm.min.js")])),super._gatherImports(e,t)}constructor(e,t=null,s){super({...s,name:e,engine:t||ee.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:Ol.FragmentUrl,defines:"#define POSITIVEX"}),this._face=0}get face(){return this._face}set face(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ")}}}Ol.FragmentUrl="passCube";class Dl extends vl{getClassName(){return"PassPostProcess"}constructor(e,t,s=null,i,r,n,a=dt.TEXTURETYPE_UNSIGNED_BYTE,o=!1){const h={size:"number"==typeof t?t:void 0,camera:s,samplingMode:i,engine:r,reusable:n,textureType:a,blockCompilation:o,...t};super(e,Cl.FragmentUrl,{effectWrapper:"number"!=typeof t&&t.effectWrapper?void 0:new Cl(e,r,h),...h})}static _Parse(e,t,s,i){return $e.Parse(()=>new Dl(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,s,i)}}(()=>{var e;let t,s=vl,i=[];e=class extends s{get face(){return this._effectWrapper.face}set face(e){this._effectWrapper.face=e}getClassName(){return"PassCubePostProcess"}constructor(e,t,s=null,r,n,a,o=dt.TEXTURETYPE_UNSIGNED_BYTE,h=!1){const l={size:"number"==typeof t?t:void 0,camera:s,samplingMode:r,engine:n,reusable:a,textureType:o,blockCompilation:h,...t};super(e,Cl.FragmentUrl,{effectWrapper:"number"!=typeof t&&t.effectWrapper?void 0:new Ol(e,n,l),...l}),A(this,i)}static _Parse(t,s,i,r){return $e.Parse(()=>new e(t.name,t.options,s,t.renderTargetSamplingMode,t._engine,t.reusable),t,i,r)}},(()=>{const r="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;t=[L()],b(e,null,t,{kind:"getter",name:"face",static:!1,private:!1,access:{has:e=>"face"in e,get:e=>e.face},metadata:r},null,i),r&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:r})})()})();const wl=de,Ll={..._e,TwoPi:2*Math.PI,Sign:Math.sign,Log2:Math.log2,HCF:wl},Fl="positions",Nl="positionsUpdate",Bl="partMatrices",Ul="partIndices",kl="intervals",Gl="sort",Vl=function(e){let t,s,i,r,n,a,o,h,l=0,c=null;e.onmessage=u=>{const d=u.data.command;if("positions"===d)t=u.data.positions,l=u.data.vertexCount;else if("positionsUpdate"===d)t&&u.data.data&&t.set(u.data.data,u.data.offset);else if("partMatrices"===d)r=u.data.partMatrices;else if("partIndices"===d)i=u.data.partIndices;else if("intervals"===d)c=u.data.intervals;else if("sort"===d){const d=u.data.cameraId,_=u.data.sortRequestId,p=u.data.rangeVersion,f=u.data.worldMatrix,g=u.data.cameraForward,m=u.data.cameraPosition;if(s=u.data.depthMix,!t||!g)return void e.postMessage({command:"sorted",depthMix:s,cameraId:d,sortRequestId:_,rangeVersion:p},[s.buffer]);const T=!1!==u.data.useCountingSort,E=!!u.data.logSortPerformance,R=u.data.rightHanded?-1:1,b=c,A=t.length/4,y=l;let M=A;if(b){M=0;for(let e=1;e<b.length;e+=2)M+=b[e]}const x=Math.max(M+15&-16,16),S=g[0]*m[0]+g[1]*m[1]+g[2]*m[2],v=e=>[g[0]*e[0]+g[1]*e[1]+g[2]*e[2],g[0]*e[4]+g[1]*e[5]+g[2]*e[6],g[0]*e[8]+g[1]*e[9]+g[2]*e[10],g[0]*e[12]+g[1]*e[13]+g[2]*e[14]-S],I=globalThis.performance,P=E&&I?I.now():0;try{if(T){const l=new Uint32Array(s.buffer);if(!n||n.length<M){const e=Math.max(M,16);n=new Uint32Array(e),a=new Float32Array(e),o=new Uint32Array(e)}const c=!!(r&&r.length>0&&i&&i.length>0);let u=[],g=0,m=0,T=0,E=0,S=0;if(c)u=r.map(e=>{const t=v(e);return t[0]*=R,t[1]*=R,t[2]*=R,t[3]*=R,t}),g=i.length;else{const e=v(f);m=e[0]*R,T=e[1]*R,E=e[2]*R,S=e[3]*R}let I=0,P=1/0,C=-1/0;const O=u.length;let D=!1;const w=b?b.length:2;e:for(let e=0;e<w;e+=2){const s=b?b[e]:0,r=s+(b?b[e+1]:A);if(c)for(let e=s;e<r;e++){const s=4*e,r=i[e<g?e:g-1];if(r>=O){D=!0;break e}const o=u[r],h=o[0]*t[s]+o[1]*t[s+1]+o[2]*t[s+2]+o[3];n[I]=e,a[I]=h,I++,h<P&&(P=h),h>C&&(C=h)}else for(let e=s;e<r;e++){const s=4*e,i=m*t[s]+T*t[s+1]+E*t[s+2]+S;n[I]=e,a[I]=i,I++,i<P&&(P=i),i>C&&(C=i)}}if(D)return void e.postMessage({command:"sorted",depthMix:s,cameraId:d,sortRequestId:_,rangeVersion:p},[s.buffer]);const L=2**Math.max(10,Math.min(20,Math.round(Math.log2(Math.max(1,M)/4))))+1;h&&h.length===L?h.fill(0):h=new Uint32Array(L);const F=C-P;if(F>1e-12){const e=(L-1)/F,t=L-1;for(let s=0;s<M;s++){let i=(C-a[s])*e>>>0;i>t&&(i=t),o[s]=i,h[i]++}}else{for(let e=0;e<M;e++)o[e]=0;h[0]=M}for(let e=1;e<L;e++)h[e]+=h[e-1];for(let e=0;e<M;e++){l[2*--h[o[e]]]=n[e]}for(let e=M;e<x;e++)l[2*e]=y}else{const e=new Uint32Array(s.buffer),n=new Float32Array(s.buffer);if(b){let t=0;for(let s=0;s<b.length;s+=2){const i=b[s],r=b[s+1];for(let s=i;s<i+r;s++)e[2*t++]=s}for(;t<x;t++)e[2*t]=y}else for(let t=0;t<x;t++)e[2*t]=t;let a=!1;if(r&&r.length>0&&i&&i.length>0){const s=r.map(e=>v(e)),o=i.length;for(let r=0;r<x;r++){const h=e[2*r],l=i[Math.min(h,o-1)];if(l>=s.length){a=!0;break}const c=s[l];n[2*r+1]=c[0]*t[4*h+0]+c[1]*t[4*h+1]+c[2]*t[4*h+2]+c[3],e[2*r+1]=~e[2*r+1]}}else{const[s,i,r,a]=v(f);for(let o=0;o<x;o++){const h=e[2*o];n[2*o+1]=s*t[4*h+0]+i*t[4*h+1]+r*t[4*h+2]+a,e[2*o+1]=~e[2*o+1]}}a||s.sort()}}catch(e){console.error("Gaussian splat sort worker encountered an error (will retry next frame):",e)}E&&I&&console.log(`[GaussianSplatting] ${T?"counting":"legacy"} sort: ${M} splats in ${(I.now()-P).toFixed(2)}ms`),e.postMessage({command:"sorted",depthMix:s,cameraId:d,sortRequestId:_,rangeVersion:p},[s.buffer])}}},Hl="undefined"!=typeof _native,zl=Hl?_native:null,Wl=(e,t)=>{const s=(1<<t)-1;return(e&s)/s},Xl=(e,t)=>{t.x=Wl(e>>>21,11),t.y=Wl(e>>>11,10),t.z=Wl(e,11)},Kl=(e,t)=>{t[0]=255*Wl(e>>>24,8),t[1]=255*Wl(e>>>16,8),t[2]=255*Wl(e>>>8,8),t[3]=255*Wl(e,8)},Yl=(e,t)=>{const s=1/(.5*Math.sqrt(2)),i=(Wl(e>>>20,10)-.5)*s,r=(Wl(e>>>10,10)-.5)*s,n=(Wl(e,10)-.5)*s,a=Math.sqrt(1-(i*i+r*r+n*n));switch(e>>>30){case 0:t.set(a,i,r,n);break;case 1:t.set(i,a,r,n);break;case 2:t.set(i,r,a,n);break;case 3:t.set(i,r,n,a)}};var jl,ql;!function(e){e[e.FLOAT=0]="FLOAT",e[e.INT=1]="INT",e[e.UINT=2]="UINT",e[e.DOUBLE=3]="DOUBLE",e[e.UCHAR=4]="UCHAR",e[e.USHORT=5]="USHORT",e[e.UNDEFINED=6]="UNDEFINED"}(jl||(jl={})),function(e){e[e.MIN_X=0]="MIN_X",e[e.MIN_Y=1]="MIN_Y",e[e.MIN_Z=2]="MIN_Z",e[e.MAX_X=3]="MAX_X",e[e.MAX_Y=4]="MAX_Y",e[e.MAX_Z=5]="MAX_Z",e[e.MIN_SCALE_X=6]="MIN_SCALE_X",e[e.MIN_SCALE_Y=7]="MIN_SCALE_Y",e[e.MIN_SCALE_Z=8]="MIN_SCALE_Z",e[e.MAX_SCALE_X=9]="MAX_SCALE_X",e[e.MAX_SCALE_Y=10]="MAX_SCALE_Y",e[e.MAX_SCALE_Z=11]="MAX_SCALE_Z",e[e.PACKED_POSITION=12]="PACKED_POSITION",e[e.PACKED_ROTATION=13]="PACKED_ROTATION",e[e.PACKED_SCALE=14]="PACKED_SCALE",e[e.PACKED_COLOR=15]="PACKED_COLOR",e[e.X=16]="X",e[e.Y=17]="Y",e[e.Z=18]="Z",e[e.SCALE_0=19]="SCALE_0",e[e.SCALE_1=20]="SCALE_1",e[e.SCALE_2=21]="SCALE_2",e[e.DIFFUSE_RED=22]="DIFFUSE_RED",e[e.DIFFUSE_GREEN=23]="DIFFUSE_GREEN",e[e.DIFFUSE_BLUE=24]="DIFFUSE_BLUE",e[e.OPACITY=25]="OPACITY",e[e.F_DC_0=26]="F_DC_0",e[e.F_DC_1=27]="F_DC_1",e[e.F_DC_2=28]="F_DC_2",e[e.F_DC_3=29]="F_DC_3",e[e.ROT_0=30]="ROT_0",e[e.ROT_1=31]="ROT_1",e[e.ROT_2=32]="ROT_2",e[e.ROT_3=33]="ROT_3",e[e.MIN_COLOR_R=34]="MIN_COLOR_R",e[e.MIN_COLOR_G=35]="MIN_COLOR_G",e[e.MIN_COLOR_B=36]="MIN_COLOR_B",e[e.MAX_COLOR_R=37]="MAX_COLOR_R",e[e.MAX_COLOR_G=38]="MAX_COLOR_G",e[e.MAX_COLOR_B=39]="MAX_COLOR_B",e[e.SH_0=40]="SH_0",e[e.SH_1=41]="SH_1",e[e.SH_2=42]="SH_2",e[e.SH_3=43]="SH_3",e[e.SH_4=44]="SH_4",e[e.SH_5=45]="SH_5",e[e.SH_6=46]="SH_6",e[e.SH_7=47]="SH_7",e[e.SH_8=48]="SH_8",e[e.SH_9=49]="SH_9",e[e.SH_10=50]="SH_10",e[e.SH_11=51]="SH_11",e[e.SH_12=52]="SH_12",e[e.SH_13=53]="SH_13",e[e.SH_14=54]="SH_14",e[e.SH_15=55]="SH_15",e[e.SH_16=56]="SH_16",e[e.SH_17=57]="SH_17",e[e.SH_18=58]="SH_18",e[e.SH_19=59]="SH_19",e[e.SH_20=60]="SH_20",e[e.SH_21=61]="SH_21",e[e.SH_22=62]="SH_22",e[e.SH_23=63]="SH_23",e[e.SH_24=64]="SH_24",e[e.SH_25=65]="SH_25",e[e.SH_26=66]="SH_26",e[e.SH_27=67]="SH_27",e[e.SH_28=68]="SH_28",e[e.SH_29=69]="SH_29",e[e.SH_30=70]="SH_30",e[e.SH_31=71]="SH_31",e[e.SH_32=72]="SH_32",e[e.SH_33=73]="SH_33",e[e.SH_34=74]="SH_34",e[e.SH_35=75]="SH_35",e[e.SH_36=76]="SH_36",e[e.SH_37=77]="SH_37",e[e.SH_38=78]="SH_38",e[e.SH_39=79]="SH_39",e[e.SH_40=80]="SH_40",e[e.SH_41=81]="SH_41",e[e.SH_42=82]="SH_42",e[e.SH_43=83]="SH_43",e[e.SH_44=84]="SH_44",e[e.SH_45=85]="SH_45",e[e.SH_46=86]="SH_46",e[e.SH_47=87]="SH_47",e[e.SH_48=88]="SH_48",e[e.SH_49=89]="SH_49",e[e.SH_50=90]="SH_50",e[e.SH_51=91]="SH_51",e[e.SH_52=92]="SH_52",e[e.SH_53=93]="SH_53",e[e.SH_54=94]="SH_54",e[e.SH_55=95]="SH_55",e[e.SH_56=96]="SH_56",e[e.SH_57=97]="SH_57",e[e.SH_58=98]="SH_58",e[e.SH_59=99]="SH_59",e[e.SH_60=100]="SH_60",e[e.SH_61=101]="SH_61",e[e.SH_62=102]="SH_62",e[e.SH_63=103]="SH_63",e[e.SH_64=104]="SH_64",e[e.SH_65=105]="SH_65",e[e.SH_66=106]="SH_66",e[e.SH_67=107]="SH_67",e[e.SH_68=108]="SH_68",e[e.SH_69=109]="SH_69",e[e.SH_70=110]="SH_70",e[e.SH_71=111]="SH_71",e[e.UNDEFINED=112]="UNDEFINED"}(ql||(ql={}));class $l extends Xn{static _GetSplatDataBytes(e){return ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}static _GetSplatDataFloats(e){const t=$l._GetSplatDataBytes(e),s=Float32Array.BYTES_PER_ELEMENT;if(t.byteLength%s!==0)throw new Error(`Gaussian splat data byte length (${t.byteLength}) is not divisible by ${s} and cannot be reinterpreted as Float32 data.`);if(t.byteOffset%s!==0){const e=new Uint8Array(t.byteLength);return e.set(t),new Float32Array(e.buffer,0,t.byteLength/s)}return new Float32Array(t.buffer,t.byteOffset,t.byteLength/s)}static _BuildSplatRangeData(e,t){if(null===e)return{ranges:null,count:t,key:""};const s=[];let i=0,r="";for(const n of e){const e=Math.max(0,Math.floor(n.offset)),a=Math.max(0,Math.floor(n.count)),o=Math.min(t,e+a),h=Math.max(0,o-e);0!==h&&(s.push(e,h),i+=h,r+=`${e}:${h};`)}return{ranges:new Uint32Array(s),count:i,key:r}}get disableDepthSort(){return this._disableDepthSort}set disableDepthSort(e){!this._disableDepthSort&&e?(this._worker?.terminate(),this._worker=null,this._disableDepthSort=!0):this._disableDepthSort&&!e&&(this._disableDepthSort=!1,this._sortIsDirty=!0,this._instantiateWorker())}get viewDirectionFactor(){return xe.OneReadOnly}get shDegree(){return this._shDegree}set shDegree(e){const t=this._maxShDegree,s=Math.max(0,Math.min(Math.round(e),t));this._shDegree!==s&&(this._shDegree=s,this.material?.resetDrawCache())}get maxShDegree(){return this._maxShDegree}get splatCount(){return this._splatIndex?.length}get renderedSplatCount(){return this._activeSplatRanges?this._activeSplatRenderCount:this._vertexCount}setSplatIndexRanges(e){this._setSplatIndexRanges(e)}_setSplatIndexRanges(e){const t=$l._BuildSplatRangeData(e,this._vertexCount);(null===this._activeSplatRanges?null===t.ranges:null!==t.ranges&&this._activeSplatRangeKey===t.key)||(this._activeSplatRanges=t.ranges,this._activeSplatRangeKey=t.key,this._activeSplatRenderCount=t.count,this._activeRangeVersion++,this._postIntervalsToWorker(),this._worker?(this._ensureDepthMixSize(Math.max(this._activeSplatRenderCount+15&-16,16)),this._sortIsDirty=!0,this._postToWorker(!0)):(this._updateSplatIndexBuffer(this._vertexCount),this._postToWorker(!0)))}get _isDepthSortSettled(){return this._readyToDisplay&&!this._sortIsDirty&&this._canPostToWorker}_ensureDepthMixSize(e){Hl||this._depthMix&&this._depthMix.length===e&&0!==this._depthMix.buffer.byteLength||(this._depthMix=new BigInt64Array(e))}_postIntervalsToWorker(){if(!this._worker)return;const e=this._activeSplatRanges?new Uint32Array(this._activeSplatRanges):new Uint32Array([0,this._vertexCount]);this._worker.postMessage({command:kl,intervals:e},[e.buffer])}_setExternalWorkBuffer(e,t,s,i,r,n,a,o=0,h){this._covariancesATexture=t,this._covariancesBTexture=s,this._centersTexture=e,this._colorsTexture=i,this._splatPositions=r,this._vertexCount=n,a&&a.length&&(this._shTextures=a,this._maxShDegree=o,this._shDegree=o),h&&h.length>=3&&(this._rotationsATexture=h[0],this._rotationsBTexture=h[1],this._rotationScaleTexture=h[2],this._needsRotationScaleTextures=!0),this._activeSplatRanges=null,this._activeSplatRangeKey="",this._activeSplatRenderCount=0,this._readyToDisplay=!1,this._instantiateWorker(),this.setEnabled(!0)}get splatsData(){return this._keepInRam?this._splatsData:null}get shData(){return this._keepInRam?this._shData:null}get splatSizeRange(){return isFinite(this._splatSizeMin)&&isFinite(this._splatSizeMax)?{min:this._splatSizeMin,max:this._splatSizeMax}:null}get covariancesATexture(){return this._covariancesATexture}get covariancesBTexture(){return this._covariancesBTexture}get centersTexture(){return this._centersTexture}get colorsTexture(){return this._colorsTexture}get rotationsATexture(){return this._rotationsATexture}get rotationsBTexture(){return this._rotationsBTexture}get rotationScaleTexture(){return this._rotationScaleTexture}get needsRotationScaleTextures(){return this._needsRotationScaleTextures}set needsRotationScaleTextures(e){this._needsRotationScaleTextures!==e&&(this._needsRotationScaleTextures=e,e&&this._covariancesATexture&&(this._splatsData?this.updateData(this._splatsData,this._shData??void 0,{flipY:!1},void 0,this._shDegree):a.Error("GaussianSplattingMeshBase: needsRotationScaleTextures was enabled after the mesh was already loaded, but the splat data is not kept in RAM. The rotation and scale matrix textures cannot be initialized. Please reload the mesh data via updateData() or construct with keepInRam=true.")))}get shTextures(){return this._shTextures}get useSog(){return this._useSog}get sogParams(){return this._sogParams}setSogTextureData(e){if(this._useSog=!0,this._sogParams?.codebookTexture?.dispose(),this._sogParams=e,this._vertexCount=e.splatCount,this._shDegree=e.shDegree??0,this._maxShDegree=this._shDegree,this._splatPositions=e.positions,this._covariancesATexture?.dispose(),this._covariancesBTexture?.dispose(),this._centersTexture?.dispose(),this._colorsTexture?.dispose(),this._rotationsATexture?.dispose(),this._shTextures)for(const e of this._shTextures)e.dispose();this._centersTexture=e.meansTextureL,this._covariancesATexture=e.meansTextureU,this._covariancesBTexture=e.scalesTexture,this._rotationsATexture=e.quatsTexture,this._colorsTexture=e.sh0Texture;const t=[];e.shCentroidsTexture&&t.push(e.shCentroidsTexture),e.shLabelsTexture&&t.push(e.shLabelsTexture),this._shTextures=t.length?t:null,this._material?.resetDrawCache();const s=e.meansTextureL.getSize();this._textureSize.x=s.width,this._textureSize.y=s.height,this._updateSplatIndexBuffer(this._vertexCount),this._instantiateWorker();const i=e.positions,r=new xe(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),n=new xe(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(let e=0;e<this._vertexCount;e++){const t=i[4*e+0],s=i[4*e+1],a=i[4*e+2];t<r.x&&(r.x=t),s<r.y&&(r.y=s),a<r.z&&(r.z=a),t>n.x&&(n.x=t),s>n.y&&(n.y=s),a>n.z&&(n.z=a)}this.getBoundingInfo().reConstruct(r,n,this.getWorldMatrix()),this.setEnabled(!0),this._sortIsDirty=!0}get kernelSize(){return this._material instanceof _l?this._material.kernelSize:0}get compensation(){return this._material instanceof _l&&this._material.compensation}get minPixelSize(){return this._material instanceof _l?this._material.minPixelSize:0}set minPixelSize(e){this._material instanceof _l&&(this._material.minPixelSize=Math.max(0,e))}set material(e){this._material=e,this._material.backFaceCulling=!1,this._material.cullBackFaces=!1,e.resetDrawCache()}get material(){return this._material}static _MakeSplatGeometryForMesh(e){const t=new or,s=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],i=[0,1,2,0,2,3],r=[],n=[];for(let e=0;e<$l._BatchSize;e++){for(let t=0;t<12;t++)2==t||5==t||8==t||11==t?r.push(e):r.push(s[t]);n.push(i.map(t=>t+4*e))}t.positions=r,t.indices=n.flat(),t.applyToMesh(e)}constructor(e,t=null,s=null,i=!1){super(e,s),this.safeOrbitCameraLimits=null,this._vertexCount=0,this._worker=null,this._modelViewProjectionMatrix=Ie.Identity(),this._canPostToWorker=!0,this._readyToDisplay=!1,this._sortRequestId=0,this._activeRangeVersion=0,this._hasRenderedOnce=!1,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._mrtAtlas=null,this._useMrtAtlas=!1,this._shMrtAtlas=null,this._useShMrtAtlas=!1,this._shMrtAtlasTextureCount=0,this._rotationsATexture=null,this._rotationsBTexture=null,this._rotationScaleTexture=null,this._rotMrtAtlas=null,this._useRotMrtAtlas=!1,this._rotationDataA=null,this._rotationDataB=null,this._rotationScaleData=null,this._needsRotationScaleTextures=!1,this._splatPositions=null,this._splatIndex=null,this._shTextures=null,this._splatsData=null,this._shData=null,this._textureSize=new Me(0,0),this._keepInRam=!1,this._alwaysRetainSplatsData=!1,this._flipY=!1,this._delayedTextureUpdate=null,this._useRGBACovariants=!1,this._useSog=!1,this._sogParams=null,this._material=null,this._tmpCovariances=[0,0,0,0,0,0],this._splatSizeMin=1/0,this._splatSizeMax=-1/0,this._sortIsDirty=!1,this._activeSplatRanges=null,this._activeSplatRangeKey="",this._activeSplatRenderCount=0,this._cachedBoundingMin=null,this._cachedBoundingMax=null,this._shDegree=0,this._maxShDegree=0,this._cameraViewInfos=new Map,this.onPartCountChangedObservable=new c,this.onPartRemovedObservable=new c,this._onBeforeAtlasRebuildObservable=new c,this._onAfterAtlasRebuildObservable=new c,this.viewUpdateThreshold=$l._DefaultViewUpdateThreshold,this._disableDepthSort=!1,this._loadingPromise=null,this._updateTextureFromData=(e,t,s,i,r)=>{this._getTextureDataUpdateEngine().updateTextureData(e.getInternalTexture(),t,0,i,s,r,0,0,!1)},this._updateTextureFromDataRect=(e,t,s,i,r,n)=>{this._getTextureDataUpdateEngine().updateTextureData(e.getInternalTexture(),t,s,i,r,n,0,0,!1)},this.subMeshes=[],new nr(0,0,4*$l._BatchSize,0,6*$l._BatchSize,this),this.setEnabled(!1),this._useRGBACovariants=!this.getEngine().isWebGPU&&1===this.getEngine().version,function(e){if(Hl)return;const t=e.customAnimationFrameRequester;if(t?._gsInterFrameYield)return void t._refCount++;if(t)return;let s=0,i=0;const r={_gsInterFrameYield:!0,_refCount:1,requestAnimationFrame:e=>(s=setTimeout(()=>{i=requestAnimationFrame(e)},0),s),cancelAnimationFrame:e=>{clearTimeout(s),i>0&&cancelAnimationFrame(i),s=0,i=0}};e.customAnimationFrameRequester=r}(this.getEngine()),this._keepInRam=i,t&&(this._loadingPromise=this.loadFileAsync(t));const r=new _l(this.name+"_material",this._scene);r.setSourceMesh(this),r.doNotSerialize=!0,this._material=r,this._scene.onCameraRemovedObservable.add(e=>{const t=e.uniqueId,s=this._cameraViewInfos.get(t);s&&(this._geometry===s.mesh.geometry&&(this._geometry=null),s.mesh.dispose(),this._cameraViewInfos.delete(t))})}getLoadingPromise(){return this._loadingPromise}getClassName(){return"GaussianSplattingMeshBase"}getTotalVertices(){return this._vertexCount}isReady(e=!1){if(!super.isReady(e,!0))return!1;if(!this._readyToDisplay)return this._postToWorker(!0),!1;if(!this._hasRenderedOnce&&!this._disableDepthSort){const e=this._scene.activeCameras?.length?this._scene.activeCameras:[this._scene.activeCamera],t=this.computeWorldMatrix(!0);let s=!1;for(const i of e){if(!i)continue;const e=this._cameraViewInfos.get(i.uniqueId);e&&e.splatIndexBufferSet?e.sortAppliedId===e.sortRequestId?this._isSortStateDirty(e,t,i,!0)&&(s=!0):s=!0:s=!0}if(s)return this._postToWorker(!0),!1}if(!this._geometry&&this._cameraViewInfos.size&&(this._geometry=this._cameraViewInfos.values().next().value.mesh.geometry),this.material&&this.material.shadowDepthWrapper){const e=this._scene.getEngine(),t=e.currentRenderPassId;try{for(const t of this._scene.lights){const s=t.getShadowGenerator();if(!s)continue;const i=s.getShadowMap(),r=i?.renderPassIds;if(r&&0!==r.length)for(let t=0;t<r.length;++t){e.currentRenderPassId=r[t];for(const e of this.subMeshes)if(!s.isReady(e,!0,!1))return!1}}}finally{e.currentRenderPassId=t}}return!0}_getCameraDirection(e){const t=e.getViewMatrix(),s=e.getProjectionMatrix(),i=Ce.Matrix[0];t.multiplyToRef(s,i);const r=this.computeWorldMatrix(!0),n=Ce.Matrix[1];r.multiplyToRef(t,n),r.multiplyToRef(i,this._modelViewProjectionMatrix);const a=Ce.Vector3[1];return a.set(n.m[2],n.m[6],n.m[10]),a.normalize(),a}_isSortStateDirty(e,t,s,i=!1){const r=t.m,n=e.sortWorldMatrix.m;for(let e=0;e<n.length;e++)if(!Ll.WithinEpsilon(n[e],r[e],this.viewUpdateThreshold))return!0;if(i)return!1;const a=s.getViewMatrix();if(!Ll.WithinEpsilon(e.sortCameraForward.x,a.m[2],this.viewUpdateThreshold)||!Ll.WithinEpsilon(e.sortCameraForward.y,a.m[6],this.viewUpdateThreshold)||!Ll.WithinEpsilon(e.sortCameraForward.z,a.m[10],this.viewUpdateThreshold))return!0;const o=s.globalPosition;return!Ll.WithinEpsilon(e.sortCameraPosition.x,o.x,this.viewUpdateThreshold)||!Ll.WithinEpsilon(e.sortCameraPosition.y,o.y,this.viewUpdateThreshold)||!Ll.WithinEpsilon(e.sortCameraPosition.z,o.z,this.viewUpdateThreshold)}_postToWorker(e=!1){const t=this._scene.getFrameId();let s=!1;this._cameraViewInfos.forEach(e=>{e.frameIdLastUpdate!==t&&(s=!0)});const i=this._scene.activeCameras?.length?this._scene.activeCameras:[this._scene.activeCamera],r=[];i.forEach(e=>{if(!e)return;const s=e.uniqueId,i=this._cameraViewInfos.get(s);if(i)r.push(i);else{const i=new Xn(this.name+"_cameraMesh_"+s,this._scene);if(i.doNotSerialize=!0,i.reservedDataStore={hidden:!0},i.setEnabled(!1),i.material=this.material,i.material&&i.material instanceof _l){const e=i.material;e.getSourceMesh()||e.setSourceMesh(this)}$l._MakeSplatGeometryForMesh(i);const n={camera:e,cameraDirection:new xe(0,0,0),sortWorldMatrix:Ie.Identity(),sortCameraForward:new xe(0,0,0),sortCameraPosition:new xe(0,0,0),sortRequestId:0,sortAppliedId:0,mesh:i,frameIdLastUpdate:t,splatIndexBufferSet:!1};r.push(n),this._cameraViewInfos.set(s,n)}}),r.sort((e,t)=>e.splatIndexBufferSet!==t.splatIndexBufferSet?e.splatIndexBufferSet?1:-1:e.frameIdLastUpdate-t.frameIdLastUpdate);const n=!!zl?.sortSplats&&!!this._splatPositions&&!!this._splatIndex,a=!this._disableDepthSort&&(this._worker||n);if((e||s)&&a&&(this._scene.activeCameras?.length||this._scene.activeCamera)&&this._canPostToWorker){const s=this.computeWorldMatrix(!0);r.forEach(i=>{const r=i.camera,n=this._getCameraDirection(r);if((e||this._isSortStateDirty(i,s,r))&&this._canPostToWorker){const e=r.getViewMatrix();i.cameraDirection.copyFrom(n),i.sortWorldMatrix.copyFrom(s),i.sortCameraForward.set(e.m[2],e.m[6],e.m[10]),i.sortCameraPosition.copyFrom(r.globalPosition),i.sortRequestId=++this._sortRequestId,i.frameIdLastUpdate=t,this._canPostToWorker=!1,this._worker?this._worker.postMessage({command:Gl,worldMatrix:s.m,cameraForward:[e.m[2],e.m[6],e.m[10]],cameraPosition:[r.globalPosition.x,r.globalPosition.y,r.globalPosition.z],depthMix:this._depthMix,cameraId:r.uniqueId,sortRequestId:i.sortRequestId,rangeVersion:this._activeRangeVersion,useCountingSort:$l.UseCountingSort,rightHanded:this._scene.useRightHandedSystem,logSortPerformance:$l.LogSortPerformance},[this._depthMix.buffer]):zl?.sortSplats&&(this._activeSplatRanges?this._updateSplatIndexBuffer(this._vertexCount):zl.sortSplats(this._modelViewProjectionMatrix,this._splatPositions,this._splatIndex,this._scene.useRightHandedSystem),i.splatIndexBufferSet?i.mesh.thinInstanceBufferUpdated("splatIndex"):(i.mesh.thinInstanceSetBuffer("splatIndex",this._splatIndex,16,!1),i.splatIndexBufferSet=!0),i.sortAppliedId=i.sortRequestId,this._canPostToWorker=!0,this._readyToDisplay=!0)}})}else this._disableDepthSort&&(this._splatIndex&&(r.forEach(e=>{e.splatIndexBufferSet||(e.mesh.thinInstanceSetBuffer("splatIndex",this._splatIndex,16,!1),e.splatIndexBufferSet=!0)}),this._readyToDisplay=!0),this._canPostToWorker=!0)}render(e,t,s){this._postToWorker(),!this._geometry&&this._cameraViewInfos.size&&(this._geometry=this._cameraViewInfos.values().next().value.mesh.geometry);const i=this._scene.activeCamera.uniqueId,r=this._cameraViewInfos.get(i);if(!r||!r.splatIndexBufferSet)return this;this.onBeforeRenderObservable&&this.onBeforeRenderObservable.notifyObservers(this);const n=r.mesh;n.getWorldMatrix().copyFrom(this.getWorldMatrix());const a=this._scene.getEngine().currentRenderPassId,o=this.getMaterialForRenderPass(a);o&&n.setMaterialForRenderPass(a,o);const h=n.render(e,t,s);return this._hasRenderedOnce=!0,o&&n.setMaterialForRenderPass(a,void 0),this.onAfterRenderObservable&&this.onAfterRenderObservable.notifyObservers(this),h}static _TypeNameToEnum(e){switch(e){case"float":return 0;case"int":return 1;case"uint":return 2;case"double":return 3;case"uchar":return 4;case"ushort":case"uint16":return 5}return 6}static _ValueNameToEnum(e){switch(e){case"min_x":return 0;case"min_y":return 1;case"min_z":return 2;case"max_x":return 3;case"max_y":return 4;case"max_z":return 5;case"min_scale_x":return 6;case"min_scale_y":return 7;case"min_scale_z":return 8;case"max_scale_x":return 9;case"max_scale_y":return 10;case"max_scale_z":return 11;case"packed_position":return 12;case"packed_rotation":return 13;case"packed_scale":return 14;case"packed_color":return 15;case"x":return 16;case"y":return 17;case"z":return 18;case"scale_0":return 19;case"scale_1":return 20;case"scale_2":return 21;case"diffuse_red":case"red":return 22;case"diffuse_green":case"green":return 23;case"diffuse_blue":case"blue":return 24;case"f_dc_0":return 26;case"f_dc_1":return 27;case"f_dc_2":return 28;case"f_dc_3":return 29;case"opacity":return 25;case"rot_0":return 30;case"rot_1":return 31;case"rot_2":return 32;case"rot_3":return 33;case"min_r":return 34;case"min_g":return 35;case"min_b":return 36;case"max_r":return 37;case"max_g":return 38;case"max_b":return 39;case"f_rest_0":return 40;case"f_rest_1":return 41;case"f_rest_2":return 42;case"f_rest_3":return 43;case"f_rest_4":return 44;case"f_rest_5":return 45;case"f_rest_6":return 46;case"f_rest_7":return 47;case"f_rest_8":return 48;case"f_rest_9":return 49;case"f_rest_10":return 50;case"f_rest_11":return 51;case"f_rest_12":return 52;case"f_rest_13":return 53;case"f_rest_14":return 54;case"f_rest_15":return 55;case"f_rest_16":return 56;case"f_rest_17":return 57;case"f_rest_18":return 58;case"f_rest_19":return 59;case"f_rest_20":return 60;case"f_rest_21":return 61;case"f_rest_22":return 62;case"f_rest_23":return 63;case"f_rest_24":return 64;case"f_rest_25":return 65;case"f_rest_26":return 66;case"f_rest_27":return 67;case"f_rest_28":return 68;case"f_rest_29":return 69;case"f_rest_30":return 70;case"f_rest_31":return 71;case"f_rest_32":return 72;case"f_rest_33":return 73;case"f_rest_34":return 74;case"f_rest_35":return 75;case"f_rest_36":return 76;case"f_rest_37":return 77;case"f_rest_38":return 78;case"f_rest_39":return 79;case"f_rest_40":return 80;case"f_rest_41":return 81;case"f_rest_42":return 82;case"f_rest_43":return 83;case"f_rest_44":return 84;case"f_rest_45":return 85;case"f_rest_46":return 86;case"f_rest_47":return 87;case"f_rest_48":return 88;case"f_rest_49":return 89;case"f_rest_50":return 90;case"f_rest_51":return 91;case"f_rest_52":return 92;case"f_rest_53":return 93;case"f_rest_54":return 94;case"f_rest_55":return 95;case"f_rest_56":return 96;case"f_rest_57":return 97;case"f_rest_58":return 98;case"f_rest_59":return 99;case"f_rest_60":return 100;case"f_rest_61":return 101;case"f_rest_62":return 102;case"f_rest_63":return 103;case"f_rest_64":return 104;case"f_rest_65":return 105;case"f_rest_66":return 106;case"f_rest_67":return 107;case"f_rest_68":return 108;case"f_rest_69":return 109;case"f_rest_70":return 110;case"f_rest_71":return 111}return 112}static ParseHeader(e){const t=new Uint8Array(e),s=(new TextDecoder).decode(t.slice(0,10240)),i="end_header\n",r=s.indexOf(i);if(r<0||!s)return null;const n=parseInt(/element vertex (\d+)\n/.exec(s)[1]),o=/element chunk (\d+)\n/.exec(s);let h=0;o&&(h=parseInt(o[1]));let l=0,c=0;const u={double:8,int:4,uint:4,float:4,short:2,ushort:2,uint16:2,uchar:1,list:0};let d;!function(e){e[e.Vertex=0]="Vertex",e[e.Chunk=1]="Chunk",e[e.SH=2]="SH",e[e.Unused=3]="Unused"}(d||(d={}));let _=1;const p=[],f=[],g=s.slice(0,r).split("\n");let m=0;for(const e of g)if(e.startsWith("property ")){const[,t,s]=e.split(" "),i=$l._ValueNameToEnum(s);112!=i&&(i>=111?m=4:i>=84?m=Math.max(m,3):i>=63?m=Math.max(m,2):i>=48&&(m=Math.max(m,1)));const r=$l._TypeNameToEnum(t);1==_?(f.push({value:i,type:r,offset:c}),c+=u[t]):0==_?(p.push({value:i,type:r,offset:l}),l+=u[t]):2==_&&p.push({value:i,type:r,offset:l}),u[t]||a.Warn(`Unsupported property type: ${t}.`)}else if(e.startsWith("element ")){const[,t]=e.split(" ");_="chunk"==t?1:"vertex"==t?0:"sh"==t?2:3}const T=new DataView(e,r+11),E=new ArrayBuffer($l._RowOutputLength*n);let R=null,b=0;if(m){b=3*((m+1)*(m+1)-1),R=new ArrayBuffer(b*n)}return{vertexCount:n,chunkCount:h,rowVertexLength:l,rowChunkLength:c,vertexProperties:p,chunkProperties:f,dataView:T,buffer:E,shDegree:m,shCoefficientCount:b,shBuffer:R}}static _GetCompressedChunks(e,t){if(!e.chunkCount)return null;const s=e.dataView,i=new Array(e.chunkCount);for(let r=0;r<e.chunkCount;r++){const n={min:new xe,max:new xe,minScale:new xe,maxScale:new xe,minColor:new xe(0,0,0),maxColor:new xe(1,1,1)};i[r]=n;for(let i=0;i<e.chunkProperties.length;i++){const r=e.chunkProperties[i];let a;if(0===r.type)switch(a=s.getFloat32(r.offset+t.value,!0),r.value){case 0:n.min.x=a;break;case 1:n.min.y=a;break;case 2:n.min.z=a;break;case 3:n.max.x=a;break;case 4:n.max.y=a;break;case 5:n.max.z=a;break;case 6:n.minScale.x=a;break;case 7:n.minScale.y=a;break;case 8:n.minScale.z=a;break;case 9:n.maxScale.x=a;break;case 10:n.maxScale.y=a;break;case 11:n.maxScale.z=a;break;case 34:n.minColor.x=a;break;case 35:n.minColor.y=a;break;case 36:n.minColor.z=a;break;case 37:n.maxColor.x=a;break;case 38:n.maxColor.y=a;break;case 39:n.maxColor.z=a}}t.value+=e.rowChunkLength}return i}static _GetSplat(e,t,s,i){const r=Ce.Quaternion[0],n=Ce.Vector3[0],a=$l._RowOutputLength,o=e.buffer,h=e.dataView,l=new Float32Array(o,t*a,3),c=new Float32Array(o,t*a+12,3),u=new Uint8ClampedArray(o,t*a+24,4),d=new Uint8ClampedArray(o,t*a+28,4);let _=null;e.shBuffer&&(_=new Uint8ClampedArray(e.shBuffer,t*e.shCoefficientCount,e.shCoefficientCount));const p=t>>8;let f=255,g=0,m=0,T=0;const E=[];for(let a=0;a<e.vertexProperties.length;a++){const o=e.vertexProperties[a];let d;switch(o.type){case 0:d=h.getFloat32(i.value+o.offset,!0);break;case 1:d=h.getInt32(i.value+o.offset,!0);break;case 2:d=h.getUint32(i.value+o.offset,!0);break;case 3:d=h.getFloat64(i.value+o.offset,!0);break;case 4:d=h.getUint8(i.value+o.offset);break;case 5:d=Qt(h.getUint16(i.value+o.offset,!0));break;default:continue}switch(o.value){case 12:{const e=s[p];Xl(d,n),l[0]=Ll.Lerp(e.min.x,e.max.x,n.x),l[1]=Ll.Lerp(e.min.y,e.max.y,n.y),l[2]=Ll.Lerp(e.min.z,e.max.z,n.z)}break;case 13:Yl(d,r),f=r.x,g=r.y,m=r.z,T=r.w;break;case 14:{const e=s[p];Xl(d,n),c[0]=Math.exp(Ll.Lerp(e.minScale.x,e.maxScale.x,n.x)),c[1]=Math.exp(Ll.Lerp(e.minScale.y,e.maxScale.y,n.y)),c[2]=Math.exp(Ll.Lerp(e.minScale.z,e.maxScale.z,n.z))}break;case 15:{const e=s[p];Kl(d,u),u[0]=255*Ll.Lerp(e.minColor.x,e.maxColor.x,u[0]/255),u[1]=255*Ll.Lerp(e.minColor.y,e.maxColor.y,u[1]/255),u[2]=255*Ll.Lerp(e.minColor.z,e.maxColor.z,u[2]/255)}break;case 16:l[0]=d;break;case 17:l[1]=d;break;case 18:l[2]=d;break;case 19:c[0]=Math.exp(d);break;case 20:c[1]=Math.exp(d);break;case 21:c[2]=Math.exp(d);break;case 22:u[0]=d;break;case 23:u[1]=d;break;case 24:u[2]=d;break;case 26:u[0]=255*(.5+$l._SH_C0*d);break;case 27:u[1]=255*(.5+$l._SH_C0*d);break;case 28:u[2]=255*(.5+$l._SH_C0*d);break;case 29:u[3]=255*(.5+$l._SH_C0*d);break;case 25:u[3]=1/(1+Math.exp(-d))*255;break;case 30:f=d;break;case 31:g=d;break;case 32:m=d;break;case 33:T=d}if(_&&o.value>=40&&o.value<=111){const s=o.value-40;if(4==o.type&&e.chunkCount){const i=h.getUint8(e.rowChunkLength*e.chunkCount+e.vertexCount*e.rowVertexLength+t*e.shCoefficientCount+s);E[s]=127.5*(i*(8/255)-4)+127.5}else{const e=Ll.Clamp(127.5*d+127.5,0,255);E[s]=e}}}if(_){const t=1==e.shDegree?3:2==e.shDegree?8:3==e.shDegree?15:24;for(let e=0;e<t;e++)_[3*e+0]=E[e],_[3*e+1]=E[e+t],_[3*e+2]=E[e+2*t]}r.set(g,m,T,f),r.normalize(),d[0]=127.5*r.w+127.5,d[1]=127.5*r.x+127.5,d[2]=127.5*r.y+127.5,d[3]=127.5*r.z+127.5,i.value+=e.rowVertexLength}static*ConvertPLYWithSHToSplat(e,t=!1){const s=$l.ParseHeader(e);if(!s)return{buffer:e};const i={value:0},r=$l._GetCompressedChunks(s,i);for(let e=0;e<s.vertexCount;e++)$l._GetSplat(s,e,r,i),e%$l._PlyConversionBatchSize===0&&t&&(yield);let n=null;if(s.shDegree&&s.shBuffer){const e=Math.ceil(s.shCoefficientCount/16);let t=0;const i=new Uint8Array(s.shBuffer);n=[];const r=s.vertexCount,a=ee.LastCreatedEngine;if(a){const o=a.getCaps().maxTextureSize;n=Zl(e,Math.ceil(r/o)*o*4*4);for(let e=0;e<r;e++)for(let r=0;r<s.shCoefficientCount;r++){const s=i[t++];n[Math.floor(r/16)][r%16+16*e]=s}}}return{buffer:s.buffer,sh:n,shDegree:s.shDegree}}static*ConvertPLYToSplat(e,t=!1){const s=$l.ParseHeader(e);if(!s)return e;const i={value:0},r=$l._GetCompressedChunks(s,i);for(let e=0;e<s.vertexCount;e++)$l._GetSplat(s,e,r,i),e%$l._PlyConversionBatchSize===0&&t&&(yield);return s.buffer}static async ConvertPLYToSplatAsync(e){return await zs($l.ConvertPLYToSplat(e,!0),Gs())}static async ConvertPLYWithSHToSplatAsync(e){return await zs($l.ConvertPLYWithSHToSplat(e,!0),Gs())}async loadDataAsync(e){return await this.updateDataAsync(e)}async loadFileAsync(e,t){await _h(e,t||ee.LastCreatedScene,{pluginOptions:{splat:{gaussianSplattingMesh:this}}})}dispose(e){if(this._mrtAtlas?(this._mrtAtlas.dispose(),this._mrtAtlas=null,this._covariancesATexture=this._covariancesBTexture=this._centersTexture=this._colorsTexture=null):(this._covariancesATexture?.dispose(),this._covariancesBTexture?.dispose(),this._centersTexture?.dispose(),this._colorsTexture?.dispose()),this._shMrtAtlas){for(const e of this._shMrtAtlas)e.dispose();if(this._shTextures)for(let e=this._shMrtAtlas.length;e<this._shTextures.length;e++)this._shTextures[e].dispose();this._shMrtAtlas=null}else if(this._shTextures)for(const e of this._shTextures)e.dispose();this._shTextures=null,this._rotMrtAtlas?(this._rotMrtAtlas.dispose(),this._rotMrtAtlas=null):(this._rotationsATexture?.dispose(),this._rotationsBTexture?.dispose(),this._rotationScaleTexture?.dispose()),this._sogParams?.codebookTexture?.dispose(),this._rotationsATexture=null,this._rotationsBTexture=null,this._rotationScaleTexture=null,this._rotationDataA=null,this._rotationDataB=null,this._rotationScaleData=null,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._shTextures=null,this._cachedBoundingMin=null,this._cachedBoundingMax=null,function(e){const t=e.customAnimationFrameRequester;t?._gsInterFrameYield&&(t._refCount--,0===t._refCount&&(e.customAnimationFrameRequester=null))}(this.getEngine()),this._worker?.terminate(),this._worker=null,this.onPartCountChangedObservable.clear(),this.onPartRemovedObservable.clear(),this._cameraViewInfos.forEach(e=>{e.mesh.dispose()}),super.dispose(e,!0)}_copyTextures(e){if(this._covariancesATexture=e.covariancesATexture?.clone(),this._covariancesBTexture=e.covariancesBTexture?.clone(),this._centersTexture=e.centersTexture?.clone(),this._colorsTexture=e.colorsTexture?.clone(),e._shTextures){this._shTextures=[];for(const t of e._shTextures)this._shTextures?.push(t.clone())}e._rotationsATexture&&(this._rotationsATexture=e._rotationsATexture.clone(),this._rotationsBTexture=e._rotationsBTexture?.clone(),this._rotationScaleTexture=e._rotationScaleTexture?.clone())}clone(e=""){const t=new $l(e,void 0,this.getScene());t._copySource(this),t.makeGeometryUnique(),t._vertexCount=this._vertexCount,t._copyTextures(this),t._modelViewProjectionMatrix=Ie.Identity(),t._splatPositions=this._splatPositions,t._readyToDisplay=!1,t._hasRenderedOnce=!1,t._disableDepthSort=this._disableDepthSort,t._instantiateWorker();const s=this.getBoundingInfo();return t.getBoundingInfo().reConstruct(s.minimum,s.maximum,this.getWorldMatrix()),t.forcedInstanceCount=this.forcedInstanceCount,t.setEnabled(!0),t}_makeEmptySplat(e,t,s,i){const r=this._useRGBACovariants?4:2;this._splatPositions[4*e+0]=0,this._splatPositions[4*e+1]=0,this._splatPositions[4*e+2]=0,t[4*e+0]=Zt(0),t[4*e+1]=Zt(0),t[4*e+2]=Zt(0),t[4*e+3]=Zt(0),s[e*r+0]=Zt(0),s[e*r+1]=Zt(0),i[4*e+3]=0}_makeSplat(e,t,s,i,r,n,a,o,h,l=e,c=e){const u=Ce.Matrix[0],d=Ce.Matrix[1],_=Ce.Quaternion[0],p=this._useRGBACovariants?4:2,f=t[8*l+0],g=t[8*l+1]*(h?-1:1),m=t[8*l+2];if(this._splatPositions[4*e+0]=f,this._splatPositions[4*e+1]=g,this._splatPositions[4*e+2]=m,a.minimizeInPlaceFromFloats(f,g,m),o.maximizeInPlaceFromFloats(f,g,m),_.set((s[32*l+28+1]-127.5)/127.5,(s[32*l+28+2]-127.5)/127.5,(s[32*l+28+3]-127.5)/127.5,-(s[32*l+28+0]-127.5)/127.5),_.normalize(),_.toRotationMatrix(u),Ie.ScalingToRef(2*t[8*l+3+0],2*t[8*l+3+1],2*t[8*l+3+2],d),this._needsRotationScaleTextures){const t=this._splatPositions.length;(!this._rotationDataA||this._rotationDataA.length<t)&&(this._rotationDataA=new Uint16Array(t),this._rotationDataB=new Uint16Array(t),this._rotationScaleData=new Uint16Array(t));const s=this._rotationDataA,i=this._rotationDataB,r=this._rotationScaleData,n=u.m,a=d.m;s[4*e+0]=Zt(n[0]),s[4*e+1]=Zt(n[1]),s[4*e+2]=Zt(n[2]),s[4*e+3]=Zt(n[4]),i[4*e+0]=Zt(n[5]),i[4*e+1]=Zt(n[6]),i[4*e+2]=Zt(n[8]),i[4*e+3]=Zt(n[9]),r[4*e+0]=Zt(n[10]),r[4*e+1]=Zt(a[0]),r[4*e+2]=Zt(a[5]),r[4*e+3]=Zt(a[10])}const T=u.multiplyToRef(d,Ce.Matrix[0]).m,E=this._tmpCovariances;E[0]=T[0]*T[0]+T[1]*T[1]+T[2]*T[2],E[1]=T[0]*T[4]+T[1]*T[5]+T[2]*T[6],E[2]=T[0]*T[8]+T[1]*T[9]+T[2]*T[10],E[3]=T[4]*T[4]+T[5]*T[5]+T[6]*T[6],E[4]=T[4]*T[8]+T[5]*T[9]+T[6]*T[10],E[5]=T[8]*T[8]+T[9]*T[9]+T[10]*T[10];let R=-1e4;for(let e=0;e<6;e++)R=Math.max(R,Math.abs(E[e]));this._splatPositions[4*e+3]=R;const b=R;i[4*c+0]=Zt(E[0]/b),i[4*c+1]=Zt(E[1]/b),i[4*c+2]=Zt(E[2]/b),i[4*c+3]=Zt(E[3]/b),r[c*p+0]=Zt(E[4]/b),r[c*p+1]=Zt(E[5]/b);const A=E[0],y=E[1],M=E[2],x=E[3],S=E[4],v=E[5],I=A*(x*v-S*S)-y*(y*v-S*M)+M*(y*S-x*M),P=Math.pow(Math.abs(I),1/6);P<this._splatSizeMin&&(this._splatSizeMin=P),P>this._splatSizeMax&&(this._splatSizeMax=P),n[4*c+0]=s[32*l+24+0],n[4*c+1]=s[32*l+24+1],n[4*c+2]=s[32*l+24+2],n[4*c+3]=s[32*l+24+3]}_onUpdateTextures(e){}_onIndexDataReceived(e,t){}_onIncrementalUpdateStart(e){}get isCompound(){return!1}_setDelayedTextureUpdate(e,t,s,i){this._delayedTextureUpdate={covA:e,covB:t,colors:s,centers:this._splatPositions,sh:i}}_createMrtAtlas(e){this._useRGBACovariants=!0;const t=this.getEngine(),s=this._getTextureDataUpdateEngine();if(!s._gl&&!s.isWebGPU)return;const i=t.getCaps().textureHalfFloatRender?dt.TEXTURETYPE_HALF_FLOAT:dt.TEXTURETYPE_FLOAT,r=new yl(this.name+"_gsAtlas",{width:e.x,height:e.y},4,this._scene,{types:[dt.TEXTURETYPE_FLOAT,i,i,dt.TEXTURETYPE_UNSIGNED_BYTE],formats:[dt.TEXTUREFORMAT_RGBA,dt.TEXTUREFORMAT_RGBA,dt.TEXTUREFORMAT_RGBA,dt.TEXTUREFORMAT_RGBA],samplingModes:[dt.TEXTURE_NEAREST_SAMPLINGMODE,dt.TEXTURE_NEAREST_SAMPLINGMODE,dt.TEXTURE_NEAREST_SAMPLINGMODE,dt.TEXTURE_NEAREST_SAMPLINGMODE],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[this.name+"_gsCenters",this.name+"_gsCovA",this.name+"_gsCovB",this.name+"_gsColors"]);r.clearColor=new Ke(0,0,0,0),r.renderList=[],r.onClearObservable.add(()=>{}),r.render(),this._mrtAtlas=r,this._centersTexture=r.textures[0],this._covariancesATexture=r.textures[1],this._covariancesBTexture=r.textures[2],this._colorsTexture=r.textures[3]}_createShMrtAtlas(e){const t=this._getTextureDataUpdateEngine();if(!t._gl&&!t.isWebGPU)return;const s=this._shMrtAtlasTextureCount;if(s<=0)return;const i=[],r=[];for(let t=0;t<s;t++){const s=`${this.name}_gsShAtlas${t}`,n=new yl(s,{width:e.x,height:e.y},1,this._scene,{types:[dt.TEXTURETYPE_UNSIGNED_INTEGER],formats:[dt.TEXTUREFORMAT_RGBA_INTEGER],samplingModes:[dt.TEXTURE_NEAREST_SAMPLINGMODE],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[s]);n.clearColor=new Ke(0,0,0,0),n.renderList=[],n.onClearObservable.add(()=>{});const a=n.textures[0];a.wrapU=dt.TEXTURE_CLAMP_ADDRESSMODE,a.wrapV=dt.TEXTURE_CLAMP_ADDRESSMODE,n.render(),i.push(n),r.push(a)}this._shMrtAtlas=i,this._shTextures=r}_createRotMrtAtlas(e){const t=this._getTextureDataUpdateEngine();if(!t._gl&&!t.isWebGPU)return;const s=this.getEngine().getCaps().textureHalfFloatRender?dt.TEXTURETYPE_HALF_FLOAT:dt.TEXTURETYPE_FLOAT,i=this.name+"_gsRotAtlas",r=new yl(i,{width:e.x,height:e.y},3,this._scene,{types:[s,s,s],formats:[dt.TEXTUREFORMAT_RGBA,dt.TEXTUREFORMAT_RGBA,dt.TEXTUREFORMAT_RGBA],samplingModes:[dt.TEXTURE_NEAREST_SAMPLINGMODE,dt.TEXTURE_NEAREST_SAMPLINGMODE,dt.TEXTURE_NEAREST_SAMPLINGMODE],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[i+"A",i+"B",i+"Scale"]);r.clearColor=new Ke(0,0,0,0),r.renderList=[],r.onClearObservable.add(()=>{});for(const e of r.textures)e.wrapU=dt.TEXTURE_CLAMP_ADDRESSMODE,e.wrapV=dt.TEXTURE_CLAMP_ADDRESSMODE;r.render(),this._rotMrtAtlas=r,this._rotationsATexture=r.textures[0],this._rotationsBTexture=r.textures[1],this._rotationScaleTexture=r.textures[2]}_updateTextures(e,t,s,i){const r=this._getTextureSize(this._vertexCount),n=(e,t,s,i)=>new pl(e,t,s,i,this._scene,!1,!1,dt.TEXTURE_BILINEAR_SAMPLINGMODE,dt.TEXTURETYPE_FLOAT),a=(e,t,s,i)=>new pl(e,t,s,i,this._scene,!1,!1,dt.TEXTURE_BILINEAR_SAMPLINGMODE,dt.TEXTURETYPE_UNSIGNED_BYTE),o=(e,t,s)=>new pl(null,e,t,s,this._scene,!1,!1,dt.TEXTURE_NEAREST_SAMPLINGMODE,dt.TEXTURETYPE_UNSIGNED_INTEGER),h=(e,t,s,i)=>new pl(e,t,s,i,this._scene,!1,!1,dt.TEXTURE_BILINEAR_SAMPLINGMODE,dt.TEXTURETYPE_HALF_FLOAT),l=null===this._covariancesATexture,c=this._textureSize.y!=r.y;this._useShMrtAtlas&&i&&(this._shMrtAtlasTextureCount=i.length);const u=this._useMrtAtlas&&!this._mrtAtlas||this._useShMrtAtlas&&(!this._shMrtAtlas||this._shMrtAtlas.length!==this._shMrtAtlasTextureCount)||this._useRotMrtAtlas&&!this._rotMrtAtlas;if(l||c||u){const c=this._useMrtAtlas&&!!this._mrtAtlas;if(c&&this._onBeforeAtlasRebuildObservable.notifyObservers(this._mrtAtlas),this._mrtAtlas?(this._mrtAtlas.dispose(),this._mrtAtlas=null,this._covariancesATexture=this._covariancesBTexture=this._centersTexture=this._colorsTexture=null):(this._covariancesATexture?.dispose(),this._covariancesBTexture?.dispose(),this._centersTexture?.dispose(),this._colorsTexture?.dispose()),this._rotMrtAtlas?(this._rotMrtAtlas.dispose(),this._rotMrtAtlas=null,this._rotationsATexture=null,this._rotationsBTexture=null,this._rotationScaleTexture=null):this._rotationsATexture&&(this._rotationsATexture.dispose(),this._rotationsBTexture?.dispose(),this._rotationScaleTexture?.dispose(),this._rotationsATexture=null,this._rotationsBTexture=null,this._rotationScaleTexture=null),this._shTextures){if(this._shMrtAtlas){for(const e of this._shMrtAtlas)e.dispose();for(let e=this._shMrtAtlas.length;e<this._shTextures.length;e++)this._shTextures[e].dispose();this._shMrtAtlas=null}else for(const e of this._shTextures)e.dispose();this._shTextures=null}if(this._textureSize=r,this._useMrtAtlas){if(this._createMrtAtlas(r),this._useShMrtAtlas&&this._createShMrtAtlas(r),this._useRotMrtAtlas&&this._createRotMrtAtlas(r),this._mrtAtlas){if(this._updateSubTextures(this._splatPositions,e,t,s,0,r.y),this._useShMrtAtlas&&i){const e=this._shTextures;if(e)for(let t=0;t<i.length&&t<e.length;t++)this._updateShTextureData(e[t],i[t],r.x,0,r.y)}c&&this._onAfterAtlasRebuildObservable.notifyObservers(this._mrtAtlas)}}else this._covariancesATexture=h(e,r.x,r.y,dt.TEXTUREFORMAT_RGBA),this._covariancesBTexture=h(t,r.x,r.y,this._useRGBACovariants?dt.TEXTUREFORMAT_RGBA:dt.TEXTUREFORMAT_RG),this._centersTexture=n(this._splatPositions,r.x,r.y,dt.TEXTUREFORMAT_RGBA),this._colorsTexture=a(s,r.x,r.y,dt.TEXTUREFORMAT_RGBA);if(i&&!this._useShMrtAtlas){this._shTextures=[];for(let e=0;e<i.length;e++){const e=o(r.x,r.y,dt.TEXTUREFORMAT_RGBA_INTEGER);e.wrapU=dt.TEXTURE_CLAMP_ADDRESSMODE,e.wrapV=dt.TEXTURE_CLAMP_ADDRESSMODE,this._shTextures.push(e)}for(let e=0;e<i.length;e++)this._updateShTextureData(this._shTextures[e],i[e],r.x,0,r.y)}if(this._needsRotationScaleTextures&&!this._useRotMrtAtlas){const t=this._rotationDataA??new Uint16Array(e.length),s=this._rotationDataB??new Uint16Array(e.length),i=this._rotationScaleData??new Uint16Array(e.length);this._rotationsATexture=h(t,r.x,r.y,dt.TEXTUREFORMAT_RGBA),this._rotationsBTexture=h(s,r.x,r.y,dt.TEXTUREFORMAT_RGBA),this._rotationScaleTexture=h(i,r.x,r.y,dt.TEXTUREFORMAT_RGBA),this._rotationsATexture.wrapU=dt.TEXTURE_CLAMP_ADDRESSMODE,this._rotationsATexture.wrapV=dt.TEXTURE_CLAMP_ADDRESSMODE,this._rotationsBTexture.wrapU=dt.TEXTURE_CLAMP_ADDRESSMODE,this._rotationsBTexture.wrapV=dt.TEXTURE_CLAMP_ADDRESSMODE,this._rotationScaleTexture.wrapU=dt.TEXTURE_CLAMP_ADDRESSMODE,this._rotationScaleTexture.wrapV=dt.TEXTURE_CLAMP_ADDRESSMODE}if(this._onUpdateTextures(r),l)this._instantiateWorker();else{if(this._worker){const e=Float32Array.from(this._splatPositions),t=this._vertexCount;this._worker.postMessage({command:Fl,positions:e,vertexCount:t},[e.buffer]),this._postIntervalsToWorker()}this._postToWorker(!0)}}else{this._setDelayedTextureUpdate(e,t,s,i);const n=Float32Array.from(this._splatPositions),a=this._vertexCount;if(this._worker&&(this._worker.postMessage({command:Fl,positions:n,vertexCount:a},[n.buffer]),this._postIntervalsToWorker()),i&&!this._shTextures&&!this._useShMrtAtlas){this._shTextures=[];for(let e=0;e<i.length;e++){const t=o(r.x,r.y,dt.TEXTUREFORMAT_RGBA_INTEGER);t.wrapU=dt.TEXTURE_CLAMP_ADDRESSMODE,t.wrapV=dt.TEXTURE_CLAMP_ADDRESSMODE,this._shTextures.push(t),this._updateShTextureData(t,i[e],r.x,0,r.y)}}this._needsRotationScaleTextures&&this._rotationDataA&&(this._rotationsATexture?(this._updateTextureFromData(this._rotationsATexture,this._rotationDataA,r.x,0,r.y),this._updateTextureFromData(this._rotationsBTexture,this._rotationDataB,r.x,0,r.y),this._updateTextureFromData(this._rotationScaleTexture,this._rotationScaleData,r.x,0,r.y)):(this._rotationsATexture=h(this._rotationDataA,r.x,r.y,dt.TEXTUREFORMAT_RGBA),this._rotationsBTexture=h(this._rotationDataB,r.x,r.y,dt.TEXTUREFORMAT_RGBA),this._rotationScaleTexture=h(this._rotationScaleData,r.x,r.y,dt.TEXTUREFORMAT_RGBA),this._rotationsATexture.wrapU=dt.TEXTURE_CLAMP_ADDRESSMODE,this._rotationsATexture.wrapV=dt.TEXTURE_CLAMP_ADDRESSMODE,this._rotationsBTexture.wrapU=dt.TEXTURE_CLAMP_ADDRESSMODE,this._rotationsBTexture.wrapV=dt.TEXTURE_CLAMP_ADDRESSMODE,this._rotationScaleTexture.wrapU=dt.TEXTURE_CLAMP_ADDRESSMODE,this._rotationScaleTexture.wrapV=dt.TEXTURE_CLAMP_ADDRESSMODE)),this._onUpdateTextures(r),this._postToWorker(!0)}}_canReuseCachedData(e,t,s=0){if(e<=0||e>t)return!1;if(null===this._splatPositions||null===this._cachedBoundingMin||null===this._cachedBoundingMax)return!1;if(null===this._covariancesATexture)return!1;if(this._useMrtAtlas&&!this._mrtAtlas)return!1;if(this._useShMrtAtlas&&(!this._shMrtAtlas||this._shMrtAtlas.length!==s))return!1;if(this._useRotMrtAtlas&&!this._rotMrtAtlas)return!1;return this._getTextureSize(t).y===this._textureSize.y}_notifyWorkerNewData(){if(this._worker){const e=Float32Array.from(this._splatPositions),t=this._vertexCount;this._worker.postMessage({command:Fl,positions:e,vertexCount:t},[e.buffer]),this._postIntervalsToWorker()}this._sortIsDirty=!0}_postWorkerPositionsRange(e,t){if(!this._worker||!this._splatPositions||t<=0)return;const s=4*e,i=this._splatPositions.slice(s,s+4*t);this._worker.postMessage({command:Nl,offset:s,data:i},[i.buffer]),this._sortIsDirty=!0}_writeStreamingSplats(e,t,s,i,r){if(!this._splatPositions)return;const n=this._splatPositions.length/4,a=$l._GetSplatDataBytes(s);if(!Number.isInteger(e)||!Number.isInteger(t)||e<0||t<0||e+t>n)throw new Error(`_writeStreamingSplats: range [${e}, ${e+t}) is outside the atlas bounds [0, ${n})`);if(a.length<32*t)throw new Error(`_writeStreamingSplats: splatsData has ${a.length} bytes, need ${32*t} for ${t} splats (stride 32)`);if(0===t||!this._covariancesATexture)return;const o=this._getTextureSize(this._vertexCount).x,h=this._useRGBACovariants?4:2,l=e+t,c=$l._GetSplatDataFloats(s),u=new Uint16Array(4*t),d=new Uint16Array(t*h),_=new Uint8Array(4*t),p=i??new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),f=r??new xe(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let s=0;s<t;s++)this._makeSplat(e+s,c,a,u,d,_,p,f,this._flipY,s,s);if(this._splatsData){new Uint8Array($l._GetSplatDataBytes(this._splatsData).buffer).set(a.subarray(0,32*t),32*e)}const g=this._splatPositions;let m=e;for(;m<l;){const t=Math.floor(m/o),s=Math.min(l,(t+1)*o),i=m-t*o,r=s-m,n=m-e;this._updateTextureFromDataRect(this._covariancesATexture,new Uint16Array(u.buffer,4*n*2,4*r),i,t,r,1),this._updateTextureFromDataRect(this._covariancesBTexture,new Uint16Array(d.buffer,n*h*2,r*h),i,t,r,1),this._updateTextureFromDataRect(this._centersTexture,new Float32Array(g.buffer,4*m*4,4*r),i,t,r,1),this._updateTextureFromDataRect(this._colorsTexture,new Uint8Array(_.buffer,4*n,4*r),i,t,r,1),m=s}this._postWorkerPositionsRange(e,t)}*_updateData(e,t,s,i,{flipY:r=!1,previousVertexCount:n=0}={},a){this._covariancesATexture||(this._readyToDisplay=!1),this._flipY=r;const o=new Uint8Array(e),h=new Float32Array(o.buffer);this._keepInRam||this._alwaysRetainSplatsData?(this._splatsData=o.buffer,this._shData=s?s.map(e=>new Uint8Array(e)):null):(this._splatsData=null,this._shData=null);const l=o.length/$l._RowOutputLength;l!=this._vertexCount&&(this._activeSplatRanges=null,this._activeSplatRangeKey="",this._activeSplatRenderCount=0,this._updateSplatIndexBuffer(l)),this._vertexCount=l,this._maxShDegree=s?a??0:0,this._shDegree=this._maxShDegree;const c=this._getTextureSize(l),u=c.x*c.y,d=$l.ProgressiveUpdateAmount??c.y;i&&this._onIndexDataReceived(i,u);const _=new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),p=new xe(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),f=this._useRGBACovariants?4:2,g=new Uint16Array(4*u),m=new Uint16Array(f*u),T=new Uint8Array(4*u),E=this._canReuseCachedData(n,l,s?.length??0);E||(this._splatSizeMin=1/0,this._splatSizeMax=-1/0);const R=E?Math.floor(n/c.x):0,b=R*c.x,A=this._splatPositions;if(this._splatPositions=new Float32Array(4*u),E&&(this._splatPositions.set(A.subarray(0,4*n)),_.copyFrom(this._cachedBoundingMin),p.copyFrom(this._cachedBoundingMax),this._onIncrementalUpdateStart(c)),$l.ProgressiveUpdateAmount){E||this._updateTextures(g,m,T,s),this.setEnabled(!0);const e=Math.ceil(c.y/d);for(let i=0;i<e;i++){const e=i*d,n=Math.min(e+d,c.y);if(n<=R)continue;const a=Math.max(e,R),u=a*c.x,f=n*c.x;for(let e=u;e<f;e++)e<l?this._makeSplat(e,h,o,g,m,T,_,p,r):this._makeEmptySplat(e,g,m,T);this._updateSubTextures(this._splatPositions,g,m,T,a,n-a,s),this.getBoundingInfo().reConstruct(_,p,this.getWorldMatrix()),t&&(yield)}this._notifyWorkerNewData()}else{for(let e=b;e<l;e++)this._makeSplat(e,h,o,g,m,T,_,p,r),t&&e%$l._SplatBatchSize===0&&(yield);const e=E?u:l+15&-16;for(let t=l;t<e;t++)this._makeEmptySplat(t,g,m,T);E?(this._updateSubTextures(this._splatPositions,g,m,T,R,c.y-R,s),this.getBoundingInfo().reConstruct(_,p,this.getWorldMatrix()),this.setEnabled(!0),this._notifyWorkerNewData()):(this._updateTextures(g,m,T,s),this.getBoundingInfo().reConstruct(_,p,this.getWorldMatrix()),this.setEnabled(!0),this._sortIsDirty=!0)}this._cachedBoundingMin=_.clone(),this._cachedBoundingMax=p.clone(),this._postToWorker(!0)}async updateDataAsync(e,t,s,i){return await zs(this._updateData(e,!0,t,s,void 0,i),Gs())}updateData(e,t,s={flipY:!0},i,r){Hs(this._updateData(e,!1,t,i,s,r))}refreshBoundingInfo(){return this.thinInstanceRefreshBoundingInfo(!1),this}_updateSplatIndexBuffer(e){const t=this._activeSplatRanges?this._activeSplatRenderCount:e,s=Math.max(t+15&-16,16),i=this._splatIndex;i&&s===i.length||(this._splatIndex=new Float32Array(s),this._cameraViewInfos.forEach(e=>{e.mesh.thinInstanceSetBuffer("splatIndex",this._splatIndex,16,!1)}));const r=this._splatIndex;if(this._activeSplatRanges){let t=0;for(let e=0;e<this._activeSplatRanges.length;e+=2){const s=this._activeSplatRanges[e],i=this._activeSplatRanges[e+1];for(let e=s;e<s+i;e++)r[t++]=e}for(;t<s;t++)r[t]=e}else for(let e=0;e<s;e++)r[e]=e;this._depthMix&&s===this._depthMix.length||Hl||(this._depthMix=new BigInt64Array(s)),this.forcedInstanceCount=Math.max(s>>4,1)}_getTextureDataUpdateEngine(){return this.getEngine()}_updateShTextureData(e,t,s,i,r){const n=this._getTextureDataUpdateEngine();if(!n._gl&&!n.isWebGPU){const i=e.getInternalTexture(),r=s*i.height*16;let a;if(t.byteLength===r&&t.byteOffset%Uint32Array.BYTES_PER_ELEMENT===0)a=new Uint32Array(t.buffer,t.byteOffset,t.byteLength/Uint32Array.BYTES_PER_ELEMENT);else{const e=new Uint8Array(r);e.set(t.subarray(0,Math.min(t.byteLength,r))),a=new Uint32Array(e.buffer)}return void n.updateRawTexture(i,a,i.format,i.invertY,null,i.type,i._useSRGBBuffer)}const a=i*s,o=Math.floor(t.byteLength/16);if(a>=o)return;let h=Math.min(r*s,o-a);if(h<=0)return;const l=(e,s)=>new Uint32Array(t.buffer,t.byteOffset+e,4*s),c=Math.floor(h/s);if(c>0){const t=c*s;this._updateTextureFromData(e,l(16*a,t),s,i,c),h-=t}if(h>0){const t=16*(a+c*s);this._updateTextureFromDataRect(e,l(t,h),0,i+c,h,1)}}_updateSubTextures(e,t,s,i,r,n,a){const o=this._getTextureSize(this._vertexCount),h=this._useRGBACovariants?4:2,l=r*o.x,c=n*o.x,u=new Uint16Array(t.buffer,4*l*Uint16Array.BYTES_PER_ELEMENT,4*c),d=new Uint16Array(s.buffer,l*h*Uint16Array.BYTES_PER_ELEMENT,c*h),_=new Uint8Array(i.buffer,4*l,4*c),p=new Float32Array(e.buffer,4*l*Float32Array.BYTES_PER_ELEMENT,4*c);if(this._updateTextureFromData(this._covariancesATexture,u,o.x,r,n),this._updateTextureFromData(this._covariancesBTexture,d,o.x,r,n),this._updateTextureFromData(this._centersTexture,p,o.x,r,n),this._updateTextureFromData(this._colorsTexture,_,o.x,r,n),this._rotationsATexture&&this._rotationDataA){const e=new Uint16Array(this._rotationDataA.buffer,4*l*Uint16Array.BYTES_PER_ELEMENT,4*c),t=new Uint16Array(this._rotationDataB.buffer,4*l*Uint16Array.BYTES_PER_ELEMENT,4*c),s=new Uint16Array(this._rotationScaleData.buffer,4*l*Uint16Array.BYTES_PER_ELEMENT,4*c);this._updateTextureFromData(this._rotationsATexture,e,o.x,r,n),this._updateTextureFromData(this._rotationsBTexture,t,o.x,r,n),this._updateTextureFromData(this._rotationScaleTexture,s,o.x,r,n)}if(a)for(let e=0;e<a.length;e++)this._updateShTextureData(this._shTextures[e],a[e],o.x,r,n)}_instantiateWorker(){if(!this._vertexCount)return;if(this._updateSplatIndexBuffer(this._vertexCount),this._disableDepthSort)return;if(Hl)return;this._worker?.terminate(),this._canPostToWorker=!0,this._worker=new Worker(URL.createObjectURL(new Blob(["(",Vl.toString(),")(self)"],{type:"application/javascript"})));const e=Float32Array.from(this._splatPositions),t=this._vertexCount;this._worker.postMessage({command:Fl,positions:e,vertexCount:t},[e.buffer]),this._postIntervalsToWorker(),this._onWorkerCreated(this._worker),this._worker.onerror=()=>{this._canPostToWorker=!0},this._worker.onmessage=e=>{const t=Math.max(this.renderedSplatCount+15&-16,16);if(e.data.depthMix.length!=t||e.data.rangeVersion!==this._activeRangeVersion)return void(this._depthMix.buffer.byteLength>0&&(this._canPostToWorker=!0,this._postToWorker(!0),this._sortIsDirty=!1));this._depthMix=e.data.depthMix;const s=e.data.cameraId,i=e.data.sortRequestId;this._splatIndex&&this._splatIndex.length===t||(this._splatIndex=new Float32Array(t),this._cameraViewInfos.forEach(e=>{e.mesh.thinInstanceSetBuffer("splatIndex",this._splatIndex,16,!1),e.splatIndexBufferSet=!0}));const r=new Uint32Array(e.data.depthMix.buffer);if(this._splatIndex)for(let e=0;e<t;e++)this._splatIndex[e]=r[2*e];if(this.forcedInstanceCount=Math.max(t>>4,1),this._delayedTextureUpdate){const e=this._vertexCount+15&-16,t=this._getTextureSize(e);this._updateSubTextures(this._delayedTextureUpdate.centers,this._delayedTextureUpdate.covA,this._delayedTextureUpdate.covB,this._delayedTextureUpdate.colors,0,t.y,this._delayedTextureUpdate.sh),this._delayedTextureUpdate=null}const n=this._cameraViewInfos.get(s);n&&(n.splatIndexBufferSet?n.mesh.thinInstanceBufferUpdated("splatIndex"):(n.mesh.thinInstanceSetBuffer("splatIndex",this._splatIndex,16,!1),n.splatIndexBufferSet=!0),n.sortAppliedId=i),this._canPostToWorker=!0,this._readyToDisplay=!0,this._sortIsDirty&&(this._postToWorker(!0),this._sortIsDirty=!1)}}_getTextureSize(e){const t=this._scene.getEngine(),s=t.getCaps().maxTextureSize;let i=1;if(1!==t.version||t.isWebGPU)i=Math.ceil(e/s),e>0&&i*s===e&&(i+=1);else{for(;s*i<e;)i*=2;e>0&&s*i===e&&(i*=2)}return i>s&&(a.Error("GaussianSplatting texture size: ("+s+", "+i+"), maxTextureSize: "+s),i=s),new Me(s,i)}_onWorkerCreated(e){}bindExtraEffectUniforms(e){}_appendSourceToArrays(e,t,s,i,r,n,a,o){const h=e._vertexCount,l=e._splatsData;if(!l||0===h)return;const c=$l._GetSplatDataBytes(l),u=$l._GetSplatDataFloats(l);for(let e=0;e<h;e++)this._makeSplat(t+e,u,c,s,i,r,a,o,!1,e);if(n&&e._shData)for(let s=0;s<n.length;s++)s<e._shData.length&&n[s].set(e._shData[s].subarray(0,16*h),16*t)}bakeTransformIntoVertices(e){const t=this.splatsData;if(!t)return a.Error("Cannot bake transform into vertices if splatsData is not kept in RAM"),this;const s=e.m,i=Math.sqrt(s[0]*s[0]+s[1]*s[1]+s[2]*s[2]),r=Math.sqrt(s[4]*s[4]+s[5]*s[5]+s[6]*s[6]),n=Math.sqrt(s[8]*s[8]+s[9]*s[9]+s[10]*s[10]);if(Math.abs(i-r)>.001||Math.abs(i-n)>.001)return a.Error("Gaussian Splatting bakeTransformIntoVertices does not support non-uniform scaling"),this;const o=new Uint8Array(t),h=new Float32Array(t),l=Ce.Vector3[0];let c;const u=Ce.Quaternion[0],d=Ce.Quaternion[1];for(e.decompose(l,d,l),c=0;c<this._vertexCount;c++){const t=8*c;xe.TransformCoordinatesFromFloatsToRef(h[t],h[t+1],h[t+2],e,l),h[t]=l.x,h[t+1]=l.y,h[t+2]=l.z,h[t+3]*=i,h[t+4]*=i,h[t+5]*=i,u.set((o[32*c+28+1]-127.5)/127.5,(o[32*c+28+2]-127.5)/127.5,(o[32*c+28+3]-127.5)/127.5,(o[32*c+28+0]-127.5)/127.5),u.normalize(),this.scaling.x<0&&(u.x=-u.x,u.w=-u.w),this.scaling.y<0&&(u.y=-u.y,u.w=-u.w),this.scaling.z<0&&(u.z=-u.z,u.w=-u.w),d.multiplyToRef(u,u),u.normalize(),o[32*c+28+0]=Math.round(127.5*u.w+127.5),o[32*c+28+1]=Math.round(127.5*u.x+127.5),o[32*c+28+2]=Math.round(127.5*u.y+127.5),o[32*c+28+3]=Math.round(127.5*u.z+127.5)}return this.updateData(t,this.shData??void 0,{flipY:!1}),this}}function Zl(e,t){const s=[];for(let i=0;i<e;i++){const e=new Uint8Array(t);e.fill(128),s.push(e)}return s}$l.UseCountingSort=!0,$l.LogSortPerformance=!1,$l._RowOutputLength=32,$l._SH_C0=.28209479177387814,$l._SplatBatchSize=327680,$l._PlyConversionBatchSize=32768,$l._BatchSize=16,$l._DefaultViewUpdateThreshold=1e-4,$l.ProgressiveUpdateAmount=0;class Ql extends Xn{get partIndex(){return this._partIndex}get proxiedMesh(){return this.compoundSplatMesh}constructor(e,t,s,i,r,n,a,o=a){super(e,t),this._partIndex=i,this._vertexCount=n,this._splatsDataOffset=a,this._shDataOffset=o,this._minimum=r.minimum.clone(),this._maximum=r.maximum.clone(),this.compoundSplatMesh=s,this._applyBoundingInfo(),this.compoundSplatMesh.setWorldMatrixForPart(this.partIndex,this.getWorldMatrix()),this.onAfterWorldMatrixUpdateObservable.add(()=>{this.compoundSplatMesh.setWorldMatrixForPart(this.partIndex,this.getWorldMatrix())})}updateBoundingInfoFromPartData(){this._applyBoundingInfo()}updateBoundingInfoFromProxiedMesh(){this.updateBoundingInfoFromPartData()}_applyBoundingInfo(){this.setBoundingInfo(new tr(this._minimum.clone(),this._maximum.clone()))}getClassName(){return"GaussianSplattingPartProxyMesh"}getHierarchyBoundingVectors(e=!0,t=null){const s=super.getHierarchyBoundingVectors(e,t),i=this.getBoundingInfo();return i.update(this.getWorldMatrix()),xe.CheckExtends(i.boundingBox.minimumWorld,s.min,s.max),xe.CheckExtends(i.boundingBox.maximumWorld,s.min,s.max),s}updatePartIndex(e){this._partIndex=e}updatePartMetadata(e,t,s=t){this._vertexCount=e,this._splatsDataOffset=t,this._shDataOffset=s}get isVisible(){return this.compoundSplatMesh.getPartVisibility(this.partIndex)>0}set isVisible(e){this.compoundSplatMesh.setPartVisibility(this.partIndex,e?1:0)}get visibility(){return this.compoundSplatMesh.getPartVisibility(this.partIndex)}set visibility(e){this.compoundSplatMesh.setPartVisibility(this.partIndex,e)}intersects(e){const t=new ur,s=this.getBoundingInfo();return s&&e.intersectsSphere(s.boundingSphere)&&e.intersectsBox(s.boundingBox)?(t.hit=!0,t.pickedMesh=this,t.distance=xe.Distance(e.origin,s.boundingSphere.center),t.subMeshId=0,t):t}serialize(e={}){(e=super.serialize(e)).subMeshes=[],e.geometryUniqueId=void 0,e.geometryId=void 0,e.materialUniqueId=void 0,e.materialId=void 0,e.instances=[],e.actions=void 0,e.type=this.getClassName(),e.compoundSplatMeshId=this.compoundSplatMesh.id,e.partIndex=this._partIndex,e.vertexCount=this._vertexCount,e.splatsDataOffset=this._splatsDataOffset,e.shDataOffset=this._shDataOffset;const t=this.getBoundingInfo();return e.boundingInfo={minimum:t.minimum.asArray(),maximum:t.maximum.asArray()},e}static Parse(e,t){const s=e.partIndex,i=e.compoundSplatMesh??t.getLastMeshById(e.compoundSplatMeshId);if(!i)throw new Error(`GaussianSplattingPartProxyMesh: compound mesh not found with ID ${e.compoundSplatMeshId}`);const r=xe.FromArray(e.boundingInfo.minimum),n=xe.FromArray(e.boundingInfo.maximum),a=new tr(r,n),o=e.vertexCount??0,h=e.splatsDataOffset??0,l=e.shDataOffset??h;return new Ql(e.name,t,i,s,a,o,h,l)}}let Jl=!1;function ec(){Jl||(Jl=!0,Xn._GaussianSplattingPartProxyMeshParser=Ql.Parse)}const tc=32,sc=16;class ic extends $l{get partIndicesTexture(){return this._partIndicesTexture}constructor(e,t=null,s=null,i=!1,r=!1){super(e,t,s,i),this._partProxies=[],this._part0LocalMin=null,this._part0LocalMax=null,this._partMatrices=[],this._rebuilding=!1,this._partVisibility=[],this._partSplatRanges=[],this._hasStreamingPart=!1,this._streamingStates=[],this._streamingShDegree=0,this._tombstonedPartIndices=new Set,this._partIndicesTexture=null,this._partIndices=null,this._alwaysRetainSplatsData=!0,this._needsRotationScaleTextures=r}getClassName(){return"GaussianSplattingMesh"}isReady(e=!1){for(const e of this._partProxies)e&&e.computeWorldMatrix(!0);return super.isReady(e)}_updateBoundingInfoFromProxies(){const e=this.getWorldMatrix(),t=Ie.Invert(e),s=this._part0LocalMin?this._part0LocalMin.clone():new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=this._part0LocalMax?this._part0LocalMax.clone():new xe(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),r=new xe;for(const e of this._partProxies){if(!e||this._tombstonedPartIndices.has(e.partIndex))continue;e.computeWorldMatrix(!1);const n=e.getBoundingInfo().boundingBox,a=n.minimumWorld,o=n.maximumWorld;for(let e=0;e<8;e++)r.set(1&e?o.x:a.x,2&e?o.y:a.y,4&e?o.z:a.z),xe.TransformCoordinatesToRef(r,t,r),s.minimizeInPlace(r),i.maximizeInPlace(r)}s.x<=i.x&&(this._boundingInfo?this._boundingInfo.reConstruct(s,i,e):this._boundingInfo=new tr(s,i,e),this._cachedBoundingMin=s.clone(),this._cachedBoundingMax=i.clone())}_updateBoundingInfo(){return this.isCompound?(this._updateBoundingInfoFromProxies(),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this):super._updateBoundingInfo()}getHierarchyBoundingVectors(e=!0,t=null){if(!this.isCompound)return super.getHierarchyBoundingVectors(e,t);const s=new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new xe(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(this._part0LocalMin&&(this._partVisibility[0]??1)>0){const e=this.getWorldMatrix(),t=this._part0LocalMin,r=this._part0LocalMax,n=new xe;for(let a=0;a<8;a++)n.set(1&a?r.x:t.x,2&a?r.y:t.y,4&a?r.z:t.z),xe.TransformCoordinatesToRef(n,e,n),s.minimizeInPlace(n),i.maximizeInPlace(n)}for(let e=0;e<this._partProxies.length;e++){const t=this._partProxies[e];if(!t||0===(this._partVisibility[e]??1))continue;t.computeWorldMatrix(!1);const r=t.getBoundingInfo().boundingBox;s.minimizeInPlace(r.minimumWorld),i.maximizeInPlace(r.maximumWorld)}return{min:s,max:i}}dispose(e){for(const e of this._partProxies)e.dispose();this._partIndicesTexture?.dispose(),this._partProxies=[],this._partMatrices=[],this._partVisibility=[],this._partIndicesTexture=null,this._part0LocalMin=null,this._part0LocalMax=null,super.dispose(e)}_onWorkerCreated(e){e.postMessage({command:Bl,partMatrices:this._partMatrices.map(e=>new Float32Array(e.m))}),e.postMessage({command:Ul,partIndices:this._partIndices?new Uint8Array(this._partIndices):null})}_onIndexDataReceived(e,t){this._partIndices=new Uint8Array(t),this._partIndices.set(e)}get isCompound(){return this._partMatrices.length>0}_instantiateWorker(){this._rebuilding&&this._worker?this._updateSplatIndexBuffer(this._vertexCount):super._instantiateWorker()}_onIncrementalUpdateStart(e){this._ensurePartIndicesTexture(e,this._partIndices??void 0)}_notifyWorkerNewData(){super._notifyWorkerNewData(),this._worker&&this._worker.postMessage({command:Ul,partIndices:this._partIndices??null})}bindExtraEffectUniforms(e){if(!this._partIndicesTexture)return;e.setTexture("partIndicesTexture",this._partIndicesTexture);const t=new Float32Array(16*this.partCount);for(let e=0;e<this.partCount;e++)this._partMatrices[e].toArray(t,16*e);e.setMatrices("partWorld",t);const s=[];for(let e=0;e<this.partCount;e++)s.push(this._partVisibility[e]??1);e.setArray("partVisibility",s)}get partCount(){return this._partMatrices.length}get partVisibility(){return this._partVisibility}setWorldMatrixForPart(e,t){if(this._partMatrices.length<=e){this.computeWorldMatrix(!0);const t=this.getWorldMatrix();for(;this._partMatrices.length<=e;)this._partMatrices.push(t.clone()),this._partVisibility.push(1)}this._partMatrices[e].equals(t)||(this._partMatrices[e].copyFrom(t),this._rebuilding||(this._worker&&this._worker.postMessage({command:Bl,partMatrices:this._partMatrices.map(e=>new Float32Array(e.m))}),this._postToWorker(!0)))}getWorldMatrixForPart(e){return this._partMatrices[e]??this.getWorldMatrix()}getPartVisibility(e){return this._partVisibility[e]??1}setPartVisibility(e,t){this._partVisibility[e]=Math.max(0,Math.min(1,t))}setPartSplatRanges(e,t){e<0||(this._partSplatRanges[e]=t?t.map(e=>({offset:e.offset,count:e.count})):null,this._refreshPartRangeUnion())}_refreshPartRangeUnion(){let e=!1;for(let t=0;t<this._partSplatRanges.length;t++)if(this._partSplatRanges[t]){e=!0;break}if(!e)return void this.setSplatIndexRanges(null);const t=[],s=this.partCount;for(let e=0;e<s;e++){const s=this._partSplatRanges[e];if(s){for(const e of s)e.count>0&&t.push({offset:e.offset,count:e.count});continue}const i=this._partProxies[e];i&&i._vertexCount>0&&t.push({offset:i._splatsDataOffset,count:i._vertexCount})}this.setSplatIndexRanges(ic._CoalesceSplatRanges(t))}static _CoalesceSplatRanges(e){if(e.length<=1)return e;const t=e.slice().sort((e,t)=>e.offset-t.offset),s=[{offset:t[0].offset,count:t[0].count}];for(let e=1;e<t.length;e++){const i=s[s.length-1],r=t[e],n=i.offset+i.count;if(r.offset<=n){const e=Math.max(n,r.offset+r.count);i.count=e-i.offset}else s.push({offset:r.offset,count:r.count})}return s}_copyTextures(e){super._copyTextures(e),this._partIndicesTexture=e._partIndicesTexture?.clone()}_onUpdateTextures(e){const t=(e,t,s,i)=>new pl(e,t,s,i,this._scene,!1,!1,dt.TEXTURE_BILINEAR_SAMPLINGMODE,dt.TEXTURETYPE_UNSIGNED_BYTE);if(this._partIndices){const s=new Uint8Array(this._partIndices);if(this._partIndicesTexture){const i=this._partIndicesTexture.getSize();i.width!==e.x||i.height!==e.y?(this._partIndicesTexture.dispose(),this._partIndicesTexture=t(s,e.x,e.y,dt.TEXTUREFORMAT_RED),this._partIndicesTexture.wrapU=dt.TEXTURE_CLAMP_ADDRESSMODE,this._partIndicesTexture.wrapV=dt.TEXTURE_CLAMP_ADDRESSMODE):this._updateTextureFromData(this._partIndicesTexture,s,e.x,0,e.y)}else this._partIndicesTexture=t(s,e.x,e.y,dt.TEXTUREFORMAT_RED),this._partIndicesTexture.wrapU=dt.TEXTURE_CLAMP_ADDRESSMODE,this._partIndicesTexture.wrapV=dt.TEXTURE_CLAMP_ADDRESSMODE}}_updateSubTextures(e,t,s,i,r,n,a,o){if(super._updateSubTextures(e,t,s,i,r,n,a),o&&this._partIndicesTexture){const e=this._getTextureSize(this._vertexCount),t=r*e.x,s=n*e.x,i=new Uint8Array(o.buffer,t,s);this._updateTextureFromData(this._partIndicesTexture,i,e.x,r,n),this._worker&&this._worker.postMessage({command:Ul,partIndices:o})}}_ensurePartIndicesTexture(e,t){if(!t||this._partIndicesTexture)return;const s=new Uint8Array(this._partIndices);this._partIndicesTexture=new pl(s,e.x,e.y,dt.TEXTUREFORMAT_RED,this._scene,!1,!1,dt.TEXTURE_BILINEAR_SAMPLINGMODE,dt.TEXTURETYPE_UNSIGNED_BYTE),this._partIndicesTexture.wrapU=dt.TEXTURE_CLAMP_ADDRESSMODE,this._partIndicesTexture.wrapV=dt.TEXTURE_CLAMP_ADDRESSMODE,this._worker&&this._worker.postMessage({command:Ul,partIndices:t??null})}_appendPartSourceToArrays(e,t,s,i,r,n,a,o){this._appendSourceToArrays(e,t,s,i,r,n,a,o)}_createRetainedPartSource(e){if(!this._splatsData||this._shDegree>0&&!this._shData)return null;const t=e._splatsDataOffset*tc,s=e._vertexCount*tc,i=e._shDataOffset*sc,r=e._vertexCount*sc,n=$l._GetSplatDataBytes(this._splatsData);return{name:e.name,_vertexCount:e._vertexCount,_splatsData:n.subarray(t,t+s),_shData:this._shData?.map(e=>e.subarray(i,i+r))??null,_shDegree:this._shData?this._shDegree:0,isCompound:!1,getWorldMatrix:()=>e.getWorldMatrix(),getBoundingInfo:()=>e.getBoundingInfo(),dispose:()=>{}}}_retainMergedPartData(e,t,s,i){if(!this._keepInRam&&!this._alwaysRetainSplatsData)return this._splatsData=null,void(this._shData=null);const r=new Uint8Array(t*tc);let n=0;this._splatsData&&e>0&&(r.set($l._GetSplatDataBytes(this._splatsData).subarray(0,e*tc),n),n+=e*tc);for(const e of s){if(!e._splatsData)continue;const t=e._vertexCount*tc;r.set($l._GetSplatDataBytes(e._splatsData).subarray(0,t),n),n+=t}if(this._splatsData=r.buffer,i<=0)return void(this._shData=null);const a=Zl(Math.ceil(3*((i+1)*(i+1)-1)/sc),t*sc);let o=0;if(this._shData&&e>0){const t=e*sc;for(let e=0;e<a.length;e++)e<this._shData.length&&a[e].set(this._shData[e].subarray(0,t),o);o+=t}for(const e of s){const t=e._vertexCount*sc;if(e._shData)for(let s=0;s<a.length;s++)s<e._shData.length&&a[s].set(e._shData[s].subarray(0,t),o);o+=t}this._shData=a}_addPartsInternal(e,t){if(0===e.length)return{proxyMeshes:[],assignedPartIndices:[]};for(const t of e){if(!t._splatsData&&!t._isReservedEmpty)throw new Error("To call addPart()/addParts(), each source mesh must be fully loaded");if(t.isCompound)throw new Error("To call addPart()/addParts(), each source mesh must not be a compound")}const s=this._vertexCount,i=e.reduce((e,t)=>e+t._vertexCount,0),r=s+i,n=this._getTextureSize(r),a=n.x*n.y,o=this._useRGBACovariants?4:2,h=new Uint16Array(4*a),l=new Uint16Array(o*a),c=new Uint8Array(4*a),u=this._streamingShDegree,d=this._shDegree>0||e.some(e=>null!==e._shData),_=d||u>0,p=_?Math.max(this._shDegree,u,...e.map(e=>e._shDegree)):0;let f;if(_&&p>0){f=Zl(Math.ceil(3*((p+1)*(p+1)-1)/sc),a*sc)}const g=this._canReuseCachedData(s,r,f?.length??0),m=g?Math.floor(s/n.x):0,T=g?this._cachedBoundingMin.clone():new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),E=g?this._cachedBoundingMax.clone():new xe(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),R=this._splatPositions;this._splatPositions=new Float32Array(4*a),g&&R&&this._splatPositions.set(R.subarray(0,4*s));let b=this.partCount,A=this._partIndices;A||(A=new Uint8Array(s),b=s>0?1:0),this._partIndices=new Uint8Array(a),this._partIndices.set(A.subarray(0,s));const y=[],M=[];let x=s;const S=ul(this._scene.getEngine());for(const t of e){if(b>=S)throw new Error(`Cannot add part, as the maximum part count (${S}) has been reached`);const e=b++;y.push(e),M.push(x),this._partIndices.fill(e,x,x+t._vertexCount),x+=t._vertexCount}if(!g&&s>0)if(this._partProxies.length>0){let e=0;if(!this._partProxies[0]&&this._splatsData){const t=s-this._partProxies.reduce((e,t)=>e+(t?t._vertexCount:0),0);if(t>0){const s=$l._GetSplatDataBytes(this._splatsData),i=$l._GetSplatDataFloats(this._splatsData);for(let e=0;e<t;e++)this._makeSplat(e,i,s,h,l,c,T,E,!1);if(f&&this._shData)for(let e=0;e<f.length;e++)e<this._shData.length&&f[e].set(this._shData[e].subarray(0,t*sc),0);e+=t}}for(let t=0;t<this._partProxies.length;t++){const s=this._partProxies[t];if(!s)continue;if(this._streamingStates.some(e=>e.proxy===s)){e+=s._vertexCount;continue}const i=this._createRetainedPartSource(s);if(!i)throw new Error(`Cannot rebuild compound part "${s.name}": the retained compound source data is not available.`);this._appendPartSourceToArrays(i,e,h,l,c,f,T,E),e+=i._vertexCount}}else if(this._splatsData){const e=$l._GetSplatDataBytes(this._splatsData),t=$l._GetSplatDataFloats(this._splatsData);for(let i=0;i<s;i++)this._makeSplat(i,t,e,h,l,c,T,E,!1);if(f&&this._shData)for(let e=0;e<f.length;e++)e<this._shData.length&&f[e].set(this._shData[e].subarray(0,s*sc),0)}if(g){const e=m*n.x;if(e<s)if(0===this._partProxies.length){if(this._splatsData){const t=$l._GetSplatDataBytes(this._splatsData),i=$l._GetSplatDataFloats(this._splatsData);for(let r=e;r<s;r++)this._makeSplat(r,i,t,h,l,c,T,E,!1,r)}}else{const t=this._partProxies.reduce((e,t)=>e+(t?t._vertexCount:0),0),i=s-t,r=new Array(this._partProxies.length).fill(null),n=new Array(this._partProxies.length).fill(null),a=new Array(this._partProxies.length).fill(0);!this._partProxies[0]&&this._splatsData&&i>0&&(r[0]=$l._GetSplatDataBytes(this._splatsData),n[0]=$l._GetSplatDataFloats(this._splatsData),a[0]=0);let o=i;for(let e=0;e<this._partProxies.length;e++){const t=this._partProxies[e];if(!t)continue;if(this._streamingStates.some(e=>e.proxy===t)){a[e]=o,o+=t._vertexCount;continue}const s=this._createRetainedPartSource(t);if(!s||!s._splatsData)throw new Error(`Cannot rebuild compound part "${t.name}": the retained compound source data is not available.`);r[e]=$l._GetSplatDataBytes(s._splatsData),n[e]=$l._GetSplatDataFloats(s._splatsData),a[e]=o,o+=s._vertexCount}for(let t=e;t<s;t++){const e=this._partIndices?this._partIndices[t]:0,s=e<r.length?r[e]:null,i=e<n.length?n[e]:null;s&&i&&this._makeSplat(t,i,s,h,l,c,T,E,!1,t-(a[e]??0))}}}x=s;for(const t of e)this._appendPartSourceToArrays(t,x,h,l,c,f,T,E),x+=t._vertexCount;const v=r+15&-16;for(let e=r;e<v;e++)this._makeEmptySplat(e,h,l,c);r!==this._vertexCount&&this._updateSplatIndexBuffer(r),this._retainMergedPartData(s,r,e,d?p:0),this._vertexCount=r,this._shDegree=p,this._maxShDegree=p;const I=!this._rebuilding;I&&(this._canPostToWorker=!1,this._rebuilding=!0);try{if(g){if(f&&(!this._shTextures||f.length>this._shTextures.length))for(this._shTextures||(this._shTextures=[]);this._shTextures.length<f.length;){const e=this._shTextures.length,t=new pl(null,n.x,n.y,dt.TEXTUREFORMAT_RGBA_INTEGER,this._scene,!1,!1,dt.TEXTURE_NEAREST_SAMPLINGMODE,dt.TEXTURETYPE_UNSIGNED_INTEGER);t.wrapU=dt.TEXTURE_CLAMP_ADDRESSMODE,t.wrapV=dt.TEXTURE_CLAMP_ADDRESSMODE,this._shTextures.push(t);const s=this._shData&&e<this._shData.length?this._shData[e]:f[e];this._updateShTextureData(t,s,n.x,0,n.y)}if(f&&this._shData){const e=m*n.x;if(e<s){const t=e*sc,i=s*sc;for(let e=0;e<f.length;e++)e<this._shData.length&&f[e].set(this._shData[e].subarray(t,i),t)}}this._onUpdateTextures(n),this._updateSubTextures(this._splatPositions,h,l,c,m,n.y-m,f)}else this._updateTextures(h,l,c,f);this.setEnabled(!0),this._notifyWorkerNewData(),!this._partProxies[0]&&s>0&&!this._part0LocalMin&&(this._part0LocalMin=this.getBoundingInfo().minimum.clone(),this._part0LocalMax=this.getBoundingInfo().maximum.clone());const i=[];for(let s=0;s<e.length;s++){const r=e[s],n=y[s],a=r.getWorldMatrix();this.setWorldMatrixForPart(n,a);const o=new Ql(r.name,this.getScene(),this,n,r.getBoundingInfo(),r._vertexCount,M[s],M[s]);t&&r.dispose();const h=new ve;a.decompose(o.scaling,h,o.position),o.rotationQuaternion=h,o.computeWorldMatrix(!0),this._partProxies[n]=o,i.push(o)}return this._updateBoundingInfoFromProxies(),I&&(this._rebuilding=!1,this._worker&&this._worker.postMessage({command:Bl,partMatrices:this._partMatrices.map(e=>new Float32Array(e.m))}),this._canPostToWorker=!0,this._hasStreamingPart&&this._refreshPartRangeUnion(),this._postToWorker(!0)),this.onPartCountChangedObservable.notifyObservers(this.partCount),{proxyMeshes:i,assignedPartIndices:y}}catch(e){throw I&&(this._rebuilding=!1,this._canPostToWorker=!0),e}}addPart(e,t=!0){const{proxyMeshes:s}=this._addPartsInternal([e],t);return s[0]}_refreshStreamingShState(){let e=0,t=0,s=!1;for(const i of this._streamingStates)this._tombstonedPartIndices.has(i.partIndex)||(i.shTextureCount>e&&(e=i.shTextureCount),i.shDegree>t&&(t=i.shDegree),i.needsRotationScale&&(s=!0));this._shMrtAtlasTextureCount=e,this._useShMrtAtlas=e>0,this._streamingShDegree=t,this._useRotMrtAtlas=s}_tombstonePart(e){this.onPartRemovedObservable.notifyObservers(e);const t=this._partProxies[e];t&&(t.setEnabled(!1),t.visibility=0),this._partVisibility[e]=0;const s=this._streamingStates.find(t=>t.partIndex===e);s&&(s.removed=!0),this._partSplatRanges[e]=[],this._tombstonedPartIndices.add(e),this._refreshPartRangeUnion(),this._updateBoundingInfoFromProxies()}_resetForRebuild(){if(this._worker&&(this._worker.terminate(),this._worker=null),this._mrtAtlas?(this._mrtAtlas.dispose(),this._mrtAtlas=null,this._covariancesATexture=this._covariancesBTexture=this._centersTexture=this._colorsTexture=null):(this._covariancesATexture?.dispose(),this._covariancesBTexture?.dispose(),this._centersTexture?.dispose(),this._colorsTexture?.dispose(),this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null),this._rotMrtAtlas?(this._rotMrtAtlas.dispose(),this._rotMrtAtlas=null):(this._rotationsATexture?.dispose(),this._rotationsBTexture?.dispose(),this._rotationScaleTexture?.dispose()),this._rotationsATexture=null,this._rotationsBTexture=null,this._rotationScaleTexture=null,this._shMrtAtlas){for(const e of this._shMrtAtlas)e.dispose();this._shMrtAtlas=null,this._shTextures=null}else if(this._shTextures){for(const e of this._shTextures)e.dispose();this._shTextures=null}this._partIndicesTexture&&(this._partIndicesTexture.dispose(),this._partIndicesTexture=null),this._vertexCount=0,this._splatPositions=null,this._partIndices=null,this._partMatrices=[],this._partVisibility=[],this._cachedBoundingMin=null,this._cachedBoundingMax=null,this._part0LocalMin=null,this._part0LocalMax=null,this._splatsData=null,this._shData=null,this._shDegree=0,this._partProxies=[],this._partSplatRanges=[]}compactAtlas(){if(0===this._tombstonedPartIndices.size)return;const e=this._getTextureSize(1).x,t=[];let s=0;for(let i=0;i<this._partProxies.length;i++){const r=this._partProxies[i];if(!r||this._tombstonedPartIndices.has(i))continue;const n=this._streamingStates.find(e=>e.proxy===r)??null,a=r.getWorldMatrix().clone(),o=this._partVisibility[i]??1;if(n){const i=Math.ceil(s/e)*e,h=i-s,l=h+n.capacity,c={name:r.name,_vertexCount:l,_splatsData:null,_shData:null,_shDegree:0,isCompound:!1,getWorldMatrix:()=>a,getBoundingInfo:()=>new tr(xe.ZeroReadOnly,xe.ZeroReadOnly),dispose:()=>{},_isReservedEmpty:!0};t.push({oldProxy:r,source:c,worldMatrix:a,visibility:o,state:n,newBase:i,frontPad:h}),s+=l}else{const e=this._createRetainedPartSource(r);if(!e||!e._splatsData)throw new Error(`compactAtlas: the retained source data for static part "${r.name}" is not available.`);t.push({oldProxy:r,source:e,worldMatrix:a,visibility:o,state:null,newBase:0,frontPad:0}),s+=e._vertexCount}}this._mrtAtlas&&this._onBeforeAtlasRebuildObservable.notifyObservers(this._mrtAtlas);for(const e of this._tombstonedPartIndices)this._partProxies[e]?.dispose();if(this._resetForRebuild(),0===t.length)return this._streamingStates.length=0,this._hasStreamingPart=!1,this._tombstonedPartIndices.clear(),this._refreshStreamingShState(),this._useMrtAtlas=!1,this._useRGBACovariants=!this.getEngine().isWebGPU&&1===this.getEngine().version,this.setEnabled(!1),void this.onPartCountChangedObservable.notifyObservers(0);this._refreshStreamingShState(),this._rebuilding=!0,this._canPostToWorker=!1;try{const{proxyMeshes:e}=this._addPartsInternal(t.map(e=>e.source),!1);for(let s=0;s<t.length;s++){const i=t[s],r=e[s],n=r.partIndex;this.setWorldMatrixForPart(n,i.worldMatrix),this.setPartVisibility(n,i.visibility);const a=new ve;i.worldMatrix.decompose(r.scaling,a,r.position),r.rotationQuaternion=a,r.computeWorldMatrix(!0),i.oldProxy.updatePartIndex(n),i.oldProxy.updatePartMetadata(r._vertexCount,r._splatsDataOffset,r._shDataOffset),this._partProxies[n]=i.oldProxy,r.dispose(),i.state?(i.state.partIndex=n,i.state.base=r._splatsDataOffset+i.frontPad,this._partSplatRanges[n]=i.state.localRanges?i.state.localRanges.map(e=>({offset:i.state.base+e.offset,count:e.count})):null):this._partSplatRanges[n]=null}this._mrtAtlas&&this._onAfterAtlasRebuildObservable.notifyObservers(this._mrtAtlas),this._streamingStates=t.filter(e=>e.state).map(e=>e.state),this._hasStreamingPart=this._streamingStates.length>0,this._tombstonedPartIndices.clear(),this._updateBoundingInfoFromProxies(),this._rebuilding=!1,this._canPostToWorker=!0,this._refreshPartRangeUnion(),this._notifyWorkerNewData();const s=this._worker;s?.postMessage({command:Bl,partMatrices:this._partMatrices.map(e=>new Float32Array(e.m))}),this._postToWorker(!0),this.onPartCountChangedObservable.notifyObservers(this.partCount)}catch(e){throw this._rebuilding=!1,this._canPostToWorker=!0,e}}removePart(e){if(e<0||e>=this.partCount)throw new Error(`Part index ${e} is out of range [0, ${this.partCount})`);if(this._hasStreamingPart)return void this._tombstonePart(e);const t=[];for(let s=0;s<this._partProxies.length;s++){const i=this._partProxies[s];if(!i||s===e)continue;const r=this._createRetainedPartSource(i);if(!r)throw new Error(`Cannot remove part: the retained compound source data is not available for part "${i.name}".`);t.push({proxyMesh:i,source:r,oldIndex:s,worldMatrix:i.getWorldMatrix().clone(),visibility:this._partVisibility[s]??1})}t.sort((e,t)=>e.oldIndex-t.oldIndex);for(const{proxyMesh:e,source:s}of t){if(!s._splatsData)throw new Error(`Cannot remove part: the source data for part "${e.name}" is not available.`);if(s._shDegree>0&&!s._shData)throw new Error(`Cannot remove part: the SH data for part "${e.name}" is not available.`)}if(this.onPartRemovedObservable.notifyObservers(e),this._partProxies[e]?.dispose(),this._resetForRebuild(),0===t.length)return this.setEnabled(!1),void this.onPartCountChangedObservable.notifyObservers(0);this._rebuilding=!0,this._canPostToWorker=!1;try{const e=t.map(e=>e.source),{proxyMeshes:s}=this._addPartsInternal(e,!1);for(let e=0;e<t.length;e++){const i=t[e].proxyMesh,r=s[e],n=r.partIndex;this.setWorldMatrixForPart(n,t[e].worldMatrix),this.setPartVisibility(n,t[e].visibility);const a=new ve;t[e].worldMatrix.decompose(r.scaling,a,r.position),r.rotationQuaternion=a,r.computeWorldMatrix(!0),i.updatePartIndex(n),i.updatePartMetadata(r._vertexCount,r._splatsDataOffset,r._shDataOffset),this._partProxies[n]=i,r.dispose()}this._rebuilding=!1;const i=this._worker;i?.postMessage({command:Bl,partMatrices:this._partMatrices.map(e=>new Float32Array(e.m))}),this._canPostToWorker=!0,this._postToWorker(!0)}catch(e){throw this._rebuilding=!1,this._canPostToWorker=!0,e}}reserveStreamingPart(e,t=Ie.Identity(),s=this.name+"_streamingPart",i=0,r=0,n=!1){if(!Number.isSafeInteger(e)||e<1)throw new Error("reserveStreamingPart: capacity must be a positive integer");if(!Number.isSafeInteger(r)||r<0||r>4)throw new Error("reserveStreamingPart: shDegree must be an integer in [0, 4]");if(!Number.isSafeInteger(i)||i<0)throw new Error("reserveStreamingPart: shTextureCount must be a non-negative integer");if(r>0!=i>0)throw new Error("reserveStreamingPart: shDegree and shTextureCount must both be positive (SH) or both zero (no SH)");if(r>0){const e=Math.ceil(3*((r+1)*(r+1)-1)/sc);if(i!==e)throw new Error(`reserveStreamingPart: shTextureCount ${i} does not match shDegree ${r} (expected ${e})`)}const a=this._scene.getEngine().getCaps().maxTextureSize,o=a*a,h=this._getTextureSize(1).x,l=this._vertexCount,c=Math.ceil(l/h)*h,u=c-l,d=Math.ceil(e/h)*h,_=u+d,p=l+_;if(p+1>o)throw new Error(`reserveStreamingPart: capacity ${e} would grow the atlas to ${p} splats (plus a sentinel), exceeding the maximum atlas capacity ${o}`);this._useMrtAtlas=!0,this._useRGBACovariants=!0,i>0&&r>0&&(this._useShMrtAtlas=!0,this._shMrtAtlasTextureCount=Math.max(this._shMrtAtlasTextureCount,i),this._streamingShDegree=Math.max(this._streamingShDegree,r)),n&&(this._useRotMrtAtlas=!0,this._needsRotationScaleTextures=!0);const f=new xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),g=new xe(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),m={name:s,_vertexCount:_,_splatsData:null,_shData:null,_shDegree:0,isCompound:!1,getWorldMatrix:()=>t,getBoundingInfo:()=>new tr(xe.ZeroReadOnly,xe.ZeroReadOnly),dispose:()=>{},_isReservedEmpty:!0},{proxyMeshes:T,assignedPartIndices:E}=this._addPartsInternal([m],!1),R=T[0],b={proxy:R,base:c,partIndex:E[0],capacity:d,boundsMin:f,boundsMax:g,localRanges:null,shTextureCount:i>0&&r>0?i:0,shDegree:i>0&&r>0?r:0,needsRotationScale:n,removed:!1};this._streamingStates.push(b);const A=this,y=()=>{f.x<=g.x&&(R.setBoundingInfo(new tr(f.clone(),g.clone())),A._updateBoundingInfoFromProxies())},M=e=>{if(b.removed)throw new Error(`${e}: this streaming part has been removed`)},x=(e,t,s)=>{if(!Number.isInteger(t)||!Number.isInteger(s)||t<0||s<0||t+s>b.capacity)throw new Error(`${e}: local range [${t}, ${t+s}) is outside the reserved region [0, ${b.capacity})`)},S={proxy:R,capacity:e=d,get partIndex(){return b.partIndex},get base(){return b.base},get centersTexture(){return A.centersTexture},get covariancesATexture(){return A.covariancesATexture},get covariancesBTexture(){return A.covariancesBTexture},get colorsTexture(){return A.colorsTexture},get splatPositions(){return A._splatPositions},get mrtAtlas(){return A._mrtAtlas},get shMrtAtlas(){return A._shMrtAtlas},get rotMrtAtlas(){return A._rotMrtAtlas},get atlasWidth(){return A._getTextureSize(A._vertexCount).x},get isDepthSortSettled(){return A._isDepthSortSettled},setActiveRanges:e=>{if(M("setActiveRanges"),e)for(const t of e)x("setActiveRanges",t.offset,t.count);b.localRanges=e?e.map(e=>({offset:e.offset,count:e.count})):null;const t=e?e.map(e=>({offset:b.base+e.offset,count:e.count})):null;A.setPartSplatRanges(b.partIndex,t)},writeSplats:(e,t,s)=>{M("writeSplats"),x("writeSplats",e,t),A._writeStreamingSplats(b.base+e,t,s,f,g),y()},postPositionsRange:(e,t)=>{M("postPositionsRange"),x("postPositionsRange",e,t),A._postWorkerPositionsRange(b.base+e,t)},expandBounds:(e,t)=>{M("expandBounds"),f.minimizeInPlace(e),g.maximizeInPlace(t),y()},notifyDataChanged:()=>{M("notifyDataChanged"),A._notifyWorkerNewData()},onBeforeAtlasRebuild:e=>{const t=A._onBeforeAtlasRebuildObservable.add(e);return()=>A._onBeforeAtlasRebuildObservable.remove(t)},onAfterAtlasRebuild:e=>{const t=A._onAfterAtlasRebuildObservable.add(e);return()=>A._onAfterAtlasRebuildObservable.remove(t)}};return this._hasStreamingPart=!0,S}serialize(e={},t="base64"){if((e=super.serialize(e)).subMeshes=[],e.geometryUniqueId=void 0,e.geometryId=void 0,e.materialUniqueId=void 0,e.materialId=void 0,e.instances=[],e.actions=void 0,e.type=this.getClassName(),e.keepInRam=this._keepInRam,e.disableDepthSort=this._disableDepthSort,e.viewUpdateThreshold=this.viewUpdateThreshold,e._flipY=this._flipY,this._splatsData&&(e.splatsData="base64"===t?lt(this._splatsData):this._splatsData),this._shData&&(e.shData="base64"===t?this._shData.map(lt):this._shData,e.shDegree=this._shDegree),this._partIndices){const s=function(e){const t=[],s=e.length;let i=0;for(;i<s;){const r=e[i];let n=1;for(;i+n<s&&e[i+n]===r;)n++;t.push(n,r),i+=n}return new Uint32Array(t)}(this._partIndices.subarray(0,this._vertexCount));e.partIndices="base64"===t?lt(s):s}return this._partProxies.length&&(e.partProxies=this._partProxies.filter(e=>!!e).map(e=>e.serialize())),e}static _ParseInternal(e,t,s){const i=new s(e.name,null,t,e.keepInRam);i.disableDepthSort=e.disableDepthSort??!1,i.viewUpdateThreshold=e.viewUpdateThreshold??$l._DefaultViewUpdateThreshold;let r=e.splatsData;"string"==typeof r&&(r=ut(r));const n=e.shData;let a;if(Array.isArray(n)&&n.length){const e=[];for(let t=0,s=n.length;t<s;t++){const s=n[t];e[t]="string"==typeof s?new Uint8Array(ut(s)):s}a=e}let o,h=e.partIndices;if("string"==typeof h&&(h=new Uint32Array(ut(h))),h&&(o=function(e){let t=0;const s=e.length;for(let i=0;i<s;i+=2)t+=e[i];const i=new Uint8Array(t);let r=0;for(let t=0;t<s;t+=2){const s=e[t],n=e[t+1];i.fill(n,r,r+s),r+=s}return i}(h)),r){const t=e._flipY??!1;i.updateData(r,a,{flipY:t},o,e.shDegree)}if(e.partProxies)for(const s of e.partProxies){const e=Object.assign({},s);e.compoundSplatMesh=i;const r=Xn.Parse(e,t,""),n=r.partIndex;i._partProxies[n]=r,i.setWorldMatrixForPart(n,r.getWorldMatrix()),i.setPartVisibility(n,r.visibility)}return i}static Parse(e,t){return ic._ParseInternal(e,t,ic)}}function rc(e){return"GaussianSplattingMesh"===e||"GaussianSplattingStream"===e}let nc=!1;function ac(){nc||(nc=!0,Xn._GaussianSplattingMeshParser=ic.Parse)}function oc(e){const t=e.minimum.x,s=e.minimum.y,i=e.minimum.z,r=e.maximum.x,n=e.maximum.y,a=e.maximum.z;return[new xe(t,s,i),new xe(r,n,a),new xe(r,s,i),new xe(t,n,i),new xe(t,s,a),new xe(r,n,i),new xe(t,n,a),new xe(r,s,a)]}function hc(...e){const t=e=>!!e&&"object"==typeof e;return e.reduce((e,s)=>{const i=Object.keys(s);for(const r of i){const i=e[r],n=s[r];Array.isArray(i)&&Array.isArray(n)?e[r]=i.concat(n):t(i)&&t(n)?e[r]=hc(i,n):e[r]=n}return e},{})}Kn||(Kn=!0,be("BABYLON.Mesh",Xn));class lc{constructor(e){this._factory=e}get value(){return this._factory&&(this._value=this._factory(),this._factory=void 0),this._value}}class cc{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class uc extends cc{getDescription(){return"Reducing render target texture size to "+this.maximumSize}constructor(e=0,t=1024,s=.5){super(e),this.priority=e,this.maximumSize=t,this.step=s}apply(e,t){let s=!0;for(let t=0;t<e.textures.length;t++){const i=e.textures[t];if(!i.canRescale||i.getContext)continue;const r=i.getSize();Math.max(r.width,r.height)>this.maximumSize&&(i.scale(this.step),s=!1)}return s}}class dc extends cc{getDescription(){return"Setting hardware scaling level to "+this._currentScale}constructor(e=0,t=2,s=.25){super(e),this.priority=e,this.maximumScale=t,this.step=s,this._currentScale=-1,this._directionOffset=1}apply(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,this._currentScale=Math.min(this.maximumScale,this._currentScale),e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale}}class _c extends cc{getDescription(){return"Turning shadows on/off"}apply(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0}}class pc extends cc{getDescription(){return"Turning post-processes on/off"}apply(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0}}class fc extends cc{getDescription(){return"Turning lens flares on/off"}apply(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0}}class gc extends cc{getDescription(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"}apply(e,t){return!this.onApply||this.onApply(e,t)}}class mc extends cc{getDescription(){return"Turning particles on/off"}apply(e,t){return e.particlesEnabled=t.isInImprovementMode,!0}}class Tc extends cc{getDescription(){return"Turning render targets off"}apply(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0}}class Ec extends cc{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof Xn))return!1;const t=e;return!t.isDisposed()&&(!(!t.isVisible||!t.isEnabled())&&(!(t.instances.length>0)&&(!t.skeleton&&!t.hasLODLevels&&0!==t.getTotalVertices())))}}static get UpdateSelectionTree(){return Ec._UpdateSelectionTree}static set UpdateSelectionTree(e){Ec._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,s){const i=e.meshes.slice(0);let r=i.length;for(let e=0;e<r;e++){const t=[],s=i[e];if(this._canBeMerged(s)){t.push(s);for(let n=e+1;n<r;n++){const e=i[n];this._canBeMerged(e)&&(e.material===s.material&&e.checkCollisions===s.checkCollisions&&(t.push(e),r--,i.splice(n,1),n--))}t.length<2||Xn.MergeMeshes(t,void 0,!0)}}const n=e;return Be(n.createOrUpdateSelectionOctree)&&(null!=s?s&&n.createOrUpdateSelectionOctree():Ec.UpdateSelectionTree&&n.createOrUpdateSelectionOctree()),!0}}Ec._UpdateSelectionTree=!1;class Rc{constructor(e=60,t=2e3){this.targetFrameRate=e,this.trackerDuration=t,this.optimizations=[]}addOptimization(e){return this.optimizations.push(e),this}addCustomOptimization(e,t,s=0){const i=new gc(s);return i.onApply=e,i.onGetDescription=t,this.optimizations.push(i),this}static LowDegradationAllowed(e){const t=new Rc(e);let s=0;return t.addOptimization(new Ec(s)),t.addOptimization(new _c(s)),t.addOptimization(new fc(s)),s++,t.addOptimization(new pc(s)),t.addOptimization(new mc(s)),s++,t.addOptimization(new uc(s,1024)),t}static ModerateDegradationAllowed(e){const t=new Rc(e);let s=0;return t.addOptimization(new Ec(s)),t.addOptimization(new _c(s)),t.addOptimization(new fc(s)),s++,t.addOptimization(new pc(s)),t.addOptimization(new mc(s)),s++,t.addOptimization(new uc(s,512)),s++,t.addOptimization(new Tc(s)),s++,t.addOptimization(new dc(s,2)),t}static HighDegradationAllowed(e){const t=new Rc(e);let s=0;return t.addOptimization(new Ec(s)),t.addOptimization(new _c(s)),t.addOptimization(new fc(s)),s++,t.addOptimization(new pc(s)),t.addOptimization(new mc(s)),s++,t.addOptimization(new uc(s,256)),s++,t.addOptimization(new Tc(s)),s++,t.addOptimization(new dc(s,4)),t}}class bc{get isInImprovementMode(){return this._improvementMode}set isInImprovementMode(e){this._improvementMode=e}get currentPriorityLevel(){return this._currentPriorityLevel}get currentFrameRate(){return this._currentFrameRate}get targetFrameRate(){return this._targetFrameRate}set targetFrameRate(e){this._targetFrameRate=e}get trackerDuration(){return this._trackerDuration}set trackerDuration(e){this._trackerDuration=e}get optimizations(){return this._options.optimizations}constructor(e,t,s=!0,i=!1){if(this._isRunning=!1,this._currentPriorityLevel=0,this._targetFrameRate=60,this._trackerDuration=2e3,this._currentFrameRate=0,this._improvementMode=!1,this.onSuccessObservable=new c,this.onNewOptimizationAppliedObservable=new c,this.onFailureObservable=new c,this._options=t||new Rc,this._options.targetFrameRate&&(this._targetFrameRate=this._options.targetFrameRate),this._options.trackerDuration&&(this._trackerDuration=this._options.trackerDuration),s){let e=0;for(const t of this._options.optimizations)t.priority=e++}this._improvementMode=i,this._scene=e||ee.LastCreatedScene,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(()=>{this._sceneDisposeObserver=null,this.dispose()})}stop(){this._isRunning=!1}reset(){this._currentPriorityLevel=0}start(){this._isRunning||(this._isRunning=!0,this._scene.executeWhenReady(()=>{setTimeout(()=>{this._checkCurrentState()},this._trackerDuration)}))}_checkCurrentState(){if(!this._isRunning)return;const e=this._scene,t=this._options;if(this._currentFrameRate=Math.round(e.getEngine().getFps()),this._improvementMode&&this._currentFrameRate<=this._targetFrameRate||!this._improvementMode&&this._currentFrameRate>=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);let s=!0,i=!0;for(let r=0;r<t.optimizations.length;r++){const n=t.optimizations[r];n.priority===this._currentPriorityLevel&&(i=!1,s=s&&n.apply(e,this),this.onNewOptimizationAppliedObservable.notifyObservers(n))}if(i)return this._isRunning=!1,void this.onFailureObservable.notifyObservers(this);s&&this._currentPriorityLevel++,e.executeWhenReady(()=>{setTimeout(()=>{this._checkCurrentState()},this._trackerDuration)})}dispose(){this.stop(),this.onSuccessObservable.clear(),this.onFailureObservable.clear(),this.onNewOptimizationAppliedObservable.clear(),this._sceneDisposeObserver&&this._scene.onDisposeObservable.remove(this._sceneDisposeObserver)}static OptimizeAsync(e,t,s,i){const r=new bc(e,t||Rc.ModerateDegradationAllowed(),!1);return s&&r.onSuccessObservable.add(()=>{s()}),i&&r.onFailureObservable.add(()=>{i()}),r.start(),r}}class Ac{constructor(e,t,s){this.name=e,this._parentTask=t,this._context=s,this.disabled=!1}setInitializeFunc(e){this._initFunc=e}setExecuteFunc(e){this._executeFunc=e}_execute(){this.disabled||this._executeFunc(this._context)}_initialize(){this._initFunc?.(this._context)}_isValid(){return void 0!==this._executeFunc?null:"Execute function is not set (call setExecuteFunc to set it)"}_dispose(){}}class yc extends Ac{static IsObjectListPass(e){return void 0!==e.setObjectList}get objectList(){return this._objectList}setObjectList(e){this._objectList=e}constructor(e,t,s,i){super(e,t,s),this._engine=i}_isValid(){const e=super._isValid();return e||(void 0!==this._objectList?null:"Object list is not set (call setObjectList to set it)")}}class Mc extends Ac{static IsRenderPass(e){return void 0!==e.setRenderTarget}get renderTarget(){return this._renderTarget}get renderTargetDepth(){return this._renderTargetDepth}get frameGraphRenderTarget(){return this._frameGraphRenderTarget}constructor(e,t,s,i){super(e,t,s),this._dependencies=new Set,this.depthReadOnly=!1,this.stencilReadOnly=!1,this._engine=i}setRenderTarget(e){this._renderTarget=e}setRenderTargetDepth(e){this._renderTargetDepth=e}addDependencies(e){if(void 0!==e)if(Array.isArray(e))for(const t of e)this._dependencies.add(t);else this._dependencies.add(e)}collectDependencies(e){const t=this._dependencies.keys();for(let s=t.next();!0!==s.done;s=t.next())e.add(s.value);if(void 0!==this._renderTarget)if(Array.isArray(this._renderTarget))for(const t of this._renderTarget)void 0!==t&&e.add(t);else e.add(this._renderTarget);void 0!==this._renderTargetDepth&&e.add(this._renderTargetDepth)}setOutputLayerAndFaceIndices(e){const t=this.frameGraphRenderTarget.renderTargetWrapper;if(t)for(const s of e)t.setLayerAndFaceIndex(s.targetIndex,s.layerIndex,s.faceIndex)}_initialize(){this._frameGraphRenderTarget=this._context.createRenderTarget(this.name,this._renderTarget,this._renderTargetDepth,this.depthReadOnly,this.stencilReadOnly),super._initialize()}_execute(){this._context.bindRenderTarget(this._frameGraphRenderTarget),super._execute(),this._context.restoreDefaultFramebuffer()}_isValid(){const e=super._isValid();return e||(void 0!==this._renderTarget||void 0!==this.renderTargetDepth?null:"Render target and render target depth cannot both be undefined.")}_dispose(){this._frameGraphRenderTarget?.dispose()}}class xc{get name(){return this._name}set name(e){this._name=e}get disabled(){return this._disabled}set disabled(e){this._disabled=e}get passes(){return this._passes}get passesDisabled(){return this._passesDisabled}getClassName(){return"FrameGraphTask"}initAsync(){return Promise.resolve()}isReady(){return!0}dispose(){this._reset(),this.onTexturesAllocatedObservable.clear(),this.onBeforeTaskExecute.clear(),this.onAfterTaskExecute.clear()}constructor(e,t){this._passes=[],this._passesDisabled=[],this._disabled=!1,this.onTexturesAllocatedObservable=new c,this.onBeforeTaskExecute=new c,this.onAfterTaskExecute=new c,this.name=e,this._frameGraph=t,this._reset()}_reset(){for(const e of this._passes)e._dispose();for(const e of this._passesDisabled)e._dispose();this._passes.length=0,this._passesDisabled.length=0}_addPass(e,t){t?this._passesDisabled.push(e):this._passes.push(e)}_checkTask(){let e,t=null,s=null;for(const i of this._passes){const r=i._isValid();if(r)throw new Error(`Pass "${i.name}" is not valid. ${r}`);if(Mc.IsRenderPass(i)){const e=Array.isArray(i.renderTarget)?i.renderTarget:[i.renderTarget];t=[];for(const s of e)void 0!==s&&t.push(this._frameGraph.textureManager.getTextureFromHandle(s));s=void 0!==i.renderTargetDepth?this._frameGraph.textureManager.getTextureFromHandle(i.renderTargetDepth):null}else yc.IsObjectListPass(i)&&(e=i.objectList)}let i,r=null,n=[],a=null;for(const e of this._passesDisabled){const t=e._isValid();if(t)throw new Error(`Pass "${e.name}" is not valid. ${t}`);if(Mc.IsRenderPass(e)){const t=Array.isArray(e.renderTarget)?e.renderTarget:[e.renderTarget];r=[];for(const e of t)void 0!==e&&r.push(this._frameGraph.textureManager.getTextureFromHandle(e));n=t,a=void 0!==e.renderTargetDepth?this._frameGraph.textureManager.getTextureFromHandle(e.renderTargetDepth):null}else yc.IsObjectListPass(e)&&(i=e.objectList)}if(this._passesDisabled.length>0){if(!this._checkSameRenderTarget(t,r)){let e=!0;for(const t of n)if(void 0!==t&&!this._frameGraph.textureManager.isHistoryTexture(t)){e=!1;break}if(!e)throw new Error(`The output texture of the task "${this.name}" is different when it is enabled or disabled.`)}if(s!==a&&null!==a)throw new Error(`The output depth texture of the task "${this.name}" is different when it is enabled or disabled.`);if(e!==i&&null!==i)throw new Error(`The output object list of the task "${this.name}" is different when it is enabled or disabled.`)}}_execute(){const e=this._disabled&&this._passesDisabled.length>0?this._passesDisabled:this._passes;this.onBeforeTaskExecute.notifyObservers(this),this._frameGraph.engine._debugPushGroup?.(`${this.getClassName()} (${this.name})`);try{for(const t of e)t._execute()}finally{this._frameGraph.engine._debugPopGroup?.()}this.onAfterTaskExecute.notifyObservers(this)}_initializePasses(){this._frameGraph.engine._debugPushGroup?.(`${this.getClassName()} (${this.name})`);try{for(const e of this._passes)e._initialize();for(const e of this._passesDisabled)e._initialize()}finally{this._frameGraph.engine._debugPopGroup?.()}}_checkSameRenderTarget(e,t){if(null===e||null===t)return e===t;if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==t[s])return!1;return!0}}class Sc extends xc{constructor(){super(...arguments),this._layerAndFaceIndicesUpdated=!1}setOutputLayerAndFaceIndices(e){this._outputLayerAndFaceIndices=e,this._layerAndFaceIndicesUpdated=e.length>0}_updateLayerAndFaceIndices(e){this._layerAndFaceIndicesUpdated&&(e.setOutputLayerAndFaceIndices(this._outputLayerAndFaceIndices),this._layerAndFaceIndicesUpdated=!1)}}class vc{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}get shaderLanguage(){return this._shaderLanguage}get blendOutput(){return this._blendOutput}set blendOutput(e){this._blendOutput=e,this._disposeTextures(),e&&this._createTextures()}constructor(e,t=5){this._depthMrts=[],this._thinTextures=[],this._colorMrts=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new Ws(10),this._excludedSubMeshes=new Ws(10),this._excludedMeshes=[],this._colorCache=[new Ke(vc._DEPTH_CLEAR_VALUE,vc._DEPTH_CLEAR_VALUE,0,0),new Ke(-vc._MIN_DEPTH,vc._MAX_DEPTH,0,0),new Ke(0,0,0,0)],this._shaderLanguage=0,this._scene=e,this._engine=e.getEngine(),this._passCount=t;for(let e=0;e<this._layoutCacheFormat.length;++e)this._layoutCache[e]=this._engine.buildTextureLayout(this._layoutCacheFormat[e]);this._renderPassIds=[],this.useRenderPasses=!1,this._engine.isWebGPU&&(this._shaderLanguage=1),this._createEffects("oitFinalSimpleBlend",["uFrontColor"])}_createRenderPassIds(){if(this._releaseRenderPassIds(),this._useRenderPasses)for(let e=0;e<this._passCount+1;++e)this._renderPassIds[e]||(this._renderPassIds[e]=this._engine.createRenderPassId(`DepthPeelingRenderer - pass #${e}`))}_releaseRenderPassIds(){for(let e=0;e<this._renderPassIds.length;++e)this._engine.releaseRenderPassId(this._renderPassIds[e]);this._renderPassIds=[]}_getTextureSize(){return this._blendOutput?{width:this._blendOutput.width,height:this._blendOutput.height}:{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()}}_createTextures(){const e=this._getTextureSize();this._depthMrts=[new yl("depthPeelingDepth0MRT",e,3,this._scene,void 0,["depthPeelingDepth0MRT_depth","depthPeelingDepth0MRT_frontColor","depthPeelingDepth0MRT_backColor"]),new yl("depthPeelingDepth1MRT",e,3,this._scene,void 0,["depthPeelingDepth1MRT_depth","depthPeelingDepth1MRT_frontColor","depthPeelingDepth1MRT_backColor"])],this._colorMrts=[new yl("depthPeelingColor0MRT",e,2,this._scene,{generateDepthBuffer:!1},["depthPeelingColor0MRT_frontColor","depthPeelingColor0MRT_backColor"]),new yl("depthPeelingColor1MRT",e,2,this._scene,{generateDepthBuffer:!1},["depthPeelingColor1MRT_frontColor","depthPeelingColor1MRT_backColor"])],this._blendBackMrt=new yl("depthPeelingBackMRT",e,1,this._scene,{generateDepthBuffer:!1},["depthPeelingBackMRT_blendBack"]),this._blendOutput&&this._blendBackMrt.setInternalTexture(this._blendOutput.texture,0);const t=[{format:dt.TEXTUREFORMAT_RG,samplingMode:dt.TEXTURE_NEAREST_SAMPLINGMODE,type:this._engine.getCaps().textureFloatLinearFiltering?dt.TEXTURETYPE_FLOAT:dt.TEXTURETYPE_HALF_FLOAT,label:"DepthPeelingRenderer-DepthTexture"},{format:dt.TEXTUREFORMAT_RGBA,samplingMode:dt.TEXTURE_NEAREST_SAMPLINGMODE,type:dt.TEXTURETYPE_HALF_FLOAT,label:"DepthPeelingRenderer-ColorTexture"}];for(let s=0;s<2;s++){const i=this._engine._createInternalTexture(e,t[0],!1),r=this._engine._createInternalTexture(e,t[1],!1),n=this._engine._createInternalTexture(e,t[1],!1);this._depthMrts[s].setInternalTexture(i,0),this._depthMrts[s].setInternalTexture(r,1),this._depthMrts[s].setInternalTexture(n,2),this._colorMrts[s].setInternalTexture(r,0),this._colorMrts[s].setInternalTexture(n,1),this._thinTextures.push(new xh(i),new xh(r),new xh(n))}this._blendOutput&&this._blendOutput.shareDepth(this._depthMrts[0].renderTarget)}_disposeTextures(){for(let e=0;e<this._thinTextures.length;e++)this._thinTextures[e].dispose();for(let e=0;e<this._depthMrts.length;e++)this._depthMrts[e].dispose(!0),this._colorMrts[e].dispose(!0),this._blendBackMrt.dispose(!0);this._thinTextures=[],this._colorMrts=[],this._depthMrts=[]}_createEffects(e,t){this._blendBackEffectWrapper=new Sl({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await import("./oitBackBlend.fragment-DMnpRJiG.esm.min.js"):await import("./oitBackBlend.fragment-BN-LfOuL.esm.min.js")}}),this._blendBackEffectWrapperPingPong=new Sl({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await import("./oitBackBlend.fragment-DMnpRJiG.esm.min.js"):await import("./oitBackBlend.fragment-BN-LfOuL.esm.min.js")}}),this._finalEffectWrapper=new Sl({fragmentShader:e,useShaderStore:!0,engine:this._engine,samplerNames:t,uniformNames:[],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await import("./oitFinalSimpleBlend.fragment-DYyXhh3h.esm.min.js"):await import("./oitFinalSimpleBlend.fragment-BCJ9UAeK.esm.min.js")}}),this._effectRenderer=new xl(this._engine)}setPrePassRenderer(e){}bind(e){e.setTexture("oitDepthSampler",this._thinTextures[3*this._currentPingPongState]),e.setTexture("oitFrontColorSampler",this._thinTextures[3*this._currentPingPongState+1])}_renderSubMeshes(e){let t;this._useRenderPasses&&(t={});for(let s=0;s<e.length;s++){const i=e.data[s].getMaterial();let r=!0,n=!1;const a=e.data[s];let o,h=!1;if(this._useRenderPasses&&(o=a._getDrawWrapper(),h=!o),i&&(r=i.allowShaderHotSwapping,n=i.backFaceCulling,i.allowShaderHotSwapping=!1,i.backFaceCulling=!1),a.render(!1),h&&(o=a._getDrawWrapper(),o.materialContext)){let e=t[o.materialContext.uniqueId];e||(e=t[o.materialContext.uniqueId]=this._engine.createMaterialContext()),a._getDrawWrapper().materialContext=e}i&&(i.allowShaderHotSwapping=r,i.backFaceCulling=n)}}_finalCompose(e){this._engine.bindFramebuffer(this._blendOutput),this._engine.setAlphaMode(dt.ALPHA_PREMULTIPLIED),this._engine.depthCullingState.depthMask=!1,this._engine.depthCullingState.depthTest=!1,this._engine.applyStates(),this._engine.enableEffect(this._finalEffectWrapper.drawWrapper),this._finalEffectWrapper.effect.setTexture("uFrontColor",this._thinTextures[3*e+1]),this._effectRenderer.render(this._finalEffectWrapper)}isReady(){return this._blendBackEffectWrapper.effect.isReady()&&this._blendBackEffectWrapperPingPong.effect.isReady()&&this._finalEffectWrapper.effect.isReady()}_beforeRender(){}_afterRender(){}_noTransparentMeshes(){}render(e){if(this._candidateSubMeshes.length=0,this._excludedSubMeshes.length=0,!this.isReady())return this._excludedSubMeshes;this._scene.activeCamera&&this._engine.setViewport(this._scene.activeCamera.viewport);for(let t=0;t<e.length;t++){const s=e.data[t],i=s.getMaterial(),r=i&&s.getRenderingMesh()._getRenderingFillMode(i.fillMode);!i||r!==Cn.TriangleFanDrawMode&&r!==Cn.TriangleFillMode&&r!==Cn.TriangleStripDrawMode||-1!==this._excludedMeshes.indexOf(s.getMesh().uniqueId)?this._excludedSubMeshes.push(s):this._candidateSubMeshes.push(s)}if(!this._candidateSubMeshes.length)return this._noTransparentMeshes(),this._excludedSubMeshes;const t=this._engine.currentRenderPassId;let s;this._beforeRender(),this._useRenderPasses&&(this._engine.currentRenderPassId=this._renderPassIds[0]),this._engine.bindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[0],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindFramebuffer(this._depthMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[1],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[1].renderTarget),this._engine.bindFramebuffer(this._colorMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[0].renderTarget),this._engine.bindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.setAlphaMode(dt.ALPHA_ONEONE_ONEONE),this._engine.setAlphaEquation(dt.ALPHA_EQUATION_MAX),this._engine.depthCullingState.depthMask=!1,this._engine.depthCullingState.depthTest=!0,this._engine.applyStates(),this._currentPingPongState=1,this._renderSubMeshes(this._candidateSubMeshes),this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget),this._scene.resetCachedMaterial();let i=0;for(let e=0;e<this._passCount;e++){s=e%2,i=1-s,this._currentPingPongState=s,this._useRenderPasses&&(this._engine.currentRenderPassId=this._renderPassIds[e+1]),this._scene.activeCamera&&this._engine.setViewport(this._scene.activeCamera.viewport),this._engine.bindFramebuffer(this._depthMrts[i].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[0],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[i].renderTarget),this._engine.bindFramebuffer(this._colorMrts[i].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[i].renderTarget),this._engine.bindFramebuffer(this._depthMrts[i].renderTarget),this._engine.bindAttachments(this._layoutCache[2]),this._engine.setAlphaMode(dt.ALPHA_ONEONE_ONEONE),this._engine.setAlphaEquation(dt.ALPHA_EQUATION_MAX),this._engine.depthCullingState.depthTest=!1,this._engine.applyStates(),this._renderSubMeshes(this._candidateSubMeshes),this._engine.unBindFramebuffer(this._depthMrts[i].renderTarget),this._scene.resetCachedMaterial(),this._engine.bindFramebuffer(this._blendBackMrt.renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.setAlphaEquation(dt.ALPHA_EQUATION_ADD),this._engine.setAlphaMode(dt.ALPHA_LAYER_ACCUMULATE),this._engine.applyStates();const t=0!==i&&this._useRenderPasses?this._blendBackEffectWrapperPingPong:this._blendBackEffectWrapper;this._engine.enableEffect(t.drawWrapper),t.effect.setTexture("uBackColor",this._thinTextures[3*i+2]),this._effectRenderer.render(t),this._engine.unBindFramebuffer(this._blendBackMrt.renderTarget)}return this._engine.currentRenderPassId=t,this._finalCompose(i),this._engine.setAlphaMode(dt.ALPHA_DISABLE),this._engine.depthCullingState.depthMask=!0,this._engine.depthCullingState.depthTest=!0,this._afterRender(),this._excludedSubMeshes}dispose(){this._disposeTextures(),this._blendBackEffectWrapper.dispose(),this._finalEffectWrapper.dispose(),this._effectRenderer.dispose(),this._releaseRenderPassIds()}}vc._DEPTH_CLEAR_VALUE=-99999,vc._MIN_DEPTH=0,vc._MAX_DEPTH=1;class Ic{constructor(e,t,s,i){this._isBackBuffer=!1,this.name=e,this._textureManager=t,this._renderTargets=void 0===s?void 0:Array.isArray(s)?s:[s],this._renderTargetDepth=i}get renderTargetWrapper(){if(!this._isBackBuffer){if(!this._renderTargetWrapper){const e=this._textureManager.engine,t=void 0===this._renderTargets||0===this._renderTargets.length?this._renderTargetDepth:this._renderTargets[0];if(this._textureManager.isBackbuffer(t))return void(this._isBackBuffer=!0);const s=this._textureManager.getTextureDescription(t),i={textureCount:this._renderTargets?.length??0,generateDepthBuffer:!1,label:this.name,samples:s.options.samples??1,dontCreateTextures:!0};this._renderTargetWrapper=e.createMultipleRenderTarget(s.size,i,!0);for(let e=0;e<i.textureCount;e++){const t=this._renderTargets[e],s=this._textureManager.getTextureFromHandle(t);if(!s)throw new Error(`FrameGraphRenderTarget.renderTargetWrapper: Failed to get texture from handle. handle: ${t}, name: ${this.name}, index: ${e}, renderTargets: ${this._renderTargets}`);s.incrementReferences(),this._renderTargetWrapper.setTexture(s,e,!1)}void 0!==this._renderTargetDepth&&this._renderTargetWrapper.setDepthStencilTexture(this._textureManager.getTextureFromHandle(this._renderTargetDepth),!1)}return this._renderTargetWrapper}}equals(e){const t=this._renderTargets,s=e._renderTargets;if(void 0!==t&&void 0!==s){if(t.length!==s.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==s[e])return!1}else if(void 0===t&&void 0!==s||void 0!==t&&void 0===s)return!1;return this._renderTargetDepth===e._renderTargetDepth}dispose(){this._renderTargetWrapper?.dispose()}}class Pc extends Sc{get camera(){return this._camera}set camera(e){this._camera=e,this._renderer.activeCamera=this.camera}get disableImageProcessing(){return this._disableImageProcessing}set disableImageProcessing(e){e!==this._disableImageProcessing&&(this._disableImageProcessing=e,this._renderer.disableImageProcessing=e)}get renderMeshes(){return this._renderMeshes}set renderMeshes(e){e!==this._renderMeshes&&(this._renderMeshes=e,this._renderer.renderMeshes=e)}get renderDepthOnlyMeshes(){return this._renderDepthOnlyMeshes}set renderDepthOnlyMeshes(e){e!==this._renderDepthOnlyMeshes&&(this._renderDepthOnlyMeshes=e,this._renderer.renderDepthOnlyMeshes=e)}get renderOpaqueMeshes(){return this._renderOpaqueMeshes}set renderOpaqueMeshes(e){e!==this._renderOpaqueMeshes&&(this._renderOpaqueMeshes=e,this._renderer.renderOpaqueMeshes=e)}get renderAlphaTestMeshes(){return this._renderAlphaTestMeshes}set renderAlphaTestMeshes(e){e!==this._renderAlphaTestMeshes&&(this._renderAlphaTestMeshes=e,this._renderer.renderAlphaTestMeshes=e)}get renderTransparentMeshes(){return this._renderTransparentMeshes}set renderTransparentMeshes(e){e!==this._renderTransparentMeshes&&(this._renderTransparentMeshes=e,this._renderer.renderTransparentMeshes=e)}get useOITForTransparentMeshes(){return this._useOITForTransparentMeshes}set useOITForTransparentMeshes(e){e!==this._useOITForTransparentMeshes&&(this._useOITForTransparentMeshes=e,this._renderer.customRenderTransparentSubMeshes=this._useOITForTransparentMeshes?(e,t)=>this._renderTransparentMeshesWithOIT(e,t):void 0,this._oitRenderer.blendOutput=e&&this._rtForOrderIndependentTransparency?this._rtForOrderIndependentTransparency.renderTargetWrapper:null)}get oitPassCount(){return this._oitRenderer.passCount}set oitPassCount(e){e!==this._oitRenderer.passCount&&(this._oitRenderer.passCount=e)}get renderParticles(){return this._renderParticles}set renderParticles(e){e!==this._renderParticles&&(this._renderParticles=e,this._renderer.renderParticles=e)}get renderSprites(){return this._renderSprites}set renderSprites(e){e!==this._renderSprites&&(this._renderSprites=e,this._renderer.renderSprites=e)}get forceLayerMaskCheck(){return this._forceLayerMaskCheck}set forceLayerMaskCheck(e){e!==this._forceLayerMaskCheck&&(this._forceLayerMaskCheck=e,this._renderer.forceLayerMaskCheck=e)}get enableBoundingBoxRendering(){return this._enableBoundingBoxRendering}set enableBoundingBoxRendering(e){e!==this._enableBoundingBoxRendering&&(this._enableBoundingBoxRendering=e,this._renderer.enableBoundingBoxRendering=e)}get enableOutlineRendering(){return this._enableOutlineRendering}set enableOutlineRendering(e){e!==this._enableOutlineRendering&&(this._enableOutlineRendering=e,this._renderer.enableOutlineRendering=e)}get objectRenderer(){return this._renderer}get name(){return this._name}set name(e){this._name=e,this._renderer&&(this._renderer.name=e)}constructor(e,t,s,i,r){super(e,t),this.shadowGenerators=[],this.depthTest=!0,this.depthWrite=!0,this.disableShadows=!1,this._disableImageProcessing=!1,this.isMainObjectRenderer=!1,this._renderMeshes=!0,this._renderDepthOnlyMeshes=!0,this._renderOpaqueMeshes=!0,this._renderAlphaTestMeshes=!0,this._renderTransparentMeshes=!0,this._useOITForTransparentMeshes=!1,this._renderParticles=!0,this._renderSprites=!0,this._forceLayerMaskCheck=!0,this._enableBoundingBoxRendering=!0,this._enableOutlineRendering=!0,this.resolveMSAAColors=!0,this.resolveMSAADepth=!1,this._onBeforeRenderObservable=null,this._onAfterRenderObservable=null,this._externalObjectRenderer=!1,this._scene=s,this._engine=s.getEngine(),this._externalObjectRenderer=!!r,this._renderer=r??new ml(e,s,i),this.name=e,this._renderer.disableImageProcessing=this._disableImageProcessing,this._renderer.renderParticles=this._renderParticles,this._renderer.renderSprites=this._renderSprites,this._renderer.enableBoundingBoxRendering=this._enableBoundingBoxRendering,this._renderer.forceLayerMaskCheck=this._forceLayerMaskCheck,this._externalObjectRenderer||this._renderer.onBeforeRenderingManagerRenderObservable.add(()=>{this._renderer.options.doNotChangeAspectRatio||s.updateTransformMatrix(!0)}),this._oitRenderer=new vc(s),this._oitRenderer.useRenderPasses=!0,this.outputTexture=this._frameGraph.textureManager.createDanglingHandle(),this.outputDepthTexture=this._frameGraph.textureManager.createDanglingHandle()}isReady(){return this._renderer.renderList=this.objectList.meshes,this._renderer.particleSystemList=this.objectList.particleSystems,this._renderer.isReadyForRendering(this._textureWidth,this._textureHeight)}getClassName(){return"FrameGraphObjectRendererTask"}record(e=!1,t){this._checkParameters();const s=this._getTargetHandles(),i=this._checkTextureCompatibility(s);this._resolveDanglingHandles(s),this._setLightsForShadow(),this._rtForOrderIndependentTransparency?.dispose();const r=this._frameGraph.addRenderPass(this.name);if(r.setRenderTarget(s),r.setRenderTargetDepth(this.depthTexture),r.setInitializeFunc(()=>{this._rtForOrderIndependentTransparency=new Ic(this.name+"_oitRT",this._frameGraph.textureManager,this.targetTexture,this.depthTexture)}),r.setExecuteFunc(e=>{this._renderer.renderList=this.objectList.meshes,this._renderer.particleSystemList=this.objectList.particleSystems,this._updateLayerAndFaceIndices(r);const s=r.frameGraphRenderTarget.renderTargetWrapper;s&&(s.resolveMSAAColors=this.resolveMSAAColors,s.resolveMSAADepth=this.resolveMSAADepth),this._useOITForTransparentMeshes&&this._oitRenderer.blendOutput!==this._rtForOrderIndependentTransparency.renderTargetWrapper&&(this._oitRenderer.blendOutput=this._rtForOrderIndependentTransparency.renderTargetWrapper);const n=this.getBoundingBoxRenderer?.(),a=n&&n.renderList.length>0?n.renderList.data.slice():[];n&&(a.length=n.renderList.length);const o=this._prepareRendering(e,i),h=this._scene._depthPeelingRenderer;this._scene._depthPeelingRenderer=this._oitRenderer;const l=this._renderer.activeCamera;if(l&&l.cameraRigMode!==dt.RIG_MODE_NONE&&!l._renderingMultiview){for(let t=0;t<l._rigCameras.length;t++){const s=l._rigCameras[t];s.rigParent=void 0,this._renderer.activeCamera=s,e.pushDebugGroup(`Render objects for camera rig ${t} "${s.name}"`),e.bindRenderTarget(r.frameGraphRenderTarget),o&&e.bindAttachments(o),e.render(this._renderer,this._textureWidth,this._textureHeight,!0),e.popDebugGroup(),s.rigParent=l}this._renderer.activeCamera=l}else e.pushDebugGroup(`Render objects for camera "${this._renderer.activeCamera?.name??"undefined"}"`),e.bindRenderTarget(r.frameGraphRenderTarget),o&&e.bindAttachments(o),e.render(this._renderer,this._textureWidth,this._textureHeight,!0),e.popDebugGroup();t?.(e),this._scene._depthPeelingRenderer=h,n&&(n.renderList.data=a,n.renderList.length=a.length)}),!e){const e=this._frameGraph.addRenderPass(this.name+"_disabled",!0);e.setRenderTarget(s),e.setRenderTargetDepth(this.depthTexture),e.setExecuteFunc(e=>{})}return r}dispose(){this._renderer.onBeforeRenderObservable.remove(this._onBeforeRenderObservable),this._renderer.onAfterRenderObservable.remove(this._onAfterRenderObservable),this._externalObjectRenderer||this._renderer.dispose(),this._oitRenderer.dispose(),this._rtForOrderIndependentTransparency?.dispose(),super.dispose()}_resolveDanglingHandles(e){e.length>0&&this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture,e[0]),void 0!==this.depthTexture&&this._frameGraph.textureManager.resolveDanglingHandle(this.outputDepthTexture,this.depthTexture)}_checkParameters(){if(void 0===this.targetTexture||void 0===this.objectList||void 0===this.camera)throw new Error(`FrameGraphObjectRendererTask ${this.name}: targetTexture, objectList, and camera are required`)}_checkTextureCompatibility(e){const t=this.getClassName();let s=e.length>0?this._frameGraph.textureManager.getTextureDescription(e[0]):null,i=!1;if(void 0!==this.depthTexture){if(s&&1!==this.depthTexture&&0===e[0])throw new Error(`${t} ${this.name}: the back buffer depth/stencil texture is the only depth texture allowed when the target is the back buffer color`);const r=this._frameGraph.textureManager.getTextureDescription(this.depthTexture);if(s||(s=r),r.options.samples!==s.options.samples)throw new Error(`${t} ${this.name}: the depth texture "${r.options.labels?.[0]??"noname"}" (${r.options.samples} samples) and the output texture "${s.options.labels?.[0]??"noname"}" (${s.options.samples} samples) must have the same number of samples`);if(r.size.width!==s.size.width||r.size.height!==s.size.height)throw new Error(`${t} ${this.name}: the depth texture (size: ${r.size.width}x${r.size.height}) and the target texture (size: ${s.size.width}x${s.size.height}) must have the same dimensions.`);i=!0}return this._textureWidth=s?.size.width??1,this._textureHeight=s?.size.height??1,i}_getTargetHandles(){return Array.isArray(this.targetTexture)?this.targetTexture:[this.targetTexture]}_prepareRendering(e,t){return e.setDepthStates(this.depthTest&&t,this.depthWrite&&t),null}_setLightsForShadow(){const e=new Set,t=new Map;if(this.shadowGenerators)for(const t of this.shadowGenerators){const s=t.shadowGenerator,i=s.getLight();i.isEnabled()&&i.shadowEnabled&&(e.add(i),"FrameGraphCascadedShadowGeneratorTask"===t.getClassName()?i._shadowGenerators.set(t.camera,s):i._shadowGenerators.set(null,s))}this._renderer.onBeforeRenderObservable.remove(this._onBeforeRenderObservable),this._onBeforeRenderObservable=this._renderer.onBeforeRenderObservable.add(()=>{for(let s=0;s<this._scene.lights.length;s++){const i=this._scene.lights[s];i.setShadowProjectionMatrix&&(t.set(i,i.shadowEnabled),i.shadowEnabled=!this.disableShadows&&e.has(i))}}),this._renderer.onAfterRenderObservable.remove(this._onAfterRenderObservable),this._onAfterRenderObservable=this._renderer.onAfterRenderObservable.add(()=>{for(let e=0;e<this._scene.lights.length;e++){const s=this._scene.lights[e];s.setShadowProjectionMatrix&&(s.shadowEnabled=t.get(s))}})}_renderTransparentMeshesWithOIT(e,t){const s=this._scene._useOrderIndependentTransparency;this._scene._useOrderIndependentTransparency=!0;const i=this._oitRenderer.render(e);i.length&&t._renderTransparent(i),this._scene._useOrderIndependentTransparency=s}}class Cc extends Sc{constructor(e,t){super(e,t),this.color=new Ke(.2,.2,.3,1),this.clearColor=!0,this.convertColorToLinearSpace=!1,this.clearDepth=!1,this.clearStencil=!1,this.stencilValue=0,this.outputTexture=this._frameGraph.textureManager.createDanglingHandle(),this.outputDepthTexture=this._frameGraph.textureManager.createDanglingHandle()}getClassName(){return"FrameGraphClearTextureTask"}record(e=!1){if(void 0===this.targetTexture&&void 0===this.depthTexture)throw new Error(`FrameGraphClearTextureTask ${this.name}: targetTexture and depthTexture can't both be undefined.`);const t=this._frameGraph.textureManager,s=void 0!==this.targetTexture?Array.isArray(this.targetTexture)?this.targetTexture:[this.targetTexture]:void 0;if(void 0!==this.targetTexture&&t.resolveDanglingHandle(this.outputTexture,s[0]),void 0!==this.depthTexture&&t.resolveDanglingHandle(this.outputDepthTexture,this.depthTexture),void 0!==this.targetTexture&&void 0!==this.depthTexture){const e=t.getTextureDescription(s[0]),i=t.getTextureDescription(this.depthTexture);if(e.size.width!==i.size.width||e.size.height!==i.size.height)throw new Error(`FrameGraphClearTextureTask ${this.name}: the depth texture (size: ${i.size.width}x${i.size.height}) and the target texture (size: ${e.size.width}x${e.size.height}) must have the same dimensions.`);const r=e.options.samples||1,n=i.options.samples||1;if(r!==n&&0!==r&&0!==n)throw new Error(`FrameGraphClearTextureTask ${this.name}: the depth texture (${n} samples) and the target texture (${r} samples) must have the same number of samples.`)}const i=this._frameGraph.engine.buildTextureLayout(s?Array(s.length).fill(!0):[],0===this.targetTexture&&!this._frameGraph.textureManager.backBufferTextureOverriden),r=Ye.Color4[0],n=this._frameGraph.addRenderPass(this.name);if(n.setRenderTarget(s),n.setRenderTargetDepth(this.depthTexture),n.setInitializeFunc(()=>{const e=n.frameGraphRenderTarget.renderTargetWrapper;e&&(e.disableAutomaticMSAAResolve=!0)}),n.setExecuteFunc(e=>{this._updateLayerAndFaceIndices(n),r.copyFrom(this.color),this.convertColorToLinearSpace&&r.toLinearSpaceToRef(r),e.clearAttachments(r,i,!!this.clearColor,!!this.clearDepth,!!this.clearStencil,this.stencilValue)}),!e){const e=this._frameGraph.addRenderPass(this.name+"_disabled",!0);e.setRenderTarget(s),e.setRenderTargetDepth(this.depthTexture),e.setExecuteFunc(e=>{})}return n}}class Oc extends Sl{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([import("./kernelBlur.fragment-B7PNt83k.esm.min.js"),import("./kernelBlur.vertex-CczLCJ3t.esm.min.js")]))):t.push(Promise.all([import("./kernelBlur.fragment-BulLAcSh.esm.min.js"),import("./kernelBlur.vertex-Bt2sRdNG.esm.min.js")]))}constructor(e,t=null,s,i,r){const n=!!r?.blockCompilation;super({...r,name:e,engine:t||ee.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:Oc.FragmentUrl,uniforms:Oc.Uniforms,samplers:Oc.Samplers,vertexUrl:Oc.VertexUrl,blockCompilation:!0}),this._packedFloat=!1,this._staticDefines="",this.textureWidth=0,this.textureHeight=0,this._staticDefines=r?Array.isArray(r.defines)?r.defines.join("\n"):r.defines||"":"",this.options.blockCompilation=n,void 0!==s&&(this.direction=s),void 0!==i&&(this.kernel=i)}set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this.options.blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this.options.blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}bind(e=!1){super.bind(e),this._drawWrapper.effect.setFloat2("delta",1/this.textureWidth*this.direction.x,1/this.textureHeight*this.direction.y)}_updateParameters(e,t){const s=this._kernel,i=(s-1)/2;let r=[],n=[],a=0;for(let e=0;e<s;e++){const t=e/(s-1),o=this._gaussianWeight(2*t-1);r[e]=e-i,n[e]=o,a+=o}for(let e=0;e<n.length;e++)n[e]/=a;const o=[],h=[],l=[];for(let e=0;e<=i;e+=2){const t=Math.min(e+1,Math.floor(i));if(e===t)l.push({o:r[e],w:n[e]});else{const s=t===i,a=n[e]+n[t]*(s?.5:1),o=r[e]+1/(1+n[e]/n[t]);0===o?(l.push({o:r[e],w:n[e]}),l.push({o:r[e+1],w:n[e+1]})):(l.push({o:o,w:a}),l.push({o:-o,w:a}))}}for(let e=0;e<l.length;e++)h[e]=l[e].o,o[e]=l[e].w;r=h,n=o;const c=this.options.engine.getCaps().maxVaryingVectors-(1===this.options.shaderLanguage?1:0),u=Math.max(c,0)-1;let d=Math.min(r.length,u),_="";_+=this._staticDefines,-1!=this._staticDefines.indexOf("DOF")&&(_+=`#define CENTER_WEIGHT ${this._glslFloat(n[d-1])}\n`,d--);for(let e=0;e<d;e++)_+=`#define KERNEL_OFFSET${e} ${this._glslFloat(r[e])}\n`,_+=`#define KERNEL_WEIGHT${e} ${this._glslFloat(n[e])}\n`;let p=0;for(let e=u;e<r.length;e++)_+=`#define KERNEL_DEP_OFFSET${p} ${this._glslFloat(r[e])}\n`,_+=`#define KERNEL_DEP_WEIGHT${p} ${this._glslFloat(n[e])}\n`,p++;this.packedFloat&&(_+="#define PACKEDFLOAT 1"),this.options.blockCompilation=!1,this.updateEffect(_,null,null,{varyingCount:d,depCount:p},e,t)}_nearestBestKernel(e){const t=Math.round(e);for(const e of[t,t-1,t+1,t-2,t+2])if(e%2!=0&&Math.floor(e/2)%2==0&&e>0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,s=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(s)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}}Oc.VertexUrl="kernelBlur",Oc.FragmentUrl="kernelBlur",Oc.Uniforms=["delta","direction"],Oc.Samplers=["circleOfConfusionSampler"];class Dc extends xc{get alphaMode(){return this.postProcess.alphaMode}set alphaMode(e){this.postProcess.alphaMode=e}get drawWrapper(){return this._postProcessDrawWrapper}constructor(e,t,s){super(e,t),this.sourceSamplingMode=dt.TEXTURE_BILINEAR_SAMPLINGMODE,this.depthReadOnly=!1,this.stencilReadOnly=!1,this.disableColorWrite=!1,this.drawBackFace=!1,this.depthTest=!0,this.postProcess=s,this._postProcessDrawWrapper=this.postProcess.drawWrapper,this.outputTexture=this._frameGraph.textureManager.createDanglingHandle(),this.outputDepthAttachmentTexture=this._frameGraph.textureManager.createDanglingHandle()}isReady(){return this.postProcess.isReady()}getClassName(){return"FrameGraphPostProcessTask"}record(e=!1,t,s){if(void 0===this.sourceTexture&&void 0===this.targetTexture)throw new Error(`FrameGraphPostProcessTask "${this.name}": sourceTexture or targetTexture is required`);const i=void 0!==this.sourceTexture?this._frameGraph.textureManager.getTextureCreationOptions(this.sourceTexture):void 0;if(i&&(i.options.samples=1),this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture,this.targetTexture,this.name,i),void 0!==this.depthAttachmentTexture&&this._frameGraph.textureManager.resolveDanglingHandle(this.outputDepthAttachmentTexture,this.depthAttachmentTexture),i){const e=this._frameGraph.textureManager.getTextureAbsoluteDimensions(i);this._sourceWidth=e.width,this._sourceHeight=e.height}const r=this._frameGraph.textureManager.getTextureDescription(this.outputTexture);this._outputWidth=r.size.width,this._outputHeight=r.size.height;const n=this._frameGraph.addRenderPass(this.name);if(n.depthReadOnly=this.depthReadOnly,n.stencilReadOnly=this.stencilReadOnly,n.addDependencies(this.sourceTexture),n.setRenderTarget(this.outputTexture),n.setRenderTargetDepth(this.depthAttachmentTexture),n.setExecuteFunc(e=>{e.pushDebugGroup(`Apply post-process (${this.name})`),void 0!==this.sourceTexture&&e.setTextureSamplingMode(this.sourceTexture,this.sourceSamplingMode),t?.(e),this.viewport&&e.setViewport(this.viewport),e.applyFullScreenEffect(this._postProcessDrawWrapper,()=>{void 0!==this.sourceTexture&&e.bindTextureHandle(this._postProcessDrawWrapper.effect,"textureSampler",this.sourceTexture),s?.(e),this.postProcess.bind()},this.stencilState,this.disableColorWrite,this.drawBackFace,this.depthTest,void 0!==this.viewport),e.restoreDefaultFramebuffer(),e.popDebugGroup()}),!e){const e=this._frameGraph.addRenderPass(this.name+"_disabled",!0);e.depthReadOnly=this.depthReadOnly,e.stencilReadOnly=this.stencilReadOnly,e.addDependencies(this.sourceTexture),e.setRenderTarget(this.outputTexture),e.setRenderTargetDepth(this.depthAttachmentTexture),e.setExecuteFunc(e=>{void 0!==this.sourceTexture&&this.alphaMode===dt.ALPHA_DISABLE&&(this.viewport&&e.setViewport(this.viewport),e.copyTexture(this.sourceTexture,void 0,void 0!==this.viewport))})}return n}dispose(){this.postProcess.dispose(),super.dispose()}}class wc extends Dc{constructor(e,t,s){super(e,t,s||new Oc(e,t.engine,new Me(1,0),10))}getClassName(){return"FrameGraphBlurTask"}record(e=!1,t,s){const i=super.record(e,t,s);return this.postProcess.textureWidth=this._outputWidth,this.postProcess.textureHeight=this._outputHeight,i}}function Lc(e){return void 0!==e.width}function Fc(e){return Lc(e)?{width:e.width,height:e.height}:{width:e,height:e}}var Nc,Bc;!function(e){e[e.Task=0]="Task",e[e.Graph=1]="Graph",e[e.External=2]="External"}(Nc||(Nc={}));class Uc{constructor(e,t=!1,s){this.engine=e,this._debugTextures=t,this._scene=s,this._textures=new Map,this._historyTextures=new Map,this._isRecordingTask=!1,this.showDebugLogsForTextureAllcationOptimization=!1,this._backBufferTextureEntry=null,this._backBufferDepthStencilTextureEntry=null,this._backBufferTextureOverriden=!1,this._addSystemTextures()}isBackbuffer(e){return!this._backBufferTextureOverriden&&this._isBackbuffer(e)}_isBackbuffer(e){if(0===e||1===e)return!0;const t=this._textures.get(e);return!!t&&(0===t.refHandle||1===t.refHandle)}isBackbufferColor(e){if(this._backBufferTextureOverriden)return!1;if(0===e)return!0;const t=this._textures.get(e);return!!t&&0===t.refHandle}isBackbufferDepthStencil(e){if(this._backBufferTextureOverriden)return!1;if(1===e)return!0;const t=this._textures.get(e);return!!t&&1===t.refHandle}isHistoryTexture(e,t=!1){const s=this._textures.get(e);return!!s&&(e=s.refHandle??e,t?!0===this._textures.get(e)?.historyTexture:this._historyTextures.has(e))}getTextureCreationOptions(e,t=!1){e=this._textures.get(e)?.refHandle??e;const s=this._textures.get(e),i=s.creationOptions;return{size:Lc(i.size)?{...i.size}:i.size,sizeIsPercentage:i.sizeIsPercentage,options:Uc.CloneTextureOptions(i.options,s.textureIndex),isHistoryTexture:!!t&&i.isHistoryTexture}}getTextureDescription(e){const t=this.getTextureCreationOptions(e);return{size:t.sizeIsPercentage?this.getAbsoluteDimensions(t.size):Lc(t.size)?t.size:{width:t.size,height:t.size},options:t.options}}getTextureHandleOrCreateTexture(e,t,s){if(void 0===e){if(void 0===t||void 0===s)throw new Error("getTextureHandleOrCreateTexture: Either handle or newTextureName and creationOptions must be provided.");return this.createRenderTargetTexture(t,s)}return e}getTextureFromHandle(e,t){const s=this._textures.get(e),i=s?.refHandle,r=void 0!==i?this._textures.get(i):s,n=void 0!==i?i:e,a=this._historyTextures.get(n);return a?a.textures[t?a.index:1^a.index]:r.texture}importTexture(e,t,s){void 0!==s&&this._freeEntry(s);const i={size:{width:t.width,height:t.height},sizeIsPercentage:!1,isHistoryTexture:!1,options:{createMipMaps:t.generateMipMaps,samples:t.samples,types:[t.type],formats:[t.format],useSRGBBuffers:[t._useSRGBBuffer],creationFlags:[t._creationFlags],labels:t.label?[t.label]:["imported"]}};return this._createHandleForTexture(e,t,i,Nc.External,s)}createRenderTargetTexture(e,t,s){return this._createHandleForTexture(e,null,{size:Lc(t.size)?{...t.size}:t.size,sizeIsPercentage:t.sizeIsPercentage,isHistoryTexture:t.isHistoryTexture,options:Uc.CloneTextureOptions(t.options,void 0,!0)},this._isRecordingTask?Nc.Task:Nc.Graph,s)}createRenderTarget(e,t,s,i,r){const n=new Ic(e,this,t,s),a=n.renderTargetWrapper;if(void 0!==a&&(a.depthReadOnly=!!i,a.stencilReadOnly=!!r,t)){const e=Array.isArray(t)?t:[t];for(let t=0;t<e.length;t++){let s=e[t];s=this._textures.get(s)?.refHandle??s;const i=this._historyTextures.get(s);i&&(i.references.push({renderTargetWrapper:a,textureIndex:t}),a.setTexture(i.textures[i.index],t,!1))}}return n}createDanglingHandle(){return Uc._Counter++}resolveDanglingHandle(e,t,s,i){if(void 0===t){if(void 0===s||void 0===i)throw new Error("resolveDanglingHandle: Either handle or newTextureName and creationOptions must be provided.");return void this.createRenderTargetTexture(s,i,e)}const r=this._textures.get(t);if(void 0===r)throw new Error(`resolveDanglingHandle: Handle ${t} does not exist!`);t=r.refHandle??t,this._textures.set(e,{texture:r.texture,refHandle:t,name:r.name,creationOptions:{size:{...r.creationOptions.size},options:Uc.CloneTextureOptions(r.creationOptions.options),sizeIsPercentage:r.creationOptions.sizeIsPercentage,isHistoryTexture:!1},namespace:r.namespace,textureIndex:r.textureIndex})}getAbsoluteDimensions(e,t,s){if(this._backBufferTextureOverriden){const e=this._textures.get(0).creationOptions.size;t??=e.width,s??=e.height}else t??=this.engine.getRenderWidth(!0),s??=this.engine.getRenderHeight(!0);const{width:i,height:r}=Fc(e);return{width:Math.floor(i*t/100),height:Math.floor(r*s/100)}}getTextureAbsoluteDimensions(e){return"number"==typeof e&&(e=this.getTextureCreationOptions(e)),e.sizeIsPercentage?this.getAbsoluteDimensions(e.size):Lc(e.size)?e.size:{width:e.size,height:e.size}}computeTotalTextureSize(e,t,s){let i=0;return this._textures.forEach((r,n)=>{if(!this._backBufferTextureOverriden&&(0===n||1===n)||void 0!==r.refHandle)return;if(e&&void 0!==r.aliasHandle)return;const a=r.creationOptions,o=r.textureIndex||0,h=a.sizeIsPercentage?this.getAbsoluteDimensions(a.size,t,s):Fc(a.size),l=Uc._GetTextureBlockInformation(a.options.types?.[o]??dt.TEXTURETYPE_UNSIGNED_BYTE,a.options.formats[o]),c=Math.ceil(h.width/l.width)*Math.ceil(h.height/l.height)*l.length;let u=c;a.options.createMipMaps&&(u=Math.floor(4*u/3)),(a.options.samples||1)>1&&(u+=c),i+=u}),i}get backBufferTextureOverriden(){return this._backBufferTextureOverriden}setBackBufferTextures(e,t,s,i){if(!(0!==e&&0!==t||s&&i)){if(this._backBufferTextureOverriden){let e=this._textures.get(0);e.texture?.dispose(),e.texture=null,e.debug?.dispose(),e.debug=void 0,e=this._textures.get(1),e.texture?.dispose(),e.texture=null,e.debug?.dispose(),e.debug=void 0}return this._backBufferTextureEntry=null,this._backBufferDepthStencilTextureEntry=null,this._backBufferTextureOverriden=!1,void this._addSystemTextures()}this._backBufferTextureOverriden=!0;const r={width:e,height:t};this._backBufferTextureEntry={name:"backbuffer color",texture:null,creationOptions:s??{size:r,options:{createMipMaps:!1,samples:this.engine.getCreationOptions().antialias?4:1,types:[dt.TEXTURETYPE_UNSIGNED_BYTE],formats:[dt.TEXTUREFORMAT_RGBA],useSRGBBuffers:[!1],creationFlags:[0],labels:["backbuffer color"]},sizeIsPercentage:!1},namespace:Nc.Graph,lifespan:{firstTask:Number.MAX_VALUE,lastTask:0}},this._backBufferTextureEntry.textureDescriptionHash=this._createTextureDescriptionHash(this._backBufferTextureEntry.creationOptions),this._backBufferDepthStencilTextureEntry={name:"backbuffer depth/stencil",texture:null,creationOptions:i??{size:r,options:{createMipMaps:!1,samples:this.engine.getCreationOptions().antialias?4:1,types:[dt.TEXTURETYPE_UNSIGNED_BYTE],formats:[this.engine.isStencilEnable?dt.TEXTUREFORMAT_DEPTH24_STENCIL8:dt.TEXTUREFORMAT_DEPTH32_FLOAT],useSRGBBuffers:[!1],creationFlags:[0],labels:["backbuffer depth/stencil"]},sizeIsPercentage:!1},namespace:Nc.Graph,lifespan:{firstTask:Number.MAX_VALUE,lastTask:0}},this._backBufferDepthStencilTextureEntry.textureDescriptionHash=this._createTextureDescriptionHash(this._backBufferDepthStencilTextureEntry.creationOptions),this._addSystemTextures()}resetBackBufferTextures(){this.setBackBufferTextures(0,0)}get hasHistoryTextures(){return this._historyTextures.size>0}_dispose(){this._releaseTextures()}_allocateTextures(e){e&&this._optimizeTextureAllocation(e),this._textures.forEach(e=>{if(!e.texture)if(void 0!==e.refHandle){const t=this._textures.get(e.refHandle);e.texture=t.texture,e.texture?.incrementReferences(),0===t.refHandle&&(e.refHandle=0),1===t.refHandle&&(e.refHandle=1)}else if(e.namespace!==Nc.External)if(void 0!==e.aliasHandle){const t=this._textures.get(e.aliasHandle);e.texture=t.texture,e.texture.incrementReferences()}else{const t=e.creationOptions,s=Fc(t.sizeIsPercentage?this.getAbsoluteDimensions(t.size):t.size),i=e.textureIndex||0,r=t.options.targetTypes?.[i]??dt.TEXTURE_2D,n=r===dt.TEXTURE_3D,a=r===dt.TEXTURE_2D_ARRAY||r===dt.TEXTURE_CUBE_MAP_ARRAY,o=t.options.layerCounts?.[i]??0,h={createMipMaps:t.options.createMipMaps,samples:t.options.samples,type:t.options.types?.[i],format:t.options.formats?.[i],useSRGBBuffer:t.options.useSRGBBuffers?.[i],creationFlags:t.options.creationFlags?.[i],label:t.options.labels?.[i]??`${e.name}${i>0?"#"+i:""}`,samplingMode:dt.TEXTURE_NEAREST_SAMPLINGMODE,createMSAATexture:t.options.samples>1,isCube:r===dt.TEXTURE_CUBE_MAP||r===dt.TEXTURE_CUBE_MAP_ARRAY},l=Di(h.format),c=Li(h.format),u=l&&c?12:l||c?14:5,d=this.engine._createInternalTexture({width:s.width,height:s.height,depth:n?o:void 0,layers:a?o:void 0},h,!1,u);l&&(d.type=wi(d.format)),e.texture=d}e.texture&&void 0===e.refHandle&&(e.debug?.dispose(),e.debug=this._createDebugTexture(e.name,e.texture))}),this._historyTextures.forEach(e=>{for(let t=0;t<e.handles.length;t++)e.textures[t]=this._textures.get(e.handles[t]).texture})}_releaseTextures(e=!0){this._textures.forEach((t,s)=>{t.lifespan&&(t.lifespan.firstTask=Number.MAX_VALUE,t.lifespan.lastTask=0),t.aliasHandle=void 0,(e||t.namespace!==Nc.External)&&(t.debug?.dispose(),t.debug=void 0),t.namespace!==Nc.External&&(t.texture?.dispose(),t.texture=null,(e||t.namespace===Nc.Task)&&(this._textures.delete(s),this._historyTextures.delete(s)))}),this._historyTextures.forEach(e=>{for(let t=0;t<e.handles.length;t++)e.textures[t]=null}),e&&(this._textures.clear(),this._historyTextures.clear(),this._addSystemTextures())}_updateHistoryTextures(){this._historyTextures.forEach(e=>{e.index=1^e.index;const t=e.textures[e.index];if(t)for(const{renderTargetWrapper:s,textureIndex:i}of e.references)s.setTexture(t,i,!1)})}_addSystemTextures(){const e={width:this.engine.getRenderWidth(!0),height:this.engine.getRenderHeight(!0)};this._textures.set(0,this._backBufferTextureEntry??{name:"backbuffer color",texture:null,creationOptions:{size:e,options:{createMipMaps:!1,samples:this.engine.getCreationOptions().antialias?4:1,types:[dt.TEXTURETYPE_UNSIGNED_BYTE],formats:[dt.TEXTUREFORMAT_RGBA],useSRGBBuffers:[!1],creationFlags:[0],labels:["backbuffer color"]},sizeIsPercentage:!1},namespace:Nc.External}),this._textures.set(1,this._backBufferDepthStencilTextureEntry??{name:"backbuffer depth/stencil",texture:null,creationOptions:{size:e,options:{createMipMaps:!1,samples:this.engine.getCreationOptions().antialias?4:1,types:[dt.TEXTURETYPE_UNSIGNED_BYTE],formats:[dt.TEXTUREFORMAT_DEPTH24],useSRGBBuffers:[!1],creationFlags:[0],labels:["backbuffer depth/stencil"]},sizeIsPercentage:!1},namespace:Nc.External})}_createDebugTexture(e,t){if(!this._debugTextures)return;const s=new Ch(null,this._scene);return s.name=e,s._texture=t,s._texture.incrementReferences(),s}_freeEntry(e){const t=this._textures.get(e);t&&(t.debug?.dispose(),this._textures.delete(e))}_createHandleForTexture(e,t,s,i,r,n){r=r??Uc._Counter++,n=n||0;const a=s.isHistoryTexture?`${e} ping`:e;let o=s.options.labels?.[n]??"";o===a&&(o="");const h={texture:t,name:`${a}${o?" "+o:""}`,creationOptions:{size:Lc(s.size)?s.size:{width:s.size,height:s.size},options:s.options,sizeIsPercentage:s.sizeIsPercentage,isHistoryTexture:s.isHistoryTexture},namespace:i,textureIndex:n,textureDescriptionHash:this._createTextureDescriptionHash(s),lifespan:{firstTask:Number.MAX_VALUE,lastTask:0},historyTexture:s.isHistoryTexture};if(this._textures.set(r,h),i===Nc.External)return r;if(s.isHistoryTexture){const t={size:{...h.creationOptions.size},options:{...h.creationOptions.options},sizeIsPercentage:h.creationOptions.sizeIsPercentage,isHistoryTexture:!1},s=this._createHandleForTexture(`${e} pong`,null,t,i);return this._textures.get(s).historyTexture=!0,this._historyTextures.set(r,{textures:[null,null],handles:[r,s],index:0,references:[]}),r}if(s.options.types&&s.options.types.length>1&&0===n){const e=s.options.types.length,t={size:Lc(s.size)?s.size:{width:s.size,height:s.size},options:s.options,sizeIsPercentage:s.sizeIsPercentage};for(let s=1;s<e;s++)this._createHandleForTexture(a,null,t,i,r+s,s);Uc._Counter+=e-1}return r}_createTextureDescriptionHash(e){const t=[];return t.push(Lc(e.size)?`${e.size.width}_${e.size.height}`:`${e.size}`),t.push(e.sizeIsPercentage?"%":"A"),t.push(e.options.createMipMaps?"M":"N"),t.push(e.options.samples?`${e.options.samples}`:"S1"),t.push(e.options.targetTypes?e.options.targetTypes.join("_"):`${dt.TEXTURE_2D}`),t.push(e.options.types?e.options.types.join("_"):`${dt.TEXTURETYPE_UNSIGNED_BYTE}`),t.push(e.options.formats?e.options.formats.join("_"):`${dt.TEXTUREFORMAT_RGBA}`),t.push(e.options.layerCounts?e.options.layerCounts.join("_"):"0"),t.push(e.options.useSRGBBuffers?e.options.useSRGBBuffers.join("_"):"false"),t.push(e.options.creationFlags?e.options.creationFlags.join("_"):"0"),t.join("_")}_optimizeTextureAllocation(e){this._computeTextureLifespan(e),this.showDebugLogsForTextureAllcationOptimization&&a.Log("================== Optimization of texture allocation ==================");const t=new Map,s=this._textures.keys();for(let e=s.next();!0!==e.done;e=s.next()){const s=e.value,i=this._textures.get(s);if(void 0!==i.refHandle||i.namespace===Nc.External||this.isHistoryTexture(s,!0))continue;const r=i.textureDescriptionHash,n=i.lifespan,o=t.get(r);if(o){let e=!1;for(const t of o){const[r,o]=t;let h=!1;for(const e of o)if(e.firstTask<=n.lastTask&&e.lastTask>=n.firstTask){h=!0;break}if(!h){this.showDebugLogsForTextureAllcationOptimization&&a.Log(`Texture ${s} (${i.name}) reuses cache entry ${r}`),o.push(n),i.aliasHandle=r,e=!0;break}}e||o.push([s,[n]])}else t.set(r,[[s,[n]]])}}_computeTextureLifespan(e){this.showDebugLogsForTextureAllcationOptimization&&a.Log("================== Dump of texture dependencies for all tasks/passes ==================");for(let t=0;t<e.length;++t){const s=e[t];s.passes.length>0&&this._computeTextureLifespanForPasses(s,t,s.passes),s.passesDisabled.length>0&&this._computeTextureLifespanForPasses(s,t,s.passesDisabled),s.dependencies&&(this.showDebugLogsForTextureAllcationOptimization&&a.Log(`task#${t} (${s.name}), global dependencies`),this._updateLifespan(100*t+99,s.dependencies))}if(this.showDebugLogsForTextureAllcationOptimization){a.Log("================== Texture lifespans ==================");const e=this._textures.keys();for(let t=e.next();!0!==t.done;t=e.next()){const e=t.value,s=this._textures.get(e);void 0!==s.refHandle||s.namespace===Nc.External||this._historyTextures.has(e)||a.Log(`${e} (${s.name}): ${s.lifespan.firstTask} - ${s.lifespan.lastTask}`)}}}_computeTextureLifespanForPasses(e,t,s){for(let i=0;i<s.length;++i){const r=new Set,n=s[i];Mc.IsRenderPass(n)&&(n.collectDependencies(r),this.showDebugLogsForTextureAllcationOptimization&&a.Log(`task#${t} (${e.name}), pass#${i} (${n.name})`),this._updateLifespan(100*t+i,r))}}_updateLifespan(e,t){const s=t.keys();for(let t=s.next();!0!==t.done;t=s.next()){const s=t.value;if(this.isBackbuffer(s))continue;let i=this._textures.get(s);if(!i)throw new Error(`FrameGraph._computeTextureLifespan: Texture handle "${s}" not found in the texture manager. Make sure you didn't forget to add a task in the frame graph.`);let r=s;for(;void 0!==i.refHandle;)if(r=i.refHandle,i=this._textures.get(r),!i)throw new Error(`FrameGraph._computeTextureLifespan: Texture handle "${r}" not found in the texture manager (source handle="${s}"). Make sure you didn't forget to add a task in the frame graph.`);i.namespace===Nc.External||this._historyTextures.has(r)||(this.showDebugLogsForTextureAllcationOptimization&&a.Log(` ${r} (${i.name})`),i.lifespan.firstTask=Math.min(i.lifespan.firstTask,e),i.lifespan.lastTask=Math.max(i.lifespan.lastTask,e))}}static CloneTextureOptions(e,t,s){return void 0!==t?{createMipMaps:e.createMipMaps,samples:e.samples,targetTypes:e.targetTypes?[e.targetTypes[t]]:void 0,types:e.types?[e.types[t]]:void 0,formats:e.formats?[e.formats[t]]:void 0,layerCounts:e.layerCounts?[e.layerCounts[t]]:void 0,useSRGBBuffers:e.useSRGBBuffers?[e.useSRGBBuffers[t]]:void 0,creationFlags:e.creationFlags?[e.creationFlags[t]]:void 0,labels:e.labels?[e.labels[t]]:void 0}:{createMipMaps:e.createMipMaps,samples:e.samples,targetTypes:e.targetTypes?[...e.targetTypes]:void 0,types:e.types?[...e.types]:void 0,formats:e.formats?[...e.formats]:void 0,layerCounts:e.layerCounts?[...e.layerCounts]:void 0,useSRGBBuffers:e.useSRGBBuffers?[...e.useSRGBBuffers]:void 0,creationFlags:e.creationFlags?[...e.creationFlags]:void 0,labels:e.labels&&s?[...e.labels]:void 0}}static _GetTextureBlockInformation(e,t){switch(t){case dt.TEXTUREFORMAT_DEPTH16:return{width:1,height:1,length:2};case dt.TEXTUREFORMAT_DEPTH24:return{width:1,height:1,length:3};case dt.TEXTUREFORMAT_DEPTH24_STENCIL8:case dt.TEXTUREFORMAT_DEPTH32_FLOAT:return{width:1,height:1,length:4};case dt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8:return{width:1,height:1,length:5};case dt.TEXTUREFORMAT_STENCIL8:return{width:1,height:1,length:1};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM:case dt.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT:case dt.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT:case dt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5:case dt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3:return{width:4,height:4,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1:case dt.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1:return{width:4,height:4,length:8};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4:return{width:4,height:4,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_5x4:return{width:5,height:4,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_5x5:return{width:5,height:5,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_6x5:return{width:6,height:5,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_6x6:return{width:6,height:6,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x5:return{width:8,height:5,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x6:return{width:8,height:6,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x8:return{width:8,height:8,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x5:return{width:10,height:5,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x6:return{width:10,height:6,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x8:return{width:10,height:8,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x10:return{width:10,height:10,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_12x10:return{width:12,height:10,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_12x12:return{width:12,height:12,length:16};case dt.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL:case dt.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2:return{width:4,height:4,length:8};case dt.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC:return{width:4,height:4,length:16}}switch(e){case dt.TEXTURETYPE_BYTE:case dt.TEXTURETYPE_UNSIGNED_BYTE:switch(t){case dt.TEXTUREFORMAT_R:case dt.TEXTUREFORMAT_R_INTEGER:case dt.TEXTUREFORMAT_ALPHA:case dt.TEXTUREFORMAT_LUMINANCE:return{width:1,height:1,length:1};case dt.TEXTUREFORMAT_RG:case dt.TEXTUREFORMAT_RG_INTEGER:case dt.TEXTUREFORMAT_LUMINANCE_ALPHA:return{width:1,height:1,length:2};case dt.TEXTUREFORMAT_RGB:case dt.TEXTUREFORMAT_RGB_INTEGER:return{width:1,height:1,length:3};case dt.TEXTUREFORMAT_RGBA_INTEGER:default:return{width:1,height:1,length:4}}case dt.TEXTURETYPE_SHORT:case dt.TEXTURETYPE_UNSIGNED_SHORT:switch(t){case dt.TEXTUREFORMAT_RED_INTEGER:return{width:1,height:1,length:2};case dt.TEXTUREFORMAT_RG_INTEGER:return{width:1,height:1,length:4};case dt.TEXTUREFORMAT_RGB_INTEGER:return{width:1,height:1,length:6};case dt.TEXTUREFORMAT_RGBA_INTEGER:default:return{width:1,height:1,length:8}}case dt.TEXTURETYPE_INT:case dt.TEXTURETYPE_UNSIGNED_INTEGER:switch(t){case dt.TEXTUREFORMAT_RED_INTEGER:return{width:1,height:1,length:4};case dt.TEXTUREFORMAT_RG_INTEGER:return{width:1,height:1,length:8};case dt.TEXTUREFORMAT_RGB_INTEGER:return{width:1,height:1,length:12};case dt.TEXTUREFORMAT_RGBA_INTEGER:default:return{width:1,height:1,length:16}}case dt.TEXTURETYPE_FLOAT:switch(t){case dt.TEXTUREFORMAT_RED:return{width:1,height:1,length:4};case dt.TEXTUREFORMAT_RG:return{width:1,height:1,length:8};case dt.TEXTUREFORMAT_RGB:return{width:1,height:1,length:12};case dt.TEXTUREFORMAT_RGBA:default:return{width:1,height:1,length:16}}case dt.TEXTURETYPE_HALF_FLOAT:switch(t){case dt.TEXTUREFORMAT_RED:return{width:1,height:1,length:2};case dt.TEXTUREFORMAT_RG:return{width:1,height:1,length:4};case dt.TEXTUREFORMAT_RGB:return{width:1,height:1,length:6};case dt.TEXTUREFORMAT_RGBA:default:return{width:1,height:1,length:8}}case dt.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return{width:1,height:1,length:2};case dt.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:case dt.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:switch(t){case dt.TEXTUREFORMAT_RGBA:case dt.TEXTUREFORMAT_RGBA_INTEGER:}return{width:1,height:1,length:4};case dt.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:case dt.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return{width:1,height:1,length:2};case dt.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:switch(t){case dt.TEXTUREFORMAT_RGBA:case dt.TEXTUREFORMAT_RGBA_INTEGER:}return{width:1,height:1,length:4}}return{width:1,height:1,length:4}}}Uc._Counter=2;class kc extends Sl{constructor(e,t=null,s,i,r){super({...r,name:e,engine:t||ee.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:kc.FragmentUrl,uniforms:kc.Uniforms}),this.direction=s,this.kernel=i,this.textureWidth=0,this.textureHeight=0}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(import("./glowBlurPostProcess.fragment-BZQ7tZn9.esm.min.js"))):t.push(import("./glowBlurPostProcess.fragment-C_j2_dYh.esm.min.js")),super._gatherImports(e,t)}bind(){super.bind(),this._drawWrapper.effect.setFloat2("screenSize",this.textureWidth,this.textureHeight),this._drawWrapper.effect.setVector2("direction",this.direction),this._drawWrapper.effect.setFloat("blurWidth",this.kernel)}}kc.FragmentUrl="glowBlurPostProcess",kc.Uniforms=["screenSize","direction","blurWidth"];class Gc extends xc{isReady(){return!this.customIsReady||this.customIsReady()}constructor(e,t){super(e,t)}getClassName(){return"FrameGraphExecuteTask"}record(){if(!this.func)throw new Error("FrameGraphExecuteTask: Execute task must have a function.");const e=this._frameGraph.addPass(this.name);e.setExecuteFunc(e=>{this.func(e)});return this._frameGraph.addPass(this.name+"_disabled",!0).setExecuteFunc(e=>{this.funcDisabled?.(e)}),e}}!function(e){e.None="none",e.Standard="standard",e.Glow="glow"}(Bc||(Bc={}));class Vc extends Dc{constructor(e,t,s){super(e,t,s||new kc(e,t.engine,new Me(1,0),1))}getClassName(){return"FrameGraphGlowBlurTask"}record(e=!1,t,s){const i=super.record(e,t,s);return this.postProcess.textureWidth=this._outputWidth,this.postProcess.textureHeight=this._outputHeight,i}}class Hc extends xc{get name(){return this._name}set name(e){if(this._name=e,this._blurX)for(let t=0;t<this._blurX.length;t++)this._blurX[t].name=`${e} Blur X${t}`,this._blurY[t].name=`${e} Blur Y${t}`;this._clearLayerTextureTask&&(this._clearLayerTextureTask.name=e+" Clear Layer"),this._objectRendererForLayerTask&&(this._objectRendererForLayerTask.name=e+" Render to Layer")}get objectRendererForLayer(){return this._objectRendererForLayerTask}constructor(e,t,s,i,r,n="standard",a=!1,o=!1,h=!0){if(super(e,t),this._blurType=n,this._setRenderTargetDepth=a,this._notifyBlurObservable=o,this._setObjectList=h,this._blurX=[],this._blurY=[],this._onBeforeBlurTask=null,this._onAfterBlurTask=null,this._onBeforeObservableObserver=null,this._onBeforeObservableObserver2=null,this._onAfterObservableObserver=null,this._onAfterRenderingGroupObserver=null,this._scene=s,this._engine=s.getEngine(),this.layer=i,"none"!==this._blurType)for(let t=0;t<r;t++)"glow"===this._blurType?(this._blurX.push(new Vc(`${e} Blur X${t}`,this._frameGraph,this.layer._postProcesses[1+2*t+0])),this._blurY.push(new Vc(`${e} Blur Y${t}`,this._frameGraph,this.layer._postProcesses[1+2*t+1]))):(this._blurX.push(new wc(`${e} Blur X${t}`,this._frameGraph,this.layer._postProcesses[2*t+0])),this._blurY.push(new wc(`${e} Blur Y${t}`,this._frameGraph,this.layer._postProcesses[2*t+1])));this._clearLayerTextureTask=new Cc(e+" Clear Layer",t),this._clearLayerTextureTask.clearColor=!0,this._clearLayerTextureTask.clearDepth=!0,this._objectRendererForLayerTask=new Pc(e+" Render to Layer",t,s,void 0,this.layer.objectRenderer),"none"!==this._blurType&&this._notifyBlurObservable&&(this._onBeforeBlurTask=new Gc(e+" On Before Blur",t),this._onAfterBlurTask=new Gc(e+" On After Blur",t),this._onBeforeBlurTask.func=()=>{this.layer.onBeforeBlurObservable.hasObservers()&&this.layer.onBeforeBlurObservable.notifyObservers(this.layer)},this._onAfterBlurTask.func=()=>{this.layer.onAfterBlurObservable.hasObservers()&&this.layer.onAfterBlurObservable.notifyObservers(this.layer)}),this.outputTexture=this._frameGraph.textureManager.createDanglingHandle()}isReady(){return this._objectRendererForLayerTask.isReady()&&this.layer.isLayerReady()}getClassName(){return"FrameGraphBaseLayerTask"}record(e,t){if(void 0===this.targetTexture||void 0===this.objectRendererTask)throw new Error(`${this.constructor.name} "${this.name}": targetTexture and objectRendererTask are required`);let s,i,r;if(this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture,this.targetTexture),this.layerTexture)r=this.layerTexture,i=this._frameGraph.textureManager.getTextureCreationOptions(this.layerTexture),s=Fc(i.size),i.size=s;else{const e=this._frameGraph.textureManager.getTextureCreationOptions(this.targetTexture),t=this.layer._options.mainTextureFixedSize?Math.max(2,this.layer._options.mainTextureFixedSize):0;s=Fc(e.size),s.width=t||Math.floor(s.width*(this.layer._options.mainTextureRatio||.1))||1,s.height=t||Math.floor(s.height*(this.layer._options.mainTextureRatio||.1))||1,i={size:s,options:{createMipMaps:!1,types:[this.layer._options.mainTextureType],formats:[this.layer._options.mainTextureFormat],samples:1,useSRGBBuffers:[!1],creationFlags:[0]},sizeIsPercentage:!this.layer._options.mainTextureFixedSize&&e.sizeIsPercentage},r=this._frameGraph.textureManager.createRenderTargetTexture(`${this.name} Color`,i)}this._layerTextureDimensions=this._frameGraph.textureManager.getTextureAbsoluteDimensions(i);const n={size:s,options:Uc.CloneTextureOptions(i.options),sizeIsPercentage:i.sizeIsPercentage};n.options.formats[0]=dt.TEXTUREFORMAT_DEPTH32_FLOAT;const a=this._frameGraph.textureManager.createRenderTargetTexture(`${this.name} Depth`,n);this._clearLayerTextureTask.targetTexture=r,this._clearLayerTextureTask.depthTexture=a,this._clearLayerTextureTask.color=this.layer.neutralColor,this._clearLayerTextureTask.clearDepth=!0;const o=this._clearLayerTextureTask.record(!0);this._objectRendererForLayerTask.targetTexture=this._clearLayerTextureTask.outputTexture,this._objectRendererForLayerTask.depthTexture=this._clearLayerTextureTask.outputDepthTexture,this._objectRendererForLayerTask.camera=this.objectRendererTask.camera,this._setObjectList&&(this._objectRendererForLayerTask.objectList=this.objectRendererTask.objectList),this._objectRendererForLayerTask.disableShadows=!0;const h=this._objectRendererForLayerTask.record(!0);let l,c;if("none"!==this._blurType){let e;e=this._engine.getCaps().textureHalfFloatRender?dt.TEXTURETYPE_HALF_FLOAT:dt.TEXTURETYPE_UNSIGNED_BYTE,i.options.types[0]=e;const t=void 0!==this.layer._options.blurTextureSizeRatio?this.layer._options.blurTextureSizeRatio||.1:void 0;void 0!==t&&(s.width=Math.floor(s.width*t)||1,s.height=Math.floor(s.height*t)||1),l=this._onBeforeBlurTask?.record();const r=[];for(let e=0;e<this._blurX.length;e++){const t=this._frameGraph.textureManager.createRenderTargetTexture(this._blurX[e].name,i);this._blurX[e].sourceTexture=0===e?this._objectRendererForLayerTask.outputTexture:this._blurY[e-1].outputTexture,this._blurX[e].sourceSamplingMode=dt.TEXTURE_BILINEAR_SAMPLINGMODE,this._blurX[e].targetTexture=t,r.push(this._blurX[e].record(!0));const n=this._frameGraph.textureManager.createRenderTargetTexture(this._blurY[e].name,i);this._blurY[e].sourceTexture=this._blurX[e].outputTexture,this._blurY[e].sourceSamplingMode=dt.TEXTURE_BILINEAR_SAMPLINGMODE,this._blurY[e].targetTexture=n,r.push(this._blurY[e].record(!0)),s.width=s.width>>1,s.height=s.height>>1}c=this._onAfterBlurTask?.record(),this.objectRendererTask.objectRenderer.onBeforeRenderObservable.remove(this._onBeforeObservableObserver2),this._onBeforeObservableObserver2=this.objectRendererTask.objectRenderer.onBeforeRenderObservable.add(()=>{const e=this.layer.shouldRender();l&&(l.disabled=!e);for(let t=0;t<r.length;t++)r[t].disabled=!e;c&&(c.disabled=!e)})}this.objectRendererTask.objectRenderer.onBeforeRenderObservable.remove(this._onBeforeObservableObserver),this._onBeforeObservableObserver=this.objectRendererTask.objectRenderer.onBeforeRenderObservable.add(()=>{const e=this.layer.shouldRender();o.disabled=!e,h.disabled=!e,e&&this.layer.needStencil()&&(this._engine.setStencilBuffer(!0),this._engine.setStencilFunctionReference(1))}),this.objectRendererTask.objectRenderer.onAfterRenderObservable.remove(this._onAfterObservableObserver),this._onAfterObservableObserver=this.objectRendererTask.objectRenderer.onAfterRenderObservable.add(()=>{this.layer.shouldRender()&&this.layer.needStencil()&&this._engine.setStencilBuffer(!1)}),this.layer.bindTexturesForCompose=void 0,this._clearAfterRenderingGroupObserver();const u=this._frameGraph.addRenderPass(this.name);for(let e=0;e<this._blurY.length;e++)u.addDependencies(this._blurY[e].outputTexture);u.setRenderTarget(this.outputTexture),this._setRenderTargetDepth&&u.setRenderTargetDepth(this.objectRendererTask.depthTexture),u.setInitializeFunc(e=>{this.layer.bindTexturesForCompose=s=>{for(let t=0;t<this._blurY.length;t++)e.bindTextureHandle(s,`textureSampler${t>0?t+1:""}`,this._blurY[t].outputTexture);t?.(e,s)},-1!==this.layer._options.renderingGroupId&&(this._onAfterRenderingGroupObserver=this._scene.onAfterRenderingGroupObservable.add(t=>{this.layer.shouldRender()&&t.renderingGroupId===this.layer._options.renderingGroupId&&t.renderingManager===this.objectRendererTask.objectRenderer.renderingManager&&(this._setObjectList&&(this._objectRendererForLayerTask.objectList=this.objectRendererTask.objectList),e.saveDepthStates(),e.setDepthStates(!1,!1),e._applyRenderTarget(),this.layer.compose(),e.restoreDepthStates())}))}),u.setExecuteFunc(e=>{this._blurY.length>0&&e.setTextureSamplingMode(this._blurY[this._blurY.length-1].targetTexture,dt.TEXTURE_BILINEAR_SAMPLINGMODE),-1===this.layer._options.renderingGroupId&&this.layer.shouldRender()&&(this._setObjectList&&(this._objectRendererForLayerTask.objectList=this.objectRendererTask.objectList),e.setDepthStates(!1,!1),e._applyRenderTarget(),this.layer.compose())});const d=this._frameGraph.addRenderPass(this.name+"_disabled",!0);d.setRenderTarget(this.outputTexture),this._setRenderTargetDepth&&d.setRenderTargetDepth(this.objectRendererTask.depthTexture),d.setExecuteFunc(e=>{})}_clearAfterRenderingGroupObserver(){this._scene.onAfterRenderingGroupObservable.remove(this._onAfterRenderingGroupObserver),this._onAfterRenderingGroupObserver=null}dispose(){this._clearAfterRenderingGroupObserver(),this._clearLayerTextureTask.dispose(),this._objectRendererForLayerTask.dispose(),this._onBeforeBlurTask?.dispose(),this._onAfterBlurTask?.dispose(),this.layer.dispose();for(let e=0;e<this._blurX.length;e++)this._blurX[e].dispose(),this._blurY[e].dispose();super.dispose()}}class zc{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new ho("shared gizmo light",new xe(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Xe.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==zc._DefaultUtilityLayer?zc._CreateDefaultUtilityLayerFromScene(ee.LastCreatedScene):zc._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return zc._DefaultUtilityLayer=new zc(e),zc._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{zc._DefaultUtilityLayer=null}),zc._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==zc._DefaultKeepDepthUtilityLayer?zc._CreateDefaultKeepUtilityLayerFromScene(ee.LastCreatedScene):zc._DefaultKeepDepthUtilityLayer}static _CreateDefaultKeepUtilityLayerFromScene(e){return zc._DefaultKeepDepthUtilityLayer=new zc(e),zc._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,zc._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{zc._DefaultKeepDepthUtilityLayer=null}),zc._DefaultKeepDepthUtilityLayer}constructor(e,t=!0,s=!1){this.originalScene=e,this.handleEvents=t,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new c,this.utilityLayerScene=new Qo(e.getEngine(),{virtual:!0,useFloatingOrigin:e.floatingOriginMode}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add(t=>{if(!this.utilityLayerScene.activeCamera)return;if(!this.pickingEnabled)return;if(!this.processAllEvents&&t.type!==Yn.POINTERMOVE&&t.type!==Yn.POINTERUP&&t.type!==Yn.POINTERDOWN&&t.type!==Yn.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const s=t.event;if(e.isPointerCaptured(s.pointerId))return void(this._pointerCaptures[s.pointerId]=!1);const i=s=>{let i;if(t.nearInteractionPickingInfo)i=t.nearInteractionPickingInfo.pickedMesh.getScene()==s?t.nearInteractionPickingInfo:new ur;else if(s!==this.utilityLayerScene&&t.originalPickingInfo)i=t.originalPickingInfo;else{let r=null;this._renderCamera&&(r=s._activeCamera,s._activeCamera=this._renderCamera,t.ray=null),i=t.ray?s.pickWithRay(t.ray):s.pick(e.pointerX,e.pointerY),r&&(s._activeCamera=r)}return i},r=i(this.utilityLayerScene);if(!t.ray&&r&&(t.ray=r.ray),t.originalPickingInfo?.aimTransform&&r&&(r.aimTransform=t.originalPickingInfo.aimTransform,r.gripTransform=t.originalPickingInfo.gripTransform),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=Yn.POINTERDOWN)return t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new $n(t.type,t.event,r),t.type),void(t.type===Yn.POINTERUP&&this._pointerCaptures[s.pointerId]&&(this._pointerCaptures[s.pointerId]=!1));if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)r&&r.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new $n(t.type,t.event,r),t.type),t.skipOnPointerObservable=!0);else{const s=i(e),n=t.event;s&&r&&(0===r.distance&&s.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(s.pickedMesh)?(this._notifyObservers(t,s,n),t.skipOnPointerObservable=!0):t.type===Yn.POINTERDOWN?(this._pointerCaptures[n.pointerId]=!0,this._notifyObservers(t,s,n)):t.type!==Yn.POINTERMOVE&&t.type!==Yn.POINTERUP||(this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,s,n)):!this._pointerCaptures[n.pointerId]&&(r.distance<s.distance||0===s.distance)?(this._notifyObservers(t,r,n),t.skipOnPointerObservable||(t.skipOnPointerObservable=r.distance>0)):!this._pointerCaptures[n.pointerId]&&r.distance>=s.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(s.pickedMesh)?(this._notifyObservers(t,s,n),t.skipOnPointerObservable=!0):(t.type!==Yn.POINTERMOVE&&t.type!==Yn.POINTERUP||this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,r,n))),t.type===Yn.POINTERUP&&this._pointerCaptures[n.pointerId]&&(this._pointerCaptures[n.pointerId]=!1))}}),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,s||(this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add(e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add(()=>{this.dispose()}),this._updateCamera()}_notifyObservers(e,t,s){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new $n(e.type,e.event,t),e.type),this._lastPointerEvents[s.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){const e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterRenderCameraObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}zc._DefaultUtilityLayer=null,zc._DefaultKeepDepthUtilityLayer=null;const Wc={FindMainCamera:function(e){return e.findMainCamera()},FindMainObjectRenderer:function(e){return e.findMainObjectRenderer()},CreateUtilityLayerRenderer:function(e,t=!0){const s=e.scene,i=new zc(s,t,!0);i.utilityLayerScene.activeCamera=s.activeCamera;let r=Wc.FindMainCamera(s.frameGraph);!r&&s.cameras.length>0&&(r=s.cameras[0]),r&&(i.setRenderCamera(r),i.utilityLayerScene.activeCamera=r);const n=s.onAfterRenderObservable.add(()=>{i.render()});return i.utilityLayerScene.onDisposeObservable.addOnce(()=>{s.onAfterRenderObservable.remove(n)}),i}};class Xc{constructor(e,t){this._disableRenderingRefCount=0,this._currentPerformancePriorityMode=0,this._isEnabling=!1,this._enableCancelFunctions=new Map,this._disableCancelFunctions=new Map,this.showDebugLogs=!1,this._particleSystemBillboardFlags=new WeakMap,this._scene=e,this._engine=e.getEngine(),this._engine.isWebGPU&&(this._options={morphTargetsNumMaxInfluences:20,...t},this._engine.snapshotRenderingMode=dt.SNAPSHOTRENDERING_FAST,this.fixMeshes(),this._onResizeObserver=this._engine.onResizeObservable.add(()=>{this._log("onResize","start"),this._fastSnapshotRenderingEnabled?(this.disableSnapshotRendering(),this.enableSnapshotRendering()):this._isEnabling&&(this._enableCancelFunctions.forEach(e=>e()),this._enableCancelFunctions.clear(),this._disableRenderingRefCount++,this.enableSnapshotRendering()),this._log("onResize","end")}),this._onBeforeRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{if(!this._fastSnapshotRenderingEnabled)return;for(const t of e.skeletons)t.prepare(!0);for(const t of e.meshes)if(t.infiniteDistance&&t.transferToEffect(t.computeWorldMatrix(!0)),t.skeleton&&t.transferToEffect(t.computeWorldMatrix(!0)),rc(t.getClassName())&&t._postToWorker(),t.morphTargetManager&&t.subMeshes)for(const e of t.subMeshes){const s=e._drawWrapper,i=s.effect;if(i){const e=s.drawContext.buffers.LeftOver,r=i._pipelineContext?.uniformBuffer;e&&r&&r.setDataBuffer(e)&&(t.morphTargetManager._bind(i),Jr(t,i),r.update())}}let t=e.activeCamera;if(e.frameGraph&&(t=Wc.FindMainCamera(e.frameGraph)||t),e.spriteManagers&&t)for(const s of e.spriteManagers){const e=s.spriteRenderer;this._spriteRendererUpdateEffects(e._drawWrapperBase,e._drawWrapperDepth,t)}if(e.particleSystems&&t)for(const s of e.particleSystems){const e=s;e._useFixedCapacityForSnapshot&&this._updateFixedCapacityParticleSystem(e,t)}}))}get isReady(){return!this._isEnabling}enableSnapshotRendering(e){if(!this._engine.isWebGPU)return;if(this._log("enableSnapshotRendering",`called (refCount: ${this._disableRenderingRefCount-1})${e?` - ${e}`:""}`),--this._disableRenderingRefCount>0)return;this._log("enableSnapshotRendering","execute"),this._disableCancelFunctions.size>0&&this._log("enableSnapshotRendering",`cancelling ${this._disableCancelFunctions.size} "disable" callbacks`),this._disableCancelFunctions.forEach(e=>e()),this._disableCancelFunctions.clear(),this._isEnabling=!0,this._disableRenderingRefCount=0,this._currentPerformancePriorityMode=this._pendingCurrentPerformancePriorityMode??this._scene.performancePriority,this._pendingCurrentPerformancePriorityMode=void 0,this._scene.performancePriority=0;const t=()=>{this._enableCancelFunctions.delete(t);const e=this._engine.frameId+2;this._log("enableSnapshotRendering",`scene ready, add callbacks for frames ${e} and ${e+1}`),this._executeAtFrame(e,()=>{this._log("enableSnapshotRendering","callback #1, enable snapshot rendering at the engine level"),this._engine.snapshotRendering=!0}),this._executeAtFrame(e+1,()=>{this._log("enableSnapshotRendering","callback #2, signals that snapshot rendering helper is ready"),this._isEnabling=!1})};this._enableCancelFunctions.set(t,()=>this._scene.onReadyObservable.removeCallback(t)),this._scene.executeWhenReady(t)}disableSnapshotRendering(e){if(this._engine.isWebGPU){if(this._log("disableSnapshotRendering",`called (refCount: ${0===this._disableRenderingRefCount?0:this._disableRenderingRefCount+1})${e?` - ${e}`:""}`),0===this._disableRenderingRefCount&&(this._log("disableSnapshotRendering","execute (refCount set to 1 after execution)"),this._enableCancelFunctions.size>0&&this._log("disableSnapshotRendering",`cancelling ${this._enableCancelFunctions.size} "enable" callbacks`),this._enableCancelFunctions.forEach(e=>e()),this._enableCancelFunctions.clear(),this._isEnabling=!1,this._scene.performancePriority=0,0!==this._currentPerformancePriorityMode)){this._log("disableSnapshotRendering",`makes sure that the scene is rendered once in BackwardCompatible mode (code: 0) before switching to mode ${this._currentPerformancePriorityMode}`),this._pendingCurrentPerformancePriorityMode=this._currentPerformancePriorityMode;const e=()=>{this._log("disableSnapshotRendering",`scene ready, add callback for frame ${this._engine.frameId+2}`),this._executeAtFrame(this._engine.frameId+2,()=>{this._log("disableSnapshotRendering",`switching to performance priority mode ${this._pendingCurrentPerformancePriorityMode}`),this._scene.performancePriority=this._pendingCurrentPerformancePriorityMode,this._pendingCurrentPerformancePriorityMode=void 0},"whenDisabled")};this._disableCancelFunctions.set(e,()=>this._scene.onReadyObservable.removeCallback(e)),this._scene.executeWhenReady(e)}this._engine.snapshotRendering=!1,this._disableRenderingRefCount++}}fixMeshes(e){if(this._engine.isWebGPU){e=e||this._scene.meshes;for(const t of e)t.ignoreCameraMaxZ=!1,t.morphTargetManager&&(t.morphTargetManager.numMaxInfluencers=Math.min(t.morphTargetManager.numTargets,this._options.morphTargetsNumMaxInfluences))}}updateMesh(e,t=!0){if(this._fastSnapshotRenderingEnabled)if(Array.isArray(e))for(const s of e)t&&this._updateInstancedMesh(s)||s.transferToEffect(s.computeWorldMatrix());else t&&this._updateInstancedMesh(e)||e.transferToEffect(e.computeWorldMatrix())}_updateInstancedMesh(e){if(e.hasInstances){if(e.subMeshes){const t=e;for(const e of t.subMeshes){const s=t._getInstancesRenderList(e._id);t._updateInstancedBuffers(e,s,s.parent.instancesBufferSize,this._engine)}}return!0}return!!e.isAnInstance}updateMeshesForEffectLayer(e,t=!0){if(!this._engine.isWebGPU)return;const s=e instanceof Hc?e.objectRendererForLayer.objectRenderer.renderPassId:e.mainTexture.renderPassId;t?this._onBeforeRenderObserverUpdateLayer=this._scene.onBeforeRenderObservable.add(()=>{this._updateMeshMatricesForRenderPassId(s)}):this._updateMeshMatricesForRenderPassId(s)}dispose(){this._engine.isWebGPU&&(this._scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserverUpdateLayer),this._engine.onResizeObservable.remove(this._onResizeObserver))}get _fastSnapshotRenderingEnabled(){return this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===dt.SNAPSHOTRENDERING_FAST}_updateMeshMatricesForRenderPassId(e){if(!this._fastSnapshotRenderingEnabled)return;const t=this._scene.objectRenderers.find(t=>t.renderPassId===e)?.activeCamera?.getTransformationMatrix()??this._scene.getTransformMatrix();for(let s=0;s<this._scene.meshes.length;++s){const i=this._scene.meshes[s];if(i.subMeshes)for(let s=0;s<i.subMeshes.length;++s){const r=i.subMeshes[s]._getDrawWrapper(e),n=r?.effect;if(n){const e=r.drawContext.buffers.LeftOver,s=n._pipelineContext?.uniformBuffer;e&&s&&s.setDataBuffer(e)&&(n.setMatrix("viewProjection",t),n.setMatrix("world",i.computeWorldMatrix()),s.update())}}}}_spriteRendererDirectMatrixUpdate(e,t){const s=e?.effect;if(s){const i=e.drawContext.buffers.LeftOver,r=s._pipelineContext?.uniformBuffer;i&&r&&r.setDataBuffer(i)&&(s.setMatrix("view",t.getViewMatrix()),s.setMatrix("projection",t.getProjectionMatrix()),r.update())}}_spriteRendererUpdateEffects(e,t,s){this._spriteRendererDirectMatrixUpdate(e,s),this._spriteRendererDirectMatrixUpdate(t,s)}fixParticleSystem(e){if(!this._engine.isWebGPU)return;if("ParticleSystem"!==e.getClassName())return void this._log("fixParticleSystem",`skipping ${e.name}: only CPU ParticleSystem is supported (got ${e.getClassName()})`);e._initFixedCapacitySnapshotData()&&(this._fastSnapshotRenderingEnabled||this._isEnabling)&&(a.Warn(`SnapshotRenderingHelper.fixParticleSystem("${e.name}") was called after snapshot rendering was enabled. Forcing a re-record so the bundle uses the fixed-capacity draw count. Call fixParticleSystem before enableSnapshotRendering to avoid this.`),this.disableSnapshotRendering("fixParticleSystem auto-recover"),this.enableSnapshotRendering("fixParticleSystem auto-recover"))}_updateFixedCapacityParticleSystem(e,t){if(!this._scene.particlesEnabled||!e.isStarted()||!e.emitter)return void e._clearFixedCapacitySnapshotData();const s=e.emitter;!s.position||s.isEnabled?.()?(e.animate(),this._particleSystemUpdateEffects(e,t)):e._clearFixedCapacitySnapshotData()}_particleSystemUpdateEffects(e,t){const s=e._drawWrappers;if(!s)return;const i=e.defaultViewMatrix??t.getViewMatrix(),r=e.defaultProjectionMatrix??t.getProjectionMatrix();let n=null;for(const e of s)if(e)for(const s of e)n=this._particleSystemDirectMatrixUpdate(s,i,r,t,n)}_particleSystemDirectMatrixUpdate(e,t,s,i,r){const n=e?.effect;if(!n)return r;const a=e.drawContext.buffers.LeftOver,o=n._pipelineContext?.uniformBuffer;if(!a||!o||!o.setDataBuffer(a))return r;n.setMatrix("view",t),n.setMatrix("projection",s);let h=this._particleSystemBillboardFlags.get(n);if(!h){const e=n.defines??"";h={billboard:e.indexOf("#define BILLBOARD")>=0,billboardAll:e.indexOf("#define BILLBOARDMODE_ALL")>=0},this._particleSystemBillboardFlags.set(n,h)}return h.billboard&&n.setVector3("eyePosition",i.globalPosition),h.billboardAll&&(r||(r=Ce.Matrix[0],t.invertToRef(r)),n.setMatrix("invView",r)),o.update(),r}_executeAtFrame(e,t,s="whenEnabled"){const i=()=>{this._engine.frameId>=e&&(this._engine.onEndFrameObservable.remove(r),"whenEnabled"===s?this._enableCancelFunctions.delete(i):this._disableCancelFunctions.delete(i),t())},r=this._engine.onEndFrameObservable.add(i);"whenEnabled"===s?this._enableCancelFunctions.set(i,()=>this._engine.onEndFrameObservable.remove(r)):this._disableCancelFunctions.set(i,()=>this._engine.onEndFrameObservable.remove(r))}_log(e,t){this.showDebugLogs&&a.Log(`[Frame: ${this._engine.frameId}] SnapshotRenderingHelper:${e} - ${t}`)}}function Kc(e){const t=e.split("?")[0],s=t.lastIndexOf(".");return s>-1?t.substring(s).toLowerCase():""}Jo||(Jo=!0,be("BABYLON.Scene",Qo));const Yc={name:"bvh",extensions:{".bvh":{isBinary:!1}}},jc={name:"fbx",extensions:{".fbx":{isBinary:!0}}},qc="Z2xURg",$c={name:"gltf",extensions:{".gltf":{isBinary:!1,mimeType:"model/gltf+json"},".glb":{isBinary:!0,mimeType:"model/gltf-binary"}},canDirectLoad:e=>-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+qc)||e.startsWith("data:;base64,"+qc)||e.startsWith("data:application/octet-stream;base64,"+qc)||e.startsWith("data:model/gltf-binary;base64,"+qc)},Zc={name:"obj",extensions:".obj"},Qc={name:"splat",extensions:{".splat":{isBinary:!0},".ply":{isBinary:!0},".spz":{isBinary:!0},".json":{isBinary:!1},".sog":{isBinary:!0}}},Jc={name:"stl",extensions:{".stl":{isBinary:!0}}},eu=new Map,tu=eu;function su(e,t,s){iu(e)&&a.Warn(`Extension with the name '${e}' already exists`),eu.set(e,{isGLTFExtension:t,factory:s})}function iu(e){return eu.delete(e)}function ru(){dh({...Yc,createPlugin:async e=>{const{BVHFileLoader:t}=await import("./bvhFileLoader-DBXbznoM.esm.min.js");return new t(e[Yc.name])}}),dh({...jc,createPlugin:async e=>{const{FBXFileLoader:t}=await import("./fbxFileLoader-BK3LLoYq.esm.min.js");return new t(e[jc.name])}}),dh({...$c,createPlugin:async e=>{const{GLTFFileLoader:t}=await import("./glTFLoader-Cj20vg9_.esm.min.js");return new t(e[$c.name])}}),iu("EXT_lights_image_based"),su("EXT_lights_image_based",!0,async e=>{const{EXT_lights_image_based:t}=await import("./EXT_lights_image_based-Ck94EzSs.esm.min.js");return new t(e)}),iu("EXT_mesh_gpu_instancing"),su("EXT_mesh_gpu_instancing",!0,async e=>{const{EXT_mesh_gpu_instancing:t}=await import("./EXT_mesh_gpu_instancing-CDRi6hrs.esm.min.js");return new t(e)}),iu("EXT_meshopt_compression"),su("EXT_meshopt_compression",!0,async e=>{const{EXT_meshopt_compression:t}=await import("./EXT_meshopt_compression-CNXr6lFP.esm.min.js");return new t(e)}),iu("EXT_texture_avif"),su("EXT_texture_avif",!0,async e=>{const{EXT_texture_avif:t}=await import("./EXT_texture_avif--1_7aZE4.esm.min.js");return new t(e)}),iu("EXT_texture_webp"),su("EXT_texture_webp",!0,async e=>{const{EXT_texture_webp:t}=await import("./EXT_texture_webp-dQaWBlwh.esm.min.js");return new t(e)}),iu("ExtrasAsMetadata"),su("ExtrasAsMetadata",!1,async e=>{const{ExtrasAsMetadata:t}=await import("./ExtrasAsMetadata-pqXBzGkY.esm.min.js");return new t(e)}),iu("KHR_animation_pointer"),su("KHR_animation_pointer",!0,async e=>{const{KHR_animation_pointer:t}=await import("./KHR_animation_pointer-0XChA3Jv.esm.min.js");return new t(e)}),iu("KHR_draco_mesh_compression"),su("KHR_draco_mesh_compression",!0,async e=>{const{KHR_draco_mesh_compression:t}=await import("./KHR_draco_mesh_compression-Cxh0eir1.esm.min.js");return new t(e)}),iu("KHR_gaussian_splatting"),su("KHR_gaussian_splatting",!0,async e=>{const{KHR_gaussian_splatting:t}=await import("./KHR_gaussian_splatting-CxfYJlme.esm.min.js");return new t(e)}),iu("KHR_interactivity"),su("KHR_interactivity",!0,async e=>{const{KHR_interactivity:t}=await import("./KHR_interactivity-BMn2G2LI.esm.min.js").then(function(e){return e.K});return new t(e)}),iu("KHR_lights_punctual"),su("KHR_lights_punctual",!0,async e=>{const{KHR_lights:t}=await import("./KHR_lights_punctual-w_U9ffmW.esm.min.js");return new t(e)}),iu("EXT_lights_area"),su("EXT_lights_area",!0,async e=>{const{EXT_lights_area:t}=await import("./EXT_lights_area-BZSxY0TB.esm.min.js");return new t(e)}),iu("EXT_lights_ies"),su("EXT_lights_ies",!0,async e=>{const{EXT_lights_ies:t}=await import("./EXT_lights_ies-Dd4teRgA.esm.min.js");return new t(e)}),iu("KHR_materials_anisotropy"),su("KHR_materials_anisotropy",!0,async e=>{const{KHR_materials_anisotropy:t}=await import("./KHR_materials_anisotropy-3N-uhWHZ.esm.min.js");return new t(e)}),iu("KHR_materials_clearcoat"),su("KHR_materials_clearcoat",!0,async e=>{const{KHR_materials_clearcoat:t}=await import("./KHR_materials_clearcoat-brE1Ot9r.esm.min.js");return new t(e)}),iu("KHR_materials_diffuse_roughness"),su("KHR_materials_diffuse_roughness",!0,async e=>{const{KHR_materials_diffuse_roughness:t}=await import("./KHR_materials_diffuse_roughness-BdQFOqIS.esm.min.js");return new t(e)}),iu("KHR_materials_diffuse_transmission"),su("KHR_materials_diffuse_transmission",!0,async e=>{const{KHR_materials_diffuse_transmission:t}=await import("./KHR_materials_diffuse_transmission-C5q5ia2b.esm.min.js");return new t(e)}),iu("KHR_materials_dispersion"),su("KHR_materials_dispersion",!0,async e=>{const{KHR_materials_dispersion:t}=await import("./KHR_materials_dispersion-k_Hb49XX.esm.min.js");return new t(e)}),iu("KHR_materials_emissive_strength"),su("KHR_materials_emissive_strength",!0,async e=>{const{KHR_materials_emissive_strength:t}=await import("./KHR_materials_emissive_strength-OnbxVKIA.esm.min.js");return new t(e)}),iu("KHR_materials_ior"),su("KHR_materials_ior",!0,async e=>{const{KHR_materials_ior:t}=await import("./KHR_materials_ior-BPFmZiTF.esm.min.js");return new t(e)}),iu("KHR_materials_iridescence"),su("KHR_materials_iridescence",!0,async e=>{const{KHR_materials_iridescence:t}=await import("./KHR_materials_iridescence-HkNSnJcj.esm.min.js");return new t(e)}),iu("KHR_materials_pbrSpecularGlossiness"),su("KHR_materials_pbrSpecularGlossiness",!0,async e=>{const{KHR_materials_pbrSpecularGlossiness:t}=await import("./KHR_materials_pbrSpecularGlossiness-DNDhf7ny.esm.min.js");return new t(e)}),iu("KHR_materials_sheen"),su("KHR_materials_sheen",!0,async e=>{const{KHR_materials_sheen:t}=await import("./KHR_materials_sheen-sIhgB8iD.esm.min.js");return new t(e)}),iu("KHR_materials_specular"),su("KHR_materials_specular",!0,async e=>{const{KHR_materials_specular:t}=await import("./KHR_materials_specular-BeSVJyG-.esm.min.js");return new t(e)}),iu("KHR_materials_transmission"),su("KHR_materials_transmission",!0,async e=>{const{KHR_materials_transmission:t}=await import("./KHR_materials_transmission-Didp17xy.esm.min.js");return new t(e)}),iu("KHR_materials_unlit"),su("KHR_materials_unlit",!0,async e=>{const{KHR_materials_unlit:t}=await import("./KHR_materials_unlit-BSAeZvCa.esm.min.js");return new t(e)}),iu("KHR_materials_variants"),su("KHR_materials_variants",!0,async e=>{const{KHR_materials_variants:t}=await import("./KHR_materials_variants-Bhot0HfS.esm.min.js");return new t(e)}),iu("KHR_materials_volume"),su("KHR_materials_volume",!0,async e=>{const{KHR_materials_volume:t}=await import("./KHR_materials_volume-es92YE75.esm.min.js");return new t(e)}),iu("KHR_mesh_quantization"),su("KHR_mesh_quantization",!0,async e=>{const{KHR_mesh_quantization:t}=await import("./KHR_mesh_quantization-BAZGtp0t.esm.min.js");return new t(e)}),iu("KHR_texture_basisu"),su("KHR_texture_basisu",!0,async e=>{const{KHR_texture_basisu:t}=await import("./KHR_texture_basisu-0lJiRsTE.esm.min.js");return new t(e)}),iu("KHR_texture_transform"),su("KHR_texture_transform",!0,async e=>{const{KHR_texture_transform:t}=await import("./KHR_texture_transform-u3dEyl_P.esm.min.js");return new t(e)}),iu("KHR_xmp_json_ld"),su("KHR_xmp_json_ld",!0,async e=>{const{KHR_xmp_json_ld:t}=await import("./KHR_xmp_json_ld-tJpVyAxw.esm.min.js");return new t(e)}),iu("MSFT_audio_emitter"),su("MSFT_audio_emitter",!0,async e=>{const{MSFT_audio_emitter:t}=await import("./MSFT_audio_emitter-DiuwnPru.esm.min.js");return new t(e)}),iu("MSFT_lod"),su("MSFT_lod",!0,async e=>{const{MSFT_lod:t}=await import("./MSFT_lod-D1FH_yXO.esm.min.js");return new t(e)}),iu("MSFT_minecraftMesh"),su("MSFT_minecraftMesh",!0,async e=>{const{MSFT_minecraftMesh:t}=await import("./MSFT_minecraftMesh-CdqsleXq.esm.min.js");return new t(e)}),iu("MSFT_sRGBFactors"),su("MSFT_sRGBFactors",!0,async e=>{const{MSFT_sRGBFactors:t}=await import("./MSFT_sRGBFactors-CC6Yta5z.esm.min.js");return new t(e)}),iu("KHR_node_visibility"),su("KHR_node_visibility",!0,async e=>{const{KHR_node_visibility:t}=await import("./KHR_node_visibility-C_4Tx4Qk.esm.min.js");return new t(e)}),iu("KHR_node_hoverability"),su("KHR_node_hoverability",!0,async e=>{const{KHR_node_hoverability:t}=await import("./KHR_node_hoverability-BkzLOdO3.esm.min.js");return new t(e)}),iu("KHR_node_selectability"),su("KHR_node_selectability",!0,async e=>{const{KHR_node_selectability:t}=await import("./KHR_node_selectability-BEWJWavb.esm.min.js");return new t(e)}),iu("KHR_materials_coat"),su("KHR_materials_coat",!0,async e=>{const{KHR_materials_coat:t}=await import("./KHR_materials_coat-0jDV0btC.esm.min.js");return new t(e)}),iu("KHR_materials_fuzz"),su("KHR_materials_fuzz",!0,async e=>{const{KHR_materials_fuzz:t}=await import("./KHR_materials_fuzz-BCr4bwbG.esm.min.js");return new t(e)}),iu("KHR_materials_volume_scatter"),su("KHR_materials_volume_scatter",!0,async e=>{const{KHR_materials_volume_scatter:t}=await import("./KHR_materials_volume_scatter-BUcgIxtl.esm.min.js");return new t(e)}),dh({...Zc,createPlugin:async e=>{const{OBJFileLoader:t}=await import("./objFileLoader-Clp3Tf4u.esm.min.js");return new t(e[Zc.name])}}),dh({...Qc,createPlugin:async e=>{const{SPLATFileLoader:t}=await import("./splatFileLoader-BjgGRBfE.esm.min.js");return new t(e[Qc.name])}}),dh({...Jc,createPlugin:async()=>{const{STLFileLoader:e}=await import("./stlFileLoader-B8PaaO83.esm.min.js");return new e}})}const nu=new lc(()=>Promise.all([import("./ssao2RenderingPipeline-BkdIabpH.esm.min.js"),import("./prePassRendererSceneComponent-27jINHst.esm.min.js"),import("./geometryBufferRendererSceneComponent-CC8Hs9qu.esm.min.js"),import("./engine.multiRender-g60Hn4RA.esm.min.js"),import("./engine.multiRender-Y4zQH9W8.esm.min.js")]));async function au(e,t){return await new Promise((s,r)=>{if(t.aborted)return void r(new i("Aborted"));const n=e.addOnce(e=>{t.removeEventListener("abort",a),s(e)}),a=()=>{n.remove(),r(new i("Aborted"))};t.addEventListener("abort",a,{once:!0})})}function ou(e){const t=e.getClassName();return rc(t)||"GaussianSplattingPartProxyMesh"===t}function hu(e){const t=e.getClassName();return t.startsWith("PBR")||"OpenPBRMaterial"===t}async function lu(e,t,s){s=s??Kc(e);const i=await(async()=>{if(".hdr"===s){const{HDRCubeTexture:s}=await import("./hdrCubeTexture-DqOKVYzv.esm.min.js");return()=>new s(e,t,256,!1,!0,!1,!0,void 0,void 0,void 0,!0,!0)}{const{CubeTexture:i}=await import("./cubeTexture-B-XedcBF.esm.min.js");return()=>new i(e,t,null,!1,null,null,null,void 0,!0,s,!0)}})(),r=t.useDelayedTextureLoading;try{return t.useDelayedTextureLoading=!1,i()}finally{t.useDelayedTextureLoading=r}}function cu(e,t){e?.scaling.setAll((t.maxZ-t.minZ)/2)}function uu(e){return e.flatMap(e=>function(e,t=null,s=1/6){const i=Ce.Vector3[0],r=new Map,n=new Map,a=e.reduce((e,t)=>Math.max(e,t.getTotalVertices()),0),o=Array.from({length:a},()=>new xe),h=Array.from({length:a},()=>new xe);for(const t of e){const e=t.getVerticesData(Gi.PositionKind);if(!e)continue;const s=t.getTotalVertices();o.length=Math.max(o.length,s),h.length=Math.max(o.length,s);for(let t=0,r=0;t<s;t++,r+=3)i.set(e[r],e[r+1],e[r+2]),o[t].copyFrom(i),h[t].copyFrom(i);const a=t.morphTargetManager;if(a)for(let e=0;e<a.numTargets;++e){const t=a.getTarget(e).getPositions();if(t)for(let e=0,r=0;e<s;e++,r+=3)i.set(t[r],t[r+1],t[r+2]),o[e].minimizeInPlace(i),h[e].maximizeInPlace(i)}const l=t.skeleton,c=l?t.getVerticesData(Gi.MatricesWeightsKind):null,u=l?t.getVerticesData(Gi.MatricesIndicesKind):null;if(c&&u){const e=t.numBoneInfluencers>4,i=e?t.getVerticesData(Gi.MatricesWeightsExtraKind):null,r=e?t.getVerticesData(Gi.MatricesIndicesExtraKind):null,a=n.get(t.uniqueId)||new Map;n.set(t.uniqueId,a);const l=(e,t,s,i)=>{for(let r=t;r<t+4;r++)if(s[r]>0){const t=i[r],s=a.get(t);s?(s.minimum.minimizeInPlace(o[e]),s.maximum.maximizeInPlace(h[e])):a.set(t,{minimum:o[e].clone(),maximum:h[e].clone()})}};for(let e=0,t=0;e<s;e++,t+=4)l(e,t,c,u),i&&r&&l(e,t,i,r)}else{const e=r.get(t.uniqueId)||{minimum:(new xe).setAll(Number.POSITIVE_INFINITY),maximum:(new xe).setAll(Number.NEGATIVE_INFINITY)};r.set(t.uniqueId,e);for(let t=0;t<s;t++)e.minimum.minimizeInPlace(o[t]),e.maximum.maximizeInPlace(h[t])}}const l=new Map,c=new Map;for(const t of e){const e=r.get(t.uniqueId);if(e)l.set(t.uniqueId,oc(e));else{const e=n.get(t.uniqueId);if(e){const s=t.skeleton.bones,i=new Map;c.set(t.uniqueId,i),e.forEach((e,t)=>{const r=oc(e),n=s[t].getAbsoluteInverseBindMatrix();for(const e of r)xe.TransformCoordinatesToRef(e,n,e);i.set(t,r)})}}}const u=Array.from({length:e.length},()=>({minimum:(new xe).setAll(Number.POSITIVE_INFINITY),maximum:(new xe).setAll(Number.NEGATIVE_INFINITY)})),d=()=>{for(let t=0;t<e.length;t++){const s=e[t];if(!s.getVerticesData(Gi.PositionKind))continue;const r=s.computeWorldMatrix(!0),n=s.skeleton;if(n){n.prepare(!0);const e=n.bones;c.get(s.uniqueId).forEach((s,n)=>{for(const a of s){const s=e[n].getFinalMatrix().multiplyToRef(r,Ce.Matrix[0]);xe.TransformCoordinatesToRef(a,s,i),u[t].minimum.minimizeInPlace(i),u[t].maximum.maximizeInPlace(i)}})}else for(const e of l.get(s.uniqueId))xe.TransformCoordinatesToRef(e,r,i),u[t].minimum.minimizeInPlace(i),u[t].maximum.maximizeInPlace(i)}};if(t&&t.isStarted){const e=t.getCurrentFrame(),i=s/t.getLength(0,1);for(let e=t.from;e<=t.to;e+=i)t.goToFrame(e),d();t.goToFrame(e)}else d();return u}(e.assetContainer.meshes,e.assetContainer.animationGroups[e.selectedAnimation]))}function du(e){return function(e){if(0===e.length)return null;const t=new xe(Math.min(...e.map(e=>e.minimum.x)),Math.min(...e.map(e=>e.minimum.y)),Math.min(...e.map(e=>e.minimum.z))),s=new xe(Math.max(...e.map(e=>e.maximum.x)),Math.max(...e.map(e=>e.maximum.y)),Math.max(...e.map(e=>e.maximum.z))),i=s.subtract(t),r=t.add(i.scale(.5));return{extents:{min:t.asArray(),max:s.asArray()},size:i.asArray(),center:r.asArray()}}(uu(e))}async function _u(e,t){await import("./ray-DM87Gj5w.esm.min.js");const s=e.assetContainer.scene,i=t.getForwardRay(100,t.getWorldMatrix(),t.globalPosition),r=t.globalPosition.clone();let n=1e-4;const a=xe.Zero(),o=s.pickWithRay(i,t=>e.assetContainer.meshes.includes(t));if(o&&o.hit)a.copyFrom(o.pickedPoint);else{const t=e.getWorldBounds(),s=t?t.center:[0,0,0],o=xe.FromArray(s),h=i.direction.clone();a.copyFrom(r),n=xe.Distance(r,o),h.scaleAndAddToRef(n,a)}const h=xe.Zero();r.subtractToRef(a,h),o&&o.hit&&(n=h.length());const l=Ja(h),c=eo(h.y,n),u=a.asArray();return{type:"world",position:u,normal:u,cameraOrbit:[l,c,n]}}const pu=m;class fu extends R{_applyClearColor(){this._scene.clearColor.r=this._clearColor.r,this._scene.clearColor.g=this._clearColor.g,this._scene.clearColor.b=this._clearColor.b,this._scene.clearColor.a=this._clearColor.a,this._markSceneMutated()}get isModelLoaded(){return null!==this._activeModelBacking}_onObjectListsUpdated(e){}constructor(e,t){if(super(),this._engine=e,this._options=t,this.showDebugLogs=!1,this._snapshotHelper=null,this._defaultMaterialPromise=null,this._renderedLastFrame=null,this._isIdle=!1,this._sceneOptimizer=null,this._tempVectors=$(4,xe.Zero),this._meshDataCache=new Map,this._beforeRenderObserver=null,this._renderLoopController=null,this._loadedModelsBacking=[],this._activeModelBacking=null,this._environmentSkyboxMode="none",this._environmentLightingMode="none",this._skybox=null,this._skyboxTexture=null,this._reflectionTexture=null,this._light=null,this._ssaoOption=this._options?.postProcessing?.ssao??pu.postProcessing.ssao,this._ssaoPipeline=null,this._autoSuspendRendering=this._options?.autoSuspendRendering??pu.autoSuspendRendering,this._sceneMutated=!1,this._suspendRenderCount=0,this._camerasAsHotSpotsAbortController=null,this._updateSSAOLock=new n,this._ssaoAbortController=null,this._activeAnimationObservers=[],this._animationSpeed=this._options?.animationSpeed??pu.animationSpeed,this._camerasAsHotSpots=!1,this._shadowState={},this._iblShadowsAnimationObserver=null,this._objectListFilters=[],this._objectListModelChangedObserver=null,"high"===this._options?.shadowConfig?.quality&&"enabled"===this._options?.postProcessing?.ssao)throw new Error("High quality shadows are not compatible with SSAO. Please choose either high quality shadows or SSAO.");this._shadowQuality=this._options?.shadowConfig?.quality??pu.shadowConfig.quality,this._environmentIntensity=this._options?.environmentConfig?.intensity??pu.environmentConfig.intensity,this._environmentBlur=this._options?.environmentConfig?.blur??pu.environmentConfig.blur,this._environmentRotation=this._options?.environmentConfig?.rotation??pu.environmentConfig.rotation,this._options?.hotSpots&&(this.hotSpots=this._options.hotSpots),this._defaultHardwareScalingLevel=this._lastHardwareScalingLevel=this._engine.getHardwareScalingLevel();{const e=new Qo(this._engine);e.useRightHandedSystem=this._options?.useRightHandedSystem??pu.useRightHandedSystem,this._toneMappingEnabled=e.imageProcessingConfiguration.toneMappingEnabled,this._toneMappingType=e.imageProcessingConfiguration.toneMappingType,this._contrast=e.imageProcessingConfiguration.contrast,this._exposure=e.imageProcessingConfiguration.exposure,this._imageProcessingConfigurationObserver=e.imageProcessingConfiguration.onUpdateParameters.add(()=>{let t=!1;this._toneMappingEnabled!==e.imageProcessingConfiguration.toneMappingEnabled&&(this._toneMappingEnabled=e.imageProcessingConfiguration.toneMappingEnabled,t=!0),this._toneMappingType!==e.imageProcessingConfiguration.toneMappingType&&(this._toneMappingType=e.imageProcessingConfiguration.toneMappingType,t=!0),this._contrast!==e.imageProcessingConfiguration.contrast&&(this._contrast=e.imageProcessingConfiguration.contrast,t=!0),this._exposure!==e.imageProcessingConfiguration.exposure&&(this._exposure=e.imageProcessingConfiguration.exposure,t=!0),t&&this.onPostProcessingChanged.notifyObservers()});const t=new so("Viewer Default Camera",0,0,1,xe.Zero(),e);t.useInputToRestoreState=!1,t.useAutoRotationBehavior=!0,t.onViewMatrixChangedObservable.add(()=>{this._markSceneMutated()}),e.onClearColorChangedObservable.add(()=>{this._markSceneMutated(),this._clearColor.a=e.clearColor.a,this._clearColor.r=e.clearColor.r,this._clearColor.g=e.clearColor.g,this._clearColor.b=e.clearColor.b,this.onClearColorChanged.notifyObservers()}),e.onPointerObservable.add(async e=>{const s=await this._pick(e.event.offsetX,e.event.offsetY);if(s?.pickedPoint){const e=s.pickedPoint.subtract(t.position).dot(t.getForwardRay().direction);t.target=t.position.add(t.getForwardRay().direction.scale(e)),t.radius=e,t.interpolateTo(void 0,void 0,void 0,s.pickedPoint)}else this.resetCamera(!0)},Yn.POINTERDOUBLETAP),e.onNewCameraAddedObservable.add(e=>{this.camerasAsHotSpots&&d(this._addCameraHotSpot(e,this._camerasAsHotSpotsAbortController?.signal))}),e.onCameraRemovedObservable.add(e=>{this._removeCameraHotSpot(e)}),this._scene=e,this._camera=t}this._scene.skipFrustumClipping=!0,this._scene.skipPointerDownPicking=!0,this._scene.skipPointerUpPicking=!0,this._scene.skipPointerMovePicking=!0,this._snapshotHelper=new Xc(this._scene,{morphTargetsNumMaxInfluences:30}),this._snapshotHelper.showDebugLogs=false,this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{this._snapshotHelper?.updateMesh(this._scene.meshes)}),this._camera.attachControl(),this._autoRotationBehavior=this._camera.getBehaviorByName("AutoRotation"),this._applyCameraAutoOrbitEnabled(),this._applyCameraAutoOrbitSpeed(),this._applyCameraAutoOrbitDelay(),this._scene.onAfterRenderObservable.add(()=>{this.onAfterRenderObservable.notifyObservers()}),this._reset(!1,"camera"),d(this.resetEnvironment()),this._beginRendering();const s=this;this._options?.onInitialized?.({scene:s._scene,camera:s._camera,get model(){return s._activeModel??null},suspendRendering:()=>this._suspendRendering(),markSceneMutated:()=>this._markSceneMutated(),pick:async(e,t)=>await this._pick(e,t),get isIdle(){return s._isIdle}}),this._reset(!1,"source","environment","post-processing")}_applyCameraAutoOrbitEnabled(){this._autoOrbitEnabled?this._camera.addBehavior(this._autoRotationBehavior):this._camera.removeBehavior(this._autoRotationBehavior)}_applyCameraAutoOrbitSpeed(){this._autoRotationBehavior.idleRotationSpeed=this._autoOrbitSpeed}_applyCameraAutoOrbitDelay(){this._autoRotationBehavior.idleRotationWaitTime=this._autoOrbitDelay}_applyEnvironmentBlur(){if(this._skybox){const e=this._skybox.material;e instanceof yh&&(this._snapshotHelper?.disableSnapshotRendering(),e.reflectionBlur=this._environmentBlur,this._snapshotHelper?.enableSnapshotRendering(),this._markSceneMutated())}}_applyEnvironmentRotation(){this._snapshotHelper?.disableSnapshotRendering(),this._skyboxTexture&&(this._skyboxTexture.rotationY=this._environmentRotation),this._reflectionTexture&&(this._reflectionTexture.rotationY=this._environmentRotation),this._snapshotHelper?.enableSnapshotRendering(),this._markSceneMutated(),this._rotateShadowLightWithEnvironment()}_applyEnvironmentIntensity(){this._snapshotHelper?.disableSnapshotRendering(),this._skyboxTexture&&(this._skyboxTexture.level=this._environmentIntensity),this._reflectionTexture&&(this._reflectionTexture.level=this._environmentIntensity),this._snapshotHelper?.enableSnapshotRendering(),this._markSceneMutated(),this._changeShadowLightIntensity()}async updateShadows(e,t){if("high"===e.quality&&"enabled"===this._ssaoOption)throw new Error("Shadows quality cannot be set to high when SSAO is enabled.");return await super.updateShadows(e,t)}_updateAutoClear(){this._scene.autoClear=!0,this._markSceneMutated()}get postProcessing(){let e="none";if(this._toneMappingEnabled)switch(this._toneMappingType){case Eo.TONEMAPPING_STANDARD:e="standard";break;case Eo.TONEMAPPING_ACES:e="aces";break;case Eo.TONEMAPPING_KHR_PBR_NEUTRAL:e="neutral"}return{toneMapping:e,contrast:this._contrast,exposure:this._exposure,ssao:this._ssaoOption}}set postProcessing(e){if(this._snapshotHelper?.disableSnapshotRendering(),void 0!==e.toneMapping)if("none"===e.toneMapping)this._scene.imageProcessingConfiguration.toneMappingEnabled=!1;else{switch(e.toneMapping){case"standard":this._scene.imageProcessingConfiguration.toneMappingType=Eo.TONEMAPPING_STANDARD;break;case"aces":this._scene.imageProcessingConfiguration.toneMappingType=Eo.TONEMAPPING_ACES;break;case"neutral":this._scene.imageProcessingConfiguration.toneMappingType=Eo.TONEMAPPING_KHR_PBR_NEUTRAL}this._scene.imageProcessingConfiguration.toneMappingEnabled=!0}if(void 0!==e.contrast&&(this._scene.imageProcessingConfiguration.contrast=e.contrast),void 0!==e.exposure&&(this._scene.imageProcessingConfiguration.exposure=e.exposure),e.ssao&&this._ssaoOption!==e.ssao){if("enabled"===e.ssao&&"high"===this._shadowQuality)throw new Error("SSAO cannot be enabled when shadows quality is set to high.");this._ssaoOption=e.ssao,this._updateSSAOPipeline()}this._scene.imageProcessingConfiguration.isEnabled=this._toneMappingEnabled||1!==this._contrast||1!==this._exposure||null!==this._ssaoPipeline,this._snapshotHelper?.enableSnapshotRendering(),this._markSceneMutated()}get _loadedModels(){return this._loadedModelsBacking}get _activeModel(){return this._activeModelBacking}_setActiveModel(...e){const[t,s]=e;t!==this._activeModelBacking&&(this._activeModelBacking=t,this._updateLight(),d(this._updateShadows(this._shadowQuality)),this._updateSSAOPipeline(),this._applyAnimationSpeed(),this._selectAnimation(0,!1),this.onSelectedMaterialVariantChanged.notifyObservers(),this._reframeCamera(!0,t?[t]:void 0),this.onModelChanged.notifyObservers(s?.source??null))}async _enableSSAOPipeline(e){if(!this._ssaoPipeline){const[{SSAO2RenderingPipeline:t}]=await nu.value;this._throwIfDisposedOrAborted(e),this._scene.postProcessRenderPipelineManager.onNewPipelineAddedObservable.addOnce(e=>{"ssao"===e.name&&this.onPostProcessingChanged.notifyObservers()}),this._scene.postProcessRenderPipelineManager.onPipelineRemovedObservable.addOnce(e=>{"ssao"===e.name&&this.onPostProcessingChanged.notifyObservers()});const s={ssaoRatio:1,blurRatio:1};let i=null;try{i=new t("ssao",this._scene,s);const r=this._getWorldBounds(this._loadedModels);if(r){const e=xe.FromArray(r.size).length();i.expensiveBlur=!0,i.maxZ=2*e;const t=50;i.radius=ne(ie(1,5,ne((e-1)/t,0,1)),1,5),i.totalStrength=ne(ie(.3,1,ne((e-1)/t,0,1)),.3,1),i.samples=Math.round(ne(ie(8,32,ne((e-1)/t,0,1)),8,32))}for(;!i.isReady();)await au(this._scene.onAfterRenderObservable,e);this._throwIfDisposedOrAborted(e),this._ssaoPipeline=i,this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline("ssao",this._camera)}catch(e){throw i?.dispose(),e}}}_disableSSAOPipeline(){this._ssaoPipeline&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline("ssao",this._camera),this._scene.postProcessRenderPipelineManager.removePipeline("ssao"),this._ssaoPipeline?.dispose(),this._ssaoPipeline=null)}_updateSSAOPipeline(){this._ssaoAbortController?.abort(new i("SSAO pipeline is being updated.")),this._ssaoAbortController=null,d((async()=>{this._ssaoAbortController=new AbortController;const e=this._ssaoAbortController.signal;await this._updateSSAOLock.lockAsync(async()=>{let t="enabled"===this._ssaoOption&&!this._scene.frameGraph;if("auto"===this._ssaoOption&&!this._scene.frameGraph){const e=this._loadedModels.length>0,s=this._loadedModels.some(e=>e.assetContainer.materials.length>0),i="high"===this._shadowQuality,r=e&&this._loadedModels.every(e=>{const t=e.assetContainer.meshes;return t.length>0&&t.every(ou)});t=e&&!s&&!i&&!r}t?await this._enableSSAOPipeline(e):this._disableSSAOPipeline()})})())}_setActiveFrameGraph(e,t=[]){if(this.onModelChanged.remove(this._objectListModelChangedObserver),this._objectListModelChangedObserver=null,this._objectListFilters=[],this._scene.frameGraph=e,this._updateSSAOPipeline(),!e)return;this._objectListFilters=t;const s=()=>{this._onObjectListsUpdated(this._objectListFilters.map(e=>this._scene.meshes.filter(e)))};s(),this._objectListModelChangedObserver=this.onModelChanged.add(s)}get animations(){return this._activeModel?.assetContainer.animationGroups.map(e=>e.name)??[]}get selectedAnimation(){return this._activeModel?.selectedAnimation??-1}set selectedAnimation(e){this._selectAnimation(e,0===this._loadOperations.size)}_selectAnimation(e,t=!0){e=Math.round(ne(e,-1,this.animations.length-1)),this._activeModel&&e!==this._activeModel.selectedAnimation&&(this._activeAnimationObservers.forEach(e=>e.remove()),this._activeAnimationObservers=[],this._activeModel.selectedAnimation=e,this._activeAnimation&&(this._activeAnimationObservers=[this._activeAnimation.onAnimationGroupPlayObservable.add(()=>{this.onIsAnimationPlayingChanged.notifyObservers()}),this._activeAnimation.onAnimationGroupPauseObservable.add(()=>{this.onIsAnimationPlayingChanged.notifyObservers()}),this._activeAnimation.onAnimationGroupEndObservable.add(()=>{this.onIsAnimationPlayingChanged.notifyObservers(),this.onAnimationProgressChanged.notifyObservers()})],this._reframeCamera(t)),this.onSelectedAnimationChanged.notifyObservers(),this.onAnimationProgressChanged.notifyObservers())}get isAnimationPlaying(){return this._activeModelBacking?._animationPlaying()??!1}get animationSpeed(){return this._animationSpeed}set animationSpeed(e){this._animationSpeed=e,this._applyAnimationSpeed(),this.onAnimationSpeedChanged.notifyObservers()}get animationProgress(){return this._activeAnimation?this._activeAnimation.getCurrentFrame()/(this._activeAnimation.to-this._activeAnimation.from):0}set animationProgress(e){this._activeAnimation&&(this._activeAnimation.goToFrame(e*(this._activeAnimation.to-this._activeAnimation.from)),this.onAnimationProgressChanged.notifyObservers(),this._autoRotationBehavior.resetLastInteractionTime(),this._markSceneMutated(),this._triggerIblShadowsVoxelization())}get _activeAnimation(){return this._activeModel?.assetContainer.animationGroups[this._activeModel?.selectedAnimation]??null}get materialVariants(){return this._activeModel?.materialVariantsController?.variants??[]}get selectedMaterialVariant(){return this._activeModel?.selectedMaterialVariant??null}set selectedMaterialVariant(e){this._activeModel&&e&&(this._activeModel.selectedMaterialVariant=e)}get camerasAsHotSpots(){return this._camerasAsHotSpots}set camerasAsHotSpots(e){this._camerasAsHotSpots!==e&&(this._camerasAsHotSpots=e,this._toggleCamerasAsHotSpots(),this.onCamerasAsHotSpotsChanged.notifyObservers())}async _getDefaultMaterialAsync(){return this._defaultMaterialPromise??=(async()=>{const{PBRMaterial:e}=await import("./pbrMaterial-Cl1OI2Xo.esm.min.js"),t=new e("Viewer Default Material",this._scene);return t.albedoColor=new Xe(.4,.4,.4),t.metallic=0,t.roughness=1,t.baseDiffuseRoughness=1,t.microSurface=0,t})(),await this._defaultMaterialPromise}async _loadModel(e,t,s){this._throwIfDisposedOrAborted(s);const i=this._beginLoadOperation(),r=t?.onProgress;delete t?.onProgress;let n=null;const a=t?.pluginOptions?.gltf?.extensionOptions?.KHR_materials_variants?.onLoaded;if(delete t?.pluginOptions?.gltf?.extensionOptions?.KHR_materials_variants?.onLoaded,!t?.pluginExtension&&this._options?.pluginExtension&&((t=t??{}).pluginExtension=this._options.pluginExtension),!t?.pluginExtension){let s=!1;if("string"==typeof e){const t=Kc(e);t&&".spz"===t.toLowerCase()&&(s=!0)}else e instanceof File&&e.name.toLowerCase().endsWith(".spz")&&(s=!0);s&&((t=t??{}).pluginExtension=".spz")}t=hc({onProgress:e=>{r?.(e),i.progress=e.lengthComputable?e.loaded/e.total:null},pluginOptions:{gltf:{transparencyAsCoverage:!0,useOpenPBR:t?.useOpenPBR??this._options?.useOpenPBR??pu.useOpenPBR,extensionOptions:{KHR_materials_variants:{onLoaded:e=>{a?.(e),n=e}}}},...".spz"===t?.pluginExtension?{splat:{flipY:!0}}:{}}},t??{}),this._snapshotHelper?.disableSnapshotRendering();try{const s=await ph(e,this._scene,t);!function(e){const t=[Gi.UVKind,Gi.UV2Kind,Gi.UV3Kind,Gi.UV4Kind,Gi.UV5Kind,Gi.UV6Kind];for(const s of e){const e=new Set(t),i=s.material?.getActiveTextures();if(i)for(const s of i)e.delete(t[s.coordinatesIndex]);e.forEach(e=>{s.isVerticesDataPresent(e)&&s.removeVerticesData(e)})}}(s.meshes.filter(e=>e instanceof Xn));const i=s.meshes.filter(e=>!e.material);if(i.length>0){const e=await this._getDefaultMaterialAsync();for(const t of i)t.material=e}s.animationGroups.forEach(e=>{e.start(!0,this.animationSpeed),e.pause()}),s.addAllToScene(),this._snapshotHelper?.fixMeshes(s.meshes);let r=-1;const a=[],o=this,h={assetContainer:s,materialVariantsController:n,_animationPlaying:()=>{const e=s.animationGroups[r];return e?.isPlaying??!1},_shouldRender:()=>{const e=h?.assetContainer.animationGroups.some(e=>e.animatables.some(e=>e.animationStarted));return h._animationPlaying()||e},getHotSpotToRef:(e,t)=>this._getHotSpotToRef(s,e,t),dispose:()=>{this._snapshotHelper?.disableSnapshotRendering(),s.meshes.forEach(e=>this._meshDataCache.delete(e)),s.dispose();const e=this._loadedModelsBacking.indexOf(h);-1!==e&&(this._loadedModelsBacking.splice(e,1),h===this._activeModel&&this._setActiveModel(null)),this._snapshotHelper?.enableSnapshotRendering(),this._markSceneMutated()},getWorldBounds:(e=r)=>{let t=a[e];return t||(t=du([h]),t&&(a[e]=t)),t},resetWorldBounds:()=>{a.length=0},get selectedAnimation(){return r},set selectedAnimation(e){let t=s.animationGroups[r];const i=t?.isPlaying??!1;t&&(t.pause(),t.goToFrame(0)),r=e,t=s.animationGroups[r],d(o._updateShadows(o._shadowQuality)),t&&(t.goToFrame(0),t.play(!0),i||t.pause())},makeActive:e=>{this._setActiveModel(h,e)},set selectedMaterialVariant(e){if(n){let t=e;t||(t=n.variants[0]),t!==n.selectedVariant&&n.variants.includes(t)&&(o._snapshotHelper?.disableSnapshotRendering(),n.selectedVariant=t,o._snapshotHelper?.enableSnapshotRendering(),o._markSceneMutated(),o.onSelectedMaterialVariantChanged.notifyObservers())}},get selectedMaterialVariant(){return n?n.selectedVariant:null}};return this._loadedModelsBacking.push(h),h}catch(e){throw this.onModelError.notifyObservers(e),e}finally{i.dispose(),this._snapshotHelper?.enableSnapshotRendering(),this._markSceneMutated()}}async loadModel(e,t,s){return await super.loadModel(e,t,s)}async _loadModelImpl(e,t,s,i){if(this._activeModel?.dispose(),this._activeModelBacking=null,this.selectedAnimation=-1,e){const r=await this._loadModel(e,t,i);u(s,i),r.makeActive(Object.assign({source:e,interpolateCamera:!1},t)),this._reset(!1,"camera","animation","material-variant")}}async _afterLoadModel(e,t,s,r){const n=this._loadedModels.some(e=>e.assetContainer.materials.some(hu)||e.assetContainer.meshes.some(e=>null!=e.material&&hu(e.material)));if(!this._scene.environmentTexture&&n){const e=s?AbortSignal.any([s,r]):r;if(await this.resetEnvironment({lighting:!0},e),r.aborted)throw new i(r.reason)}this._startSceneOptimizer(!0)}async _updateShadowsImpl(e,t,s){this._snapshotHelper?.disableSnapshotRendering();try{if("none"===e)this._disposeShadows();else{if(!this._reflectionTexture){const e=t?AbortSignal.any([t,s]):s;await this.loadEnvironment("auto",{lighting:!0,skybox:!1},e)}"normal"===e?await this._updateShadowMap(s):"high"===e&&await this._updateEnvShadow(s)}}finally{this._snapshotHelper?.enableSnapshotRendering(),this._markSceneMutated()}}_changeShadowLightIntensity(){this._shadowState.high&&(this._shadowState.high.pipeline.resetAccumulation(),this._startIblShadowsRenderTime())}_rotateShadowLightWithEnvironment(){"normal"===this._shadowQuality&&this._shadowState.normal?this._shadowState.normal.light&&this._shadowState.normal.refreshLightPositionDirection(this._environmentRotation):"high"===this._shadowQuality&&this._shadowState.high&&(this._shadowState.high.pipeline?.resetAccumulation(),this._startIblShadowsRenderTime())}_startIblShadowsRenderTime(){if(this._shadowState.high){null!=this._shadowState.high.renderTimer?clearTimeout(this._shadowState.high.renderTimer):this._snapshotHelper?.disableSnapshotRendering(),this._shadowState.high.shouldRender=!0;const e=()=>{this._shadowState.high&&(this._shadowState.high.shouldRender=!1,this._shadowState.high.renderTimer=null),this._snapshotHelper?.enableSnapshotRendering()};this._shadowState.high.renderTimer=setTimeout(e,4e3*this._shadowState.high.pipeline.shadowRemanence)}}async _updateEnvShadow(e){const[{ShaderMaterial:t},{ShaderLanguage:s},{CreateDisc:i},{IblShadowsRenderPipeline:r}]=await Promise.all([import("./shaderMaterial-dqH3UF0Q.esm.min.js"),import("./shaderLanguage-R84fVnRr.esm.min.js"),import("./discBuilder-CeYpSEZS.esm.min.js"),import("./iblShadowsRenderPipeline-Cex8mL60.esm.min.js"),import("./engine.multiRender-g60Hn4RA.esm.min.js"),import("./engine.multiRender-Y4zQH9W8.esm.min.js"),import("./postProcessRenderPipelineManagerSceneComponent-C69Ubh5a.esm.min.js")]);this._throwIfDisposedOrAborted(e,this._loadModelAbortSignal,this._loadEnvironmentLightingAbortSignal,this._loadEnvironmentSkyboxAbortSignal);let n=this._shadowState.high;const a=du(this._loadedModelsBacking);if(!a)return n?.ground.setEnabled(!1),void this._log("No models loaded, cannot create shadows.");const o=4*xe.FromArray(a.size).length(),h=()=>{if(this._shadowState.high){this._snapshotHelper?.disableSnapshotRendering();const{pipeline:e,groundMaterial:t,ground:s}=this._shadowState.high;t?.setVector2("renderTargetSize",new Me(this._scene.getEngine().getRenderWidth(),this._scene.getEngine().getRenderHeight())),t?.setFloat("shadowOpacity",e.shadowOpacity),t?.setTexture("shadowTexture",e._getAccumulatedTexture());const i=4*e?.voxelGridSize;s?.scaling.set(i,i,i),this._snapshotHelper?.enableSnapshotRendering(),this._markSceneMutated()}};if(this._snapshotHelper?.disableSnapshotRendering(),!n){const e=new r("ibl shadows",this._scene,{resolutionExp:6,sampleDirections:3,ssShadowsEnabled:!0,shadowRemanence:.7,triPlanarVoxelization:!0},[this._camera]);e.toggleShadow(!1);const s=this._scene.getEngine().isWebGPU?1:0,l={attributes:["position","uv"],uniforms:["world","worldView","worldViewProjection","view","projection","renderTargetSize","shadowOpacity"],samplers:["shadowTexture"],shaderLanguage:s,extraInitializationsAsync:async()=>{1===s?await Promise.all([import("./envShadowGround.vertex-Buydq8ui.esm.min.js"),import("./envShadowGround.fragment-C1ThKxQU.esm.min.js")]):await Promise.all([import("./envShadowGround.vertex-Cui2aHT1.esm.min.js"),import("./envShadowGround.fragment-BF9R_WzU.esm.min.js")])}},c=new t("envShadowGroundMaterial",this._scene,"envShadowGround",l);c.alphaMode=dt.ALPHA_MULTIPLY,c.alpha=.99,h(),e.onShadowTextureReadyObservable.addOnce(h);const u=this._engine.onResizeObservable.add(()=>{h(),e?.resetAccumulation(),this._startIblShadowsRenderTime()});this._camera.onViewMatrixChangedObservable.add(()=>{this._startIblShadowsRenderTime()});const d=i("envShadowGround",{radius:o,tessellation:64},this._scene);d.setEnabled(!1),d.rotation.x=Math.PI/2,d.position.y=a.extents.min[1],d.material=c,n={pipeline:e,groundMaterial:c,resizeObserver:u,shouldRender:!0,ground:d}}n.pipeline.clearShadowCastingMeshes(),n.pipeline.clearShadowReceivingMaterials();for(const e of this._loadedModelsBacking){const t=e.assetContainer.meshes;for(const e of t)e instanceof Xn&&(n.pipeline.addShadowCastingMesh(e),e.material&&n.pipeline.addShadowReceivingMaterial(e.material))}n.pipeline.onVoxelizationCompleteObservable.addOnce(()=>{this._snapshotHelper?.disableSnapshotRendering(),h(),n.pipeline.toggleShadow(!0),n.ground.setEnabled(!0),this._snapshotHelper?.enableSnapshotRendering(),this._markSceneMutated()}),n.ground.position.y=a.extents.min[1],n.pipeline.updateSceneBounds(),n.pipeline.updateVoxelization(),n.pipeline.resetAccumulation(),this._shadowState.normal?.ground.setEnabled(!1),this._shadowState.high=n,this._startIblShadowsRenderTime(),this.isAnimationPlaying&&this._startIblShadowsAnimationUpdate(),this._snapshotHelper?.enableSnapshotRendering(),this._markSceneMutated()}async _findIblDominantDirection(e){return this._reflectionTexture&&e.iblSource!==this._reflectionTexture&&(e.iblSource=this._reflectionTexture,await e.renderWhenReady()),await e.findDominantDirection()}async _updateShadowMap(e){const[{CreateDisc:t},{RenderTargetTexture:s},{ShadowGenerator:i},{IblCdfGenerator:r}]=await Promise.all([import("./discBuilder-CeYpSEZS.esm.min.js"),import("./renderTargetTexture-Wv-A2q6-.esm.min.js"),import("./shadowGenerator-BZdd1hPe.esm.min.js"),import("./iblCdfGenerator-BikPHS7-.esm.min.js").then(function(e){return e.i}),import("./iblCdfGeneratorSceneComponent-DFpS0xoG.esm.min.js"),import("./shadowGeneratorSceneComponent-DHA2NZSM.esm.min.js")]);this._throwIfDisposedOrAborted(e,this._loadModelAbortSignal,this._loadEnvironmentLightingAbortSignal,this._loadEnvironmentSkyboxAbortSignal);let n=this._shadowState.normal;const a=du(this._loadedModelsBacking);if(!a)return n?.ground.setEnabled(!1),void this._log("No models loaded, cannot create shadows.");const o=xe.FromArray(a.size).length();if("normal"!==this._shadowQuality)return;const h=n?.iblDirection.iblCdfGenerator?n?.iblDirection.iblCdfGenerator:new r(this._engine),l=await this._findIblDominantDirection(h);this._throwIfDisposedOrAborted(e,this._loadModelAbortSignal,this._loadEnvironmentLightingAbortSignal,this._loadEnvironmentSkyboxAbortSignal),this._snapshotHelper?.disableSnapshotRendering();const c=20*o,u=3*o,d=l?ne(l.length(),0,1):.5;if(!n){const e=new ao("shadowMapDirectionalLight",xe.Zero(),this._scene);e.autoUpdateExtends=!1;const r=new i(4096,e);r.setDarkness(ie(.8,.2,d)),r.setTransparencyShadow(!0),r.filteringQuality=i.QUALITY_HIGH,r.useBlurExponentialShadowMap=!0,r.enableSoftTransparentShadow=!0,r.bias=o/1e3,r.useKernelBlur=!0,r.blurKernel=Math.floor(ie(64,8,d));const _=r.getShadowMap();_&&(_.refreshRate=s.REFRESHRATE_RENDER_ONEVERYFRAME,_.renderList=this._scene.meshes.slice());const p=new yh("shadowMapGroundMaterial",this._scene);p.shadowOnly=!0,p.primaryColor=Xe.Black();const f=t("shadowMapGround",{radius:c,tessellation:64},this._scene);f.rotation.x=Math.PI/2,f.receiveShadows=!0,f.position.y=a.extents.min[1],f.material=p;const g=n={light:e,generator:r,ground:f,shouldRender:!0,iblDirection:{iblCdfGenerator:h,positionFactor:u,direction:l},refreshLightPositionDirection(e){let t=this.iblDirection.direction.normalizeToNew();this.light.getScene().useRightHandedSystem&&(t.z*=-1);const s=Ie.RotationY(-1*e);t=xe.TransformCoordinates(t,s),this.light.position=t.scale(this.iblDirection.positionFactor),this.light.direction=function(e){const t=e.clone();return t.y>0&&(t.y*=-1),t.y>-.01&&(t.y=Math.min(10*t.y,-.05)),t}(t.negate())}};await new Promise((e,t)=>{Yt(()=>_.isReadyForRendering(),()=>e(void 0),()=>t(new Error("Failed to get shadow map generator ready")))}),r.onAfterShadowMapRenderObservable.addOnce(()=>{g.shouldRender=!1})}n.iblDirection.direction=l,n.iblDirection.positionFactor=u,n.refreshLightPositionDirection(this._environmentRotation),n.light.shadowFrustumSize=4*o;for(const e of this._loadedModelsBacking)for(const t of e.assetContainer.meshes)n.generator.addShadowCaster(t,!1),t.receiveShadows=!0;n.ground.position.y=a.extents.min[1],n.ground.scaling.set(c,c,c),this._shadowState.high?.ground.setEnabled(!1),this._shadowState.high?.pipeline.toggleShadow(!1),n.ground.setEnabled(!0),this._shadowState.normal=n,this._snapshotHelper?.enableSnapshotRendering(),this._markSceneMutated()}_disposeShadows(){if(this._stopIblShadowsAnimationUpdate(),this._snapshotHelper?.disableSnapshotRendering(),!this._shadowState)return;for(const e of this._loadedModelsBacking){const t=e.assetContainer.meshes,s=e.assetContainer.meshes[0];this._shadowState.normal?.generator.removeShadowCaster(s,!0),s.receiveShadows=!1;for(const e of t)e instanceof Xn&&(this._shadowState.high?.pipeline.removeShadowCastingMesh(e),e.material&&this._shadowState.high?.pipeline.removeShadowReceivingMaterial(e.material))}const e=this._shadowState.high,t=this._shadowState.normal;t&&(t.generator.dispose(),t.light.dispose(),t.ground.dispose(!0,!0),t.iblDirection.iblCdfGenerator.dispose(),this._scene.removeMesh(t.ground)),e&&(e.resizeObserver.remove(),e.pipeline.dispose(),e.ground.dispose(!0,!0),this._scene.removeMesh(e.ground),e.renderTimer&&clearTimeout(e.renderTimer)),delete this._shadowState.normal,delete this._shadowState.high,this.onShadowsConfigurationChanged.clear(),this._snapshotHelper?.enableSnapshotRendering(),this._markSceneMutated()}async resetEnvironment(e,t){const s=[];if(e?.lighting&&this._scene.materials.some(hu)){const i={...e,skybox:!1};e={...e,lighting:!1},s.push(this._updateEnvironment("auto",i,t))}s.push(this._updateEnvironment(void 0,e,t)),await Promise.all(s)}_setEnvironmentLighting(e){this._reflectionTexture=e,this._scene.environmentTexture=this._reflectionTexture,this._reflectionTexture.level=this.environmentConfig.intensity,this._reflectionTexture.rotationY=this.environmentConfig.rotation}_setEnvironmentSkybox(e){this._skyboxTexture=e,this._skyboxTexture.level=this.environmentConfig.intensity,this._skyboxTexture.rotationY=this.environmentConfig.rotation,this._skybox=function(e,t,s,i){const r=e.blockMaterialDirtyMechanism;e.blockMaterialDirtyMechanism=!0;try{const r=Fh("hdrSkyBox",{sideOrientation:Xn.BACKSIDE},e),n=new yh("skyBox",e);return n.imageProcessingConfiguration=new Eo,n.reflectionTexture=s,s.coordinatesMode=Ch.SKYBOX_MODE,n.reflectionBlur=i,r.material=n,r.isPickable=!1,r.infiniteDistance=!0,r.applyFog=!1,cu(r,t),r}finally{e.blockMaterialDirtyMechanism=r}}(this._scene,this._camera,this._skyboxTexture,this.environmentConfig.blur),this._skybox.setEnabled(!0),this._snapshotHelper?.fixMeshes([this._skybox]),this._updateAutoClear()}async _loadEnvironmentImpl(e,t,s,i){const r=async()=>(await import("./defaultEnvironment-DPUnnTO0.esm.min.js")).default,n=async e=>{await new Promise((t,s)=>{const i=e.onLoadObservable.addOnce(()=>{r.remove(),t()}),r=Ch.OnTextureLoadErrorObservable.add(t=>{t===e&&(i.remove(),r.remove(),s(new Error("Failed to load environment texture.")))})})},a=e?"auto"===e?"auto":"url":"none";this._environmentLightingMode=t.lighting?a:this._environmentLightingMode,this._environmentSkyboxMode=t.skybox?a:this._environmentSkyboxMode;let o=this._reflectionTexture?.url,h=this._skyboxTexture?.url;this._snapshotHelper?.disableSnapshotRendering();try{"auto"===this._environmentLightingMode&&"auto"===this._environmentSkyboxMode?o=h=await r():("auto"!==this._environmentLightingMode&&t.lighting&&(o=e),"auto"!==this._environmentSkyboxMode&&t.skybox&&(h=e),"auto"===this._environmentLightingMode&&(o=h??await r()),"auto"===this._environmentSkyboxMode&&(h=o??await r()));const a=[];if(o!==this._reflectionTexture?.url)if(o){const e=this._reflectionTexture;if(o===this._skyboxTexture?.url){const e=this._skyboxTexture.clone();e.coordinatesMode=Ch.CUBIC_MODE,this._setEnvironmentLighting(e)}else{let e=t;"auto"===this._environmentLightingMode&&(e={...e,extension:".env"});const s=await lu(o,this._scene,e.extension);a.push(n(s)),this._setEnvironmentLighting(s)}e?.dispose()}else this._reflectionTexture?.dispose(),this._reflectionTexture=null,this._scene.environmentTexture=null;if(h!==this._skyboxTexture?.url)if(h){const e=this._skybox,s=this._skyboxTexture;if(h===this._reflectionTexture?.url)this._setEnvironmentSkybox(this._reflectionTexture.clone());else{let e=t;"auto"===this._environmentSkyboxMode&&(e={...e,extension:".env"});const s=await lu(h,this._scene,e.extension);a.push(n(s)),this._setEnvironmentSkybox(s)}e?.dispose(void 0,!0),s?.dispose()}else this._skybox?.dispose(void 0,!0),this._skyboxTexture=null,this._skybox=null,this._updateAutoClear();await Promise.all(a),u(s,i),this._updateLight(),d(this._updateShadows(this._shadowQuality)),this.onEnvironmentChanged.notifyObservers()}catch(e){throw this.onEnvironmentError.notifyObservers(e),e}finally{this._snapshotHelper?.enableSnapshotRendering(),this._markSceneMutated()}}toggleAnimation(){this.isAnimationPlaying?this.pauseAnimation():this.playAnimation()}playAnimation(){this._activeAnimation?.play(!0),this._startIblShadowsAnimationUpdate()}async pauseAnimation(){this._activeAnimation?.pause(),this._stopIblShadowsAnimationUpdate(),this._triggerIblShadowsVoxelization()}_triggerIblShadowsVoxelization(){if(this._shadowState.high){if(this._shadowState.high.voxelizationInProgress)return void(this._shadowState.high.voxelizationDirty=!0);this._shadowState.high.voxelizationInProgress=!0,this._shadowState.high.pipeline.updateSceneBounds(),this._shadowState.high.pipeline.updateVoxelization(),this._shadowState.high.pipeline.onVoxelizationCompleteObservable.addOnce(()=>{if(this._shadowState.high&&(this._shadowState.high.voxelizationInProgress=!1,this._shadowState.high.pipeline.resetAccumulation(),this._shadowState.high.voxelizationDirty))return this._shadowState.high.voxelizationDirty=!1,void this._triggerIblShadowsVoxelization();this._startIblShadowsRenderTime()})}}_startIblShadowsAnimationUpdate(){if(this._shadowState.high&&!this._iblShadowsAnimationObserver){let e=0;this._iblShadowsAnimationObserver=this._scene.onAfterAnimationsObservable.add(()=>{const t=this._shadowState.high;t&&e++%2==0&&(t.voxelizationInProgress||(t.voxelizationInProgress=!0,t.pipeline.updateVoxelization(),t.pipeline.onVoxelizationCompleteObservable.addOnce(()=>{this._shadowState.high&&this._shadowState.high===t&&(t.voxelizationInProgress=!1,t.pipeline.resetAccumulation(),this._startIblShadowsRenderTime())})))})}}_stopIblShadowsAnimationUpdate(){this._iblShadowsAnimationObserver&&(this._scene.onAfterAnimationsObservable.remove(this._iblShadowsAnimationObserver),this._iblShadowsAnimationObserver=null)}resetCamera(e){null==e&&(e=this.selectedAnimation!==(this._options?.selectedAnimation??0)),e?this._reframeCamera(!0):this._reset(!0,"camera")}updateCamera(e){this._reframeCameraFromBounds(!0,this._loadedModels,e.alpha??NaN,e.beta??NaN,e.radius??NaN,e.targetX??NaN,e.targetY??NaN,e.targetZ??NaN)}_resetEnvironment(){const e=this._options?.clearColor??pu.clearColor;this.clearColor={r:e[0],g:e[1],b:e[2],a:e[3]??1},this.environmentConfig={intensity:this._options?.environmentConfig?.intensity??pu.environmentConfig.intensity,blur:this._options?.environmentConfig?.blur??pu.environmentConfig.blur,rotation:this._options?.environmentConfig?.rotation??pu.environmentConfig.rotation},this._options?.environmentLighting===this._options?.environmentSkybox?d(this._updateEnvironment(this._options?.environmentLighting,{lighting:!0,skybox:!0})):(d(this._updateEnvironment(this._options?.environmentLighting,{lighting:!0})),d(this._updateEnvironment(this._options?.environmentSkybox,{skybox:!0})))}_resetAnimation(){this.animationSpeed=this._options?.animationSpeed??pu.animationSpeed,this.selectedAnimation=this._options?.selectedAnimation??0,this._options?.animationAutoPlay?this.playAnimation():this.pauseAnimation()}_resetCamera(e){const t=Number(this._options?.cameraOrbit?.[0]),s=Number(this._options?.cameraOrbit?.[1]),i=Number(this._options?.cameraOrbit?.[2]),r=Number(this._options?.cameraTarget?.[0]),n=Number(this._options?.cameraTarget?.[1]),a=Number(this._options?.cameraTarget?.[2]);this._reframeCameraFromBounds(e,this._loadedModels,isNaN(t)?void 0:t,isNaN(s)?void 0:s,isNaN(i)?void 0:i,isNaN(r)?void 0:r,isNaN(n)?void 0:n,isNaN(a)?void 0:a),this.cameraAutoOrbit={enabled:this._options?.cameraAutoOrbit?.enabled??pu.cameraAutoOrbit.enabled,speed:this._options?.cameraAutoOrbit?.speed??pu.cameraAutoOrbit.speed,delay:this._options?.cameraAutoOrbit?.delay??pu.cameraAutoOrbit.delay}}_resetPostProcessing(){this.postProcessing={toneMapping:this._options?.postProcessing?.toneMapping??pu.postProcessing.toneMapping,contrast:this._options?.postProcessing?.contrast??pu.postProcessing.contrast,exposure:this._options?.postProcessing?.exposure??pu.postProcessing.exposure,ssao:this._options?.postProcessing?.ssao??pu.postProcessing.ssao}}dispose(){this._isDisposed||(this.selectedAnimation=-1,this.animationProgress=0,this._camerasAsHotSpotsAbortController?.abort(new i("The viewer is being disposed.")),this._ssaoAbortController?.abort(new i("The viewer is being disposed.")),this._renderLoopController?.dispose(),this._activeModel?.dispose(),this._loadedModelsBacking.forEach(e=>e.dispose()),this._disposeShadows(),this._scene.dispose(),this._imageProcessingConfigurationObserver.remove(),this._beforeRenderObserver?.remove(),this._snapshotHelper?.dispose(),this.onModelChanged.remove(this._objectListModelChangedObserver),super.dispose())}getHotSpotToRef(e,t){return this._getHotSpotToRef(this._loadedModels.flatMap(e=>e.assetContainer.meshes),e,t)}_getHotSpotToRef(...e){const[t,s,i]=e,r=Array.isArray(t)?t:t?.meshes,n=this._tempVectors[2],a=this._tempVectors[1],o=this._tempVectors[0];if("surface"===s.type){const e=r?.[s.meshIndex];if(!e)return!1;if(!function(e,t,s,i){s.set(0,0,0);for(let i=0;i<3;i++){if(!wh(e,t.pointIndex[i],Ce.Vector3[i]))return!1;Ce.Vector3[i].scaleAndAddToRef(t.barycentric[i],s)}if(xe.TransformCoordinatesToRef(s,e.getWorldMatrix(),s),i){const t=Ce.Vector3[0],s=Ce.Vector3[1],r=Ce.Vector3[2],n=Ce.Vector3[3],a=Ce.Vector3[4];n.copyFrom(s),n.subtractInPlace(t),a.copyFrom(r),a.subtractInPlace(t),n.normalize(),a.normalize(),xe.CrossToRef(n,a,i),e.material&&e.material.sideOrientation===(e.getScene().useRightHandedSystem?dt.MATERIAL_ClockWiseSideOrientation:dt.MATERIAL_CounterClockWiseSideOrientation)&&i.scaleInPlace(-1),xe.TransformNormalToRef(i,e.getWorldMatrix(),i),i.normalize()}return!0}(e,s,a,n))return!1}else a.copyFromFloats(s.position[0],s.position[1],s.position[2]),n.copyFromFloats(s.normal[0],s.normal[1],s.normal[2]);const h=this._camera.viewport.width*this._engine.getRenderWidth()*this._engine.getHardwareScalingLevel(),l=this._camera.viewport.height*this._engine.getRenderHeight()*this._engine.getHardwareScalingLevel(),c=this._scene;xe.ProjectToRef(a,Ie.IdentityReadOnly,c.getTransformMatrix(),new Ks(0,0,h,l),o),i.screenPosition[0]=o.x,i.screenPosition[1]=o.y,i.worldPosition[0]=a.x,i.worldPosition[1]=a.y,i.worldPosition[2]=a.z;const u=this._tempVectors[3];return u.copyFrom(this._camera.globalPosition),u.subtractInPlace(a),u.normalize(),i.visibility=xe.Dot(u,n),!0}queryHotSpot(e,t){return null!=this._queryHotSpot(e,t)}focusHotSpot(e){const t=new g,s=this._queryHotSpot(e,t);if(s){this.pauseAnimation();const e=s.cameraOrbit??[void 0,void 0,void 0];return this._camera.interpolateTo(e[0],e[1],e[2],new xe(t.worldPosition[0],t.worldPosition[1],t.worldPosition[2])),!0}return!1}_queryHotSpot(e,t){const s=this.hotSpots?.[e];return s&&this.getHotSpotToRef(s,t)?s:null}async _addCameraHotSpot(e,t){if(e!==this._camera){const s=await this._createHotSpotFromCamera(e);s&&!t?.aborted&&(this.hotSpots={...this.hotSpots,[`camera-${e.name}`]:s})}}_removeCameraHotSpot(e){delete this.hotSpots[`camera-${e.name}`],this.hotSpots={...this.hotSpots}}_toggleCamerasAsHotSpots(){if(this.camerasAsHotSpots){const e=this._camerasAsHotSpotsAbortController=new AbortController;this._scene.cameras.forEach(async t=>await this._addCameraHotSpot(t,e.signal))}else this._camerasAsHotSpotsAbortController?.abort(),this._camerasAsHotSpotsAbortController=null,this._scene.cameras.forEach(e=>this._removeCameraHotSpot(e))}async _createHotSpotFromCamera(e){if(e instanceof so){const t=e.target.asArray();return{type:"world",position:t,normal:t,cameraOrbit:[e.alpha,e.beta,e.radius]}}return this._activeModel?await _u(this._activeModel,e):null}get _shouldRender(){return!this._autoSuspendRendering||this._sceneMutated||!1===this._snapshotHelper?.isReady||this._shadowState.normal?.shouldRender||this._shadowState.high?.shouldRender||!1===this._ssaoPipeline?.isReady()||this._loadedModelsBacking.some(e=>e._shouldRender())||this._loadOperations.size>0}_markSceneMutated(){this._sceneMutated=!0}_suspendRendering(){this._renderLoopController?.dispose(),this._suspendRenderCount++;let e=!1;return{dispose:()=>{e||(e=!0,this._suspendRenderCount--,0===this._suspendRenderCount&&this._beginRendering())}}}_beginRendering(){if(!this._renderLoopController){let e=!1;const t=()=>{this._log("Viewer Resumed Rendering"),this._isIdle=!1,this._engine.setHardwareScalingLevel(this._lastHardwareScalingLevel),this._engine.performanceMonitor.enable(),this._snapshotHelper?.enableSnapshotRendering(),this._startSceneOptimizer()},s=()=>{this._log("Viewer Suspended Rendering"),this._isIdle=!0,this._renderedLastFrame=!1,e=!1,this._lastHardwareScalingLevel=this._engine.getHardwareScalingLevel(),this._stopSceneOptimizer(),this._snapshotHelper?.disableSnapshotRendering(),this._engine.performanceMonitor.disable(),this._engine.setHardwareScalingLevel(this._defaultHardwareScalingLevel),this._engine.beginFrame(),this._scene.render(),this._engine.endFrame()},i=()=>{let i=this._shouldRender;i||!this._renderedLastFrame||e||(e=this._scene.isReady(!0),i=!0),i?(this._renderedLastFrame||(null!==this._renderedLastFrame&&t(),this._renderedLastFrame=!0),this._sceneMutated=!1,this._scene.render(),this._camera.panningSensibility=5e3/this._camera.radius,this._camera.speed=.2*this._camera.radius,this._camera.inputs.attached.keyboard.zoomingSensibility=500/this._camera.radius,this.isAnimationPlaying&&(this.onAnimationProgressChanged.notifyObservers(),this._autoRotationBehavior.resetLastInteractionTime())):(this._camera.update(),this._renderedLastFrame&&s())};this._engine.runRenderLoop(i);let r=!1;this._renderLoopController={dispose:()=>{r||(r=!0,this._engine.stopRenderLoop(i),this._renderLoopController=null,this._renderedLastFrame&&s())}}}}_reframeCamera(e=!1,t=this._loadedModelsBacking){this._reframeCameraFromBounds(e,t)}_getWorldBounds(e){return du(e)}_getCameraConfig(e){let t=1,s=xe.Zero();const i=this._getWorldBounds(e);i&&(this._camera.lowerRadiusLimit=null,t=1.1*xe.FromArray(i.size).length(),s=xe.FromArray(i.center),isFinite(t)||(t=1,s.copyFromFloats(0,0,0)));return{radius:t,target:s,lowerRadiusLimit:.001*t,upperRadiusLimit:5*t,minZ:.001*t,maxZ:1e3*t}}_reframeCameraFromBounds(e,t,s,i,r,n,a,o){const h=xe.Zero();let l=T,c=E;const{radius:u,target:d,lowerRadiusLimit:_,upperRadiusLimit:p,minZ:f,maxZ:g}=this._getCameraConfig(t);this._camera.lowerRadiusLimit=_,this._camera.upperRadiusLimit=p,this._camera.minZ=f,this._camera.maxZ=g,l=s??l,c=i??c;const m=r??u;h.x=n??d.x,h.y=a??d.y,h.z=o??d.z,e?this._camera.interpolateTo(l,c,m,h,void 0,.1):(this._camera.stopInterpolation(),isNaN(l)||(this._camera.alpha=l),isNaN(c)||(this._camera.beta=c),isNaN(m)||(this._camera.radius=m),this._camera.setTarget(new xe(isNaN(h.x)?this._camera.target.x:h.x,isNaN(h.y)?this._camera.target.y:h.y,isNaN(h.z)?this._camera.target.z:h.z),void 0,void 0,!0)),this._camera.wheelDeltaPercentage=.01,this._camera.useNaturalPinchZoom=!0,cu(this._skybox,this._camera)}_updateLight(){let e;if(0===this._loadedModels.length)e=!1;else{const t=this._loadedModels.some(e=>e.assetContainer.lights.length>0),s=!!this._reflectionTexture,i=this._loadedModels.some(e=>e.assetContainer.materials.some(e=>!hu(e)));e=!t&&(!s||i)}e?this._light||(this._light=new ho("defaultLight",xe.Up(),this._scene)):(this._light?.dispose(),this._light=null)}_applyAnimationSpeed(){this._activeModel?.assetContainer.animationGroups.forEach(e=>e.speedRatio=this._animationSpeed)}async _pick(e,t){if(await import("./ray-DM87Gj5w.esm.min.js"),this._loadedModels.length>0){const s=this._loadedModelsBacking.flatMap(e=>e.assetContainer.meshes);s.forEach(e=>{let t=this._meshDataCache.get(e);t||(t={},this._meshDataCache.set(e,t)),e.refreshBoundingInfo({applyMorph:!0,applySkeleton:!0,cache:t})});const i=this._scene.pick(e,t,e=>s.includes(e));if(i.hit)return i}return null}_startSceneOptimizer(e=!1){this._stopSceneOptimizer(),e&&this._engine.setHardwareScalingLevel(this._defaultHardwareScalingLevel);const t=new Rc(60,1e3),s=new dc(void 0,1);t.addOptimization(s),this._sceneOptimizer=new bc(this._scene,t),this._sceneOptimizer.start()}_stopSceneOptimizer(){this._sceneOptimizer?.dispose(),this._sceneOptimizer=null}_log(e){this.showDebugLogs&&a.Log(e)}}ru();const gu=!0,mu=!0,Tu=!0,Eu=!0;async function Ru(e,t={}){const s=new r;t=new Proxy(t,{get(e,t){switch(t){case"antialias":return e.antialias??gu;case"adaptToDeviceRatio":return e.adaptToDeviceRatio??mu;case"enableAllFeatures":return e.enableAllFeatures??Tu;case"setMaximumLimits":return e.setMaximumLimits??Eu;case"onInitialized":return t=>{e.onInitialized?.(t),s.resolve(t)};default:return e[t]}}});const i=[];let n;switch(t.engine??("gpu"in navigator&&"chrome"in window?"WebGPU":"WebGL")){case"WebGPU":{const{WebGPUEngine:s}=await import("./webgpuEngine-Bijao1fx.esm.min.js"),i=new s(e,t);try{await i.initAsync(),n=i;break}catch{a.Warn("Failed to initialize WebGPU engine. Falling back to WebGL.")}}case"WebGL":{const{Engine:s}=await import("./engine-C2Q9MRjl.esm.min.js");n=new s(e,void 0,t);break}}if(t.onFaulted){const e=t.onFaulted,s=n.onContextLostObservable.addOnce(()=>{e(new Error("The engine context was lost."))});i.push(()=>s.remove())}const o=new(t?.viewerClass??fu)(n,t);{const t=await s.promise;let r=!1;const a=new ResizeObserver(()=>{r=!0,t.markSceneMutated()});a.observe(e),i.push(()=>a.disconnect());const o=t.scene.onBeforeRenderObservable.add(()=>{r&&(n.resize(),r=!1)});i.push(()=>o.remove()),i.push(function(e,t){let s=null;const i=new IntersectionObserver(e=>{e.length>0&&(e[e.length-1].isIntersecting?(s?.dispose(),s=null):s??=t())});return i.observe(e),{dispose:()=>i.disconnect()}}(e,()=>t.suspendRendering()).dispose)}return i.push(o.dispose.bind(o)),i.push(()=>n.dispose()),o.dispose=()=>i.forEach(e=>e()),o}
/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/const bu=globalThis,Au=bu.ShadowRoot&&(void 0===bu.ShadyCSS||bu.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,yu=Symbol(),Mu=new WeakMap;let xu=class{constructor(e,t,s){if(this._$cssResult$=!0,s!==yu)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(Au&&void 0===e){const s=void 0!==t&&1===t.length;s&&(e=Mu.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),s&&Mu.set(t,e))}return e}toString(){return this.cssText}};const Su=(e,...t)=>{const s=1===e.length?e[0]:t.reduce((t,s,i)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+e[i+1],e[0]);return new xu(s,e,yu)},vu=Au?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const s of e.cssRules)t+=s.cssText;return(e=>new xu("string"==typeof e?e:e+"",void 0,yu))(t)})(e):e,{is:Iu,defineProperty:Pu,getOwnPropertyDescriptor:Cu,getOwnPropertyNames:Ou,getOwnPropertySymbols:Du,getPrototypeOf:wu}=Object,Lu=globalThis,Fu=Lu.trustedTypes,Nu=Fu?Fu.emptyScript:"",Bu=Lu.reactiveElementPolyfillSupport,Uu=(e,t)=>e,ku={toAttribute(e,t){switch(t){case Boolean:e=e?Nu:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let s=e;switch(t){case Boolean:s=null!==e;break;case Number:s=null===e?null:Number(e);break;case Object:case Array:try{s=JSON.parse(e)}catch(e){s=null}}return s}},Gu=(e,t)=>!Iu(e,t),Vu={attribute:!0,type:String,converter:ku,reflect:!1,useDefault:!1,hasChanged:Gu};
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/Symbol.metadata??=Symbol("metadata"),Lu.litPropertyMetadata??=new WeakMap;let Hu=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Vu){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const s=Symbol(),i=this.getPropertyDescriptor(e,s,t);void 0!==i&&Pu(this.prototype,e,i)}}static getPropertyDescriptor(e,t,s){const{get:i,set:r}=Cu(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:i,set(t){const n=i?.call(this);r?.call(this,t),this.requestUpdate(e,n,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Vu}static _$Ei(){if(this.hasOwnProperty(Uu("elementProperties")))return;const e=wu(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Uu("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Uu("properties"))){const e=this.properties,t=[...Ou(e),...Du(e)];for(const s of t)this.createProperty(s,e[s])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,s]of t)this.elementProperties.set(e,s)}this._$Eh=new Map;for(const[e,t]of this.elementProperties){const s=this._$Eu(e,t);void 0!==s&&this._$Eh.set(s,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const s=new Set(e.flat(1/0).reverse());for(const e of s)t.unshift(vu(e))}else void 0!==e&&t.push(vu(e));return t}static _$Eu(e,t){const s=t.attribute;return!1===s?void 0:"string"==typeof s?s:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const s of t.keys())this.hasOwnProperty(s)&&(e.set(s,this[s]),delete this[s]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((e,t)=>{if(Au)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const s of t){const t=document.createElement("style"),i=bu.litNonce;void 0!==i&&t.setAttribute("nonce",i),t.textContent=s.cssText,e.appendChild(t)}})(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,s){this._$AK(e,s)}_$ET(e,t){const s=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,s);if(void 0!==i&&!0===s.reflect){const r=(void 0!==s.converter?.toAttribute?s.converter:ku).toAttribute(t,s.type);this._$Em=e,null==r?this.removeAttribute(i):this.setAttribute(i,r),this._$Em=null}}_$AK(e,t){const s=this.constructor,i=s._$Eh.get(e);if(void 0!==i&&this._$Em!==i){const e=s.getPropertyOptions(i),r="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:ku;this._$Em=i;const n=r.fromAttribute(t,e.type);this[i]=n??this._$Ej?.get(i)??n,this._$Em=null}}requestUpdate(e,t,s,i=!1,r){if(void 0!==e){const n=this.constructor;if(!1===i&&(r=this[e]),s??=n.getPropertyOptions(e),!((s.hasChanged??Gu)(r,t)||s.useDefault&&s.reflect&&r===this._$Ej?.get(e)&&!this.hasAttribute(n._$Eu(e,s))))return;this.C(e,t,s)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:s,reflect:i,wrapped:r},n){s&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,n??t??this[e]),!0!==r||void 0!==n)||(this._$AL.has(e)||(this.hasUpdated||s||(t=void 0),this._$AL.set(e,t)),!0===i&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,s]of e){const{wrapped:e}=s,i=this[t];!0!==e||this._$AL.has(t)||void 0===i||this.C(t,void 0,s,i)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};Hu.elementStyles=[],Hu.shadowRootOptions={mode:"open"},Hu[Uu("elementProperties")]=new Map,Hu[Uu("finalized")]=new Map,Bu?.({ReactiveElement:Hu}),(Lu.reactiveElementVersions??=[]).push("2.1.2");
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const zu=globalThis,Wu=e=>e,Xu=zu.trustedTypes,Ku=Xu?Xu.createPolicy("lit-html",{createHTML:e=>e}):void 0,Yu="$lit$",ju=`lit$${Math.random().toFixed(9).slice(2)}$`,qu="?"+ju,$u=`<${qu}>`,Zu=document,Qu=()=>Zu.createComment(""),Ju=e=>null===e||"object"!=typeof e&&"function"!=typeof e,ed=Array.isArray,td="[ \t\n\f\r]",sd=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,id=/-->/g,rd=/>/g,nd=RegExp(`>|${td}(?:([^\\s"'>=/]+)(${td}*=${td}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),ad=/'/g,od=/"/g,hd=/^(?:script|style|textarea|title)$/i,ld=(e=>(t,...s)=>({_$litType$:e,strings:t,values:s}))(1),cd=Symbol.for("lit-noChange"),ud=Symbol.for("lit-nothing"),dd=new WeakMap,_d=Zu.createTreeWalker(Zu,129);function pd(e,t){if(!ed(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==Ku?Ku.createHTML(t):t}const fd=(e,t)=>{const s=e.length-1,i=[];let r,n=2===t?"<svg>":3===t?"<math>":"",a=sd;for(let t=0;t<s;t++){const s=e[t];let o,h,l=-1,c=0;for(;c<s.length&&(a.lastIndex=c,h=a.exec(s),null!==h);)c=a.lastIndex,a===sd?"!--"===h[1]?a=id:void 0!==h[1]?a=rd:void 0!==h[2]?(hd.test(h[2])&&(r=RegExp("</"+h[2],"g")),a=nd):void 0!==h[3]&&(a=nd):a===nd?">"===h[0]?(a=r??sd,l=-1):void 0===h[1]?l=-2:(l=a.lastIndex-h[2].length,o=h[1],a=void 0===h[3]?nd:'"'===h[3]?od:ad):a===od||a===ad?a=nd:a===id||a===rd?a=sd:(a=nd,r=void 0);const u=a===nd&&e[t+1].startsWith("/>")?" ":"";n+=a===sd?s+$u:l>=0?(i.push(o),s.slice(0,l)+Yu+s.slice(l)+ju+u):s+ju+(-2===l?t:u)}return[pd(e,n+(e[s]||"<?>")+(2===t?"</svg>":3===t?"</math>":"")),i]};class gd{constructor({strings:e,_$litType$:t},s){let i;this.parts=[];let r=0,n=0;const a=e.length-1,o=this.parts,[h,l]=fd(e,t);if(this.el=gd.createElement(h,s),_d.currentNode=this.el.content,2===t||3===t){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(i=_d.nextNode())&&o.length<a;){if(1===i.nodeType){if(i.hasAttributes())for(const e of i.getAttributeNames())if(e.endsWith(Yu)){const t=l[n++],s=i.getAttribute(e).split(ju),a=/([.?@])?(.*)/.exec(t);o.push({type:1,index:r,name:a[2],strings:s,ctor:"."===a[1]?bd:"?"===a[1]?Ad:"@"===a[1]?yd:Rd}),i.removeAttribute(e)}else e.startsWith(ju)&&(o.push({type:6,index:r}),i.removeAttribute(e));if(hd.test(i.tagName)){const e=i.textContent.split(ju),t=e.length-1;if(t>0){i.textContent=Xu?Xu.emptyScript:"";for(let s=0;s<t;s++)i.append(e[s],Qu()),_d.nextNode(),o.push({type:2,index:++r});i.append(e[t],Qu())}}}else if(8===i.nodeType)if(i.data===qu)o.push({type:2,index:r});else{let e=-1;for(;-1!==(e=i.data.indexOf(ju,e+1));)o.push({type:7,index:r}),e+=ju.length-1}r++}}static createElement(e,t){const s=Zu.createElement("template");return s.innerHTML=e,s}}function md(e,t,s=e,i){if(t===cd)return t;let r=void 0!==i?s._$Co?.[i]:s._$Cl;const n=Ju(t)?void 0:t._$litDirective$;return r?.constructor!==n&&(r?._$AO?.(!1),void 0===n?r=void 0:(r=new n(e),r._$AT(e,s,i)),void 0!==i?(s._$Co??=[])[i]=r:s._$Cl=r),void 0!==r&&(t=md(e,r._$AS(e,t.values),r,i)),t}class Td{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:s}=this._$AD,i=(e?.creationScope??Zu).importNode(t,!0);_d.currentNode=i;let r=_d.nextNode(),n=0,a=0,o=s[0];for(;void 0!==o;){if(n===o.index){let t;2===o.type?t=new Ed(r,r.nextSibling,this,e):1===o.type?t=new o.ctor(r,o.name,o.strings,this,e):6===o.type&&(t=new Md(r,this,e)),this._$AV.push(t),o=s[++a]}n!==o?.index&&(r=_d.nextNode(),n++)}return _d.currentNode=Zu,i}p(e){let t=0;for(const s of this._$AV)void 0!==s&&(void 0!==s.strings?(s._$AI(e,s,t),t+=s.strings.length-2):s._$AI(e[t])),t++}}class Ed{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,s,i){this.type=2,this._$AH=ud,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=s,this.options=i,this._$Cv=i?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return void 0!==t&&11===e?.nodeType&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=md(this,e,t),Ju(e)?e===ud||null==e||""===e?(this._$AH!==ud&&this._$AR(),this._$AH=ud):e!==this._$AH&&e!==cd&&this._(e):void 0!==e._$litType$?this.$(e):void 0!==e.nodeType?this.T(e):(e=>ed(e)||"function"==typeof e?.[Symbol.iterator])(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==ud&&Ju(this._$AH)?this._$AA.nextSibling.data=e:this.T(Zu.createTextNode(e)),this._$AH=e}$(e){const{values:t,_$litType$:s}=e,i="number"==typeof s?this._$AC(e):(void 0===s.el&&(s.el=gd.createElement(pd(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===i)this._$AH.p(t);else{const e=new Td(i,this),s=e.u(this.options);e.p(t),this.T(s),this._$AH=e}}_$AC(e){let t=dd.get(e.strings);return void 0===t&&dd.set(e.strings,t=new gd(e)),t}k(e){ed(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let s,i=0;for(const r of e)i===t.length?t.push(s=new Ed(this.O(Qu()),this.O(Qu()),this,this.options)):s=t[i],s._$AI(r),i++;i<t.length&&(this._$AR(s&&s._$AB.nextSibling,i),t.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){const t=Wu(e).nextSibling;Wu(e).remove(),e=t}}setConnected(e){void 0===this._$AM&&(this._$Cv=e,this._$AP?.(e))}}class Rd{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,s,i,r){this.type=1,this._$AH=ud,this._$AN=void 0,this.element=e,this.name=t,this._$AM=i,this.options=r,s.length>2||""!==s[0]||""!==s[1]?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=ud}_$AI(e,t=this,s,i){const r=this.strings;let n=!1;if(void 0===r)e=md(this,e,t,0),n=!Ju(e)||e!==this._$AH&&e!==cd,n&&(this._$AH=e);else{const i=e;let a,o;for(e=r[0],a=0;a<r.length-1;a++)o=md(this,i[s+a],t,a),o===cd&&(o=this._$AH[a]),n||=!Ju(o)||o!==this._$AH[a],o===ud?e=ud:e!==ud&&(e+=(o??"")+r[a+1]),this._$AH[a]=o}n&&!i&&this.j(e)}j(e){e===ud?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class bd extends Rd{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===ud?void 0:e}}class Ad extends Rd{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==ud)}}class yd extends Rd{constructor(e,t,s,i,r){super(e,t,s,i,r),this.type=5}_$AI(e,t=this){if((e=md(this,e,t,0)??ud)===cd)return;const s=this._$AH,i=e===ud&&s!==ud||e.capture!==s.capture||e.once!==s.once||e.passive!==s.passive,r=e!==ud&&(s===ud||i);i&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){"function"==typeof this._$AH?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}}class Md{constructor(e,t,s){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(e){md(this,e)}}const xd=zu.litHtmlPolyfillSupport;xd?.(gd,Ed),(zu.litHtmlVersions??=[]).push("3.3.2");const Sd=globalThis;
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/let vd=class extends Hu{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=((e,t,s)=>{const i=s?.renderBefore??t;let r=i._$litPart$;if(void 0===r){const e=s?.renderBefore??null;i._$litPart$=r=new Ed(t.insertBefore(Qu(),e),e,void 0,s??{})}return r._$AI(e),r})(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return cd}};vd._$litElement$=!0,vd.finalized=!0,Sd.litElementHydrateSupport?.({LitElement:vd});const Id=Sd.litElementPolyfillSupport;Id?.({LitElement:vd}),(Sd.litElementVersions??=[]).push("4.2.2");
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const Pd=e=>(t,s)=>{void 0!==s?s.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)},Cd={attribute:!0,type:String,converter:ku,reflect:!1,hasChanged:Gu},Od=(e=Cd,t,s)=>{const{kind:i,metadata:r}=s;let n=globalThis.litPropertyMetadata.get(r);if(void 0===n&&globalThis.litPropertyMetadata.set(r,n=new Map),"setter"===i&&((e=Object.create(e)).wrapped=!0),n.set(s.name,e),"accessor"===i){const{name:i}=s;return{set(s){const r=t.get.call(this);t.set.call(this,s),this.requestUpdate(i,r,e,!0,s)},init(t){return void 0!==t&&this.C(i,void 0,e,t),t}}}if("setter"===i){const{name:i}=s;return function(s){const r=this[i];t.call(this,s),this.requestUpdate(i,r,e,!0,s)}}throw Error("Unsupported decorator location: "+i)};
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/function Dd(e){return(t,s)=>"object"==typeof s?Od(e,t,s):((e,t,s)=>{const i=t.hasOwnProperty(s);return t.constructor.createProperty(s,e),i?Object.getOwnPropertyDescriptor(t,s):void 0})(e,t,s)}
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/function wd(e){return Dd({...e,state:!0,attribute:!1})}
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
function Ld(e,t){return(t,s,i)=>((e,t,s)=>(s.configurable=!0,s.enumerable=!0,Reflect.decorate&&"object"!=typeof t&&Object.defineProperty(e,t,s),s))(t,s,{get(){return(t=>t.renderRoot?.querySelector(e)??null)(this)}})}
/**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/const Fd=2;
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/class Nd{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,s){this._$Ct=e,this._$AM=t,this._$Ci=s}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/const Bd=(e,t)=>{const s=e._$AN;if(void 0===s)return!1;for(const e of s)e._$AO?.(t,!1),Bd(e,t);return!0},Ud=e=>{let t,s;do{if(void 0===(t=e._$AM))break;s=t._$AN,s.delete(e),e=t}while(0===s?.size)},kd=e=>{for(let t;t=e._$AM;e=t){let s=t._$AN;if(void 0===s)t._$AN=s=new Set;else if(s.has(e))break;s.add(e),Hd(t)}};function Gd(e){void 0!==this._$AN?(Ud(this),this._$AM=e,kd(this)):this._$AM=e}function Vd(e,t=!1,s=0){const i=this._$AH,r=this._$AN;if(void 0!==r&&0!==r.size)if(t)if(Array.isArray(i))for(let e=s;e<i.length;e++)Bd(i[e],!1),Ud(i[e]);else null!=i&&(Bd(i,!1),Ud(i));else Bd(this,e)}const Hd=e=>{e.type==Fd&&(e._$AP??=Vd,e._$AQ??=Gd)};class zd extends Nd{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,s){super._$AT(e,t,s),kd(this),this.isConnected=e._$AU}_$AO(e,t=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),t&&(Bd(this,e),Ud(this))}setValue(e){if((e=>void 0===e.strings)(this._$Ct))this._$Ct._$AI(e,this);else{const t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}}const Wd=new WeakMap,Xd=(e=>(...t)=>({_$litDirective$:e,values:t}))(class extends zd{render(e){return ud}update(e,[t]){const s=t!==this.G;return s&&void 0!==this.G&&this.rt(void 0),(s||this.lt!==this.ct)&&(this.G=t,this.ht=e.options?.host,this.rt(this.ct=e.element)),ud}rt(e){if(this.isConnected||(e=void 0),"function"==typeof this.G){const t=this.ht??globalThis;let s=Wd.get(t);void 0===s&&(s=new WeakMap,Wd.set(t,s)),void 0!==s.get(this.G)&&this.G.call(this.ht,void 0),s.set(this.G,e),void 0!==e&&this.G.call(this.ht,e)}else this.G.value=e}get lt(){return"function"==typeof this.G?Wd.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}}),Kd=[.5,1,1.5,2];function Yd(e){if(!e)return null;const t=document.createElement("canvas");t.width=t.height=1;const s=t.getContext("2d");if(!s)throw new Error("Unable to get 2d context for parseColor");s.clearRect(0,0,1,1),s.fillStyle=e,s.fillRect(0,0,1,1);const i=s.getImageData(0,0,1,1).data;return{r:i[0]/255,g:i[1]/255,b:i[2]/255,a:i[3]/255}}function jd(e){return null==e?null:Number(e)}function qd(e){if(!e)return null;const t=e.trim().split(/\s+/);if(3!==t.length)throw new Error(`Camera orbit and target should be defined as three space separated numbers, but was specified as "${e}".`);return t.map(e=>Number(e))}function $d(e){return e&&function(e){return _.includes(e)}(e)?e:null}function Zd(e){return e&&"auto"!==e?"reframe"===e?"reframe":e.trim().split(/\s+/):"auto"}let Qd=(()=>{var e,t,s,r,o,h,l,c,u,d,_,p,g,m,T,E,R,y,S,v,I,P,C,O,D,w,L,F,N,B,U,k,G,V;let H,z,W,X,K,Y,j,q,$,Z,Q,J,ee,te,se,ie,re,ne,ae,oe,he,le,ce,ue,de,_e,pe,fe,ge,me,Te,Ee,Re,be,Ae=vd,ye=[],Me=[],xe=[],Se=[],ve=[],Ie=[],Pe=[],Ce=[],Oe=[],De=[],we=[],Le=[],Fe=[],Ne=[],Be=[],Ue=[],ke=[],Ge=[],Ve=[],He=[],ze=[],We=[],Xe=[],Ke=[],Ye=[],je=[],qe=[],$e=[],Ze=[],Qe=[],Je=[],et=[],tt=[],st=[],it=[],rt=[],nt=[],at=[],ot=[],ht=[],lt=[],ct=[],ut=[],dt=[],_t=[],pt=[],ft=[],gt=[],mt=[],Tt=[],Et=[],Rt=[],bt=[],At=[],yt=[],Mt=[],xt=[],St=[],vt=[],It=[],Pt=[],Ct=[],Ot=[],Dt=[],wt=[],Lt=[],Ft=[];return e=class extends Ae{constructor(e={}){super(),this._options=(A(this,ye),e),this._viewerLock=new n,this._animationSliderResizeObserver=null,this._propertyBindings=[this._createPropertyBinding("clearColor",e=>e.onClearColorChanged,e=>e.clearColor=this.clearColor??{r:0,g:0,b:0,a:0},e=>this.clearColor=e.clearColor),this._createPropertyBinding("skyboxBlur",e=>e.onEnvironmentConfigurationChanged,e=>e.environmentConfig={blur:this.skyboxBlur??e.environmentConfig.blur},e=>this.skyboxBlur=e.environmentConfig.blur),this._createPropertyBinding("environmentIntensity",e=>e.onEnvironmentConfigurationChanged,e=>e.environmentConfig={intensity:this.environmentIntensity??e.environmentConfig.intensity},e=>this.environmentIntensity=e.environmentConfig.intensity),this._createPropertyBinding("environmentRotation",e=>e.onEnvironmentConfigurationChanged,e=>e.environmentConfig={rotation:this.environmentRotation??e.environmentConfig.rotation},e=>this.environmentRotation=e.environmentConfig.rotation),this._createPropertyBinding("toneMapping",e=>e.onPostProcessingChanged,e=>{this.toneMapping&&(e.postProcessing={toneMapping:this.toneMapping})},e=>this.toneMapping=e.postProcessing?.toneMapping),this._createPropertyBinding("contrast",e=>e.onPostProcessingChanged,e=>e.postProcessing={contrast:this.contrast??void 0},e=>this.contrast=e.postProcessing.contrast),this._createPropertyBinding("exposure",e=>e.onPostProcessingChanged,e=>e.postProcessing={exposure:this.exposure??void 0},e=>this.exposure=e.postProcessing.exposure),this._createPropertyBinding("ssao",e=>e.onPostProcessingChanged,e=>e.postProcessing={ssao:this.ssao??void 0},e=>this.ssao=e.postProcessing.ssao),this._createPropertyBinding("cameraAutoOrbit",e=>e.onCameraAutoOrbitChanged,e=>e.cameraAutoOrbit={enabled:this.cameraAutoOrbit},e=>this.cameraAutoOrbit=e.cameraAutoOrbit.enabled),this._createPropertyBinding("cameraAutoOrbitSpeed",e=>e.onCameraAutoOrbitChanged,e=>e.cameraAutoOrbit={speed:this.cameraAutoOrbitSpeed??void 0},e=>this.cameraAutoOrbitSpeed=e.cameraAutoOrbit.speed),this._createPropertyBinding("cameraAutoOrbitDelay",e=>e.onCameraAutoOrbitChanged,e=>e.cameraAutoOrbit={delay:this.cameraAutoOrbitDelay??void 0},e=>this.cameraAutoOrbitDelay=e.cameraAutoOrbit.delay),this._createPropertyBinding("animationSpeed",e=>e.onAnimationSpeedChanged,e=>e.animationSpeed=this.animationSpeed,e=>{let t=e.animationSpeed;t=Kd.reduce((e,s)=>Math.abs(s-t)<Math.abs(e-t)?s:e),this.animationSpeed=t,this._dispatchCustomEvent("animationspeedchange",e=>new Event(e))}),this._createPropertyBinding("selectedAnimation",e=>e.onSelectedAnimationChanged,e=>e.selectedAnimation=this.selectedAnimation??e.selectedAnimation,e=>this.selectedAnimation=e.selectedAnimation),this._createPropertyBinding("selectedMaterialVariant",e=>e.onSelectedMaterialVariantChanged,e=>e.selectedMaterialVariant=this.selectedMaterialVariant??e.selectedMaterialVariant??"",e=>this.selectedMaterialVariant=e.selectedMaterialVariant),this._createPropertyBinding("hotSpots",e=>e.onHotSpotsChanged,e=>e.hotSpots=this.hotSpots??e.hotSpots,e=>this.hotSpots=e.hotSpots),this._createPropertyBinding("camerasAsHotSpots",e=>e.onCamerasAsHotSpotsChanged,e=>e.camerasAsHotSpots=this.camerasAsHotSpots??e.camerasAsHotSpots,e=>this.camerasAsHotSpots=e.camerasAsHotSpots)],t.set(this,A(this,Me,!1)),s.set(this,(A(this,xe),A(this,Se,!1===this._options.autoSuspendRendering))),r.set(this,(A(this,ve),A(this,Ie,this._options.source??null))),o.set(this,(A(this,Pe),A(this,Ce,null))),h.set(this,(A(this,Oe),A(this,De,this._options.useOpenPBR??!1))),l.set(this,(A(this,we),A(this,Le,this._options.environmentLighting??null))),c.set(this,(A(this,Fe),A(this,Ne,this._options.environmentSkybox??null))),u.set(this,(A(this,Be),A(this,Ue,this._options.environmentConfig?.intensity??null))),d.set(this,(A(this,ke),A(this,Ge,this._options.environmentConfig?.rotation??null))),_.set(this,(A(this,Ve),A(this,He,null))),p.set(this,(A(this,ze),A(this,We,!1))),g.set(this,(A(this,Xe),A(this,Ke,this._options.environmentConfig?.blur??null))),m.set(this,(A(this,Ye),A(this,je,this._options.postProcessing?.toneMapping??null))),T.set(this,(A(this,qe),A(this,$e,this._options.postProcessing?.contrast??null))),E.set(this,(A(this,Ze),A(this,Qe,this._options.postProcessing?.exposure??null))),R.set(this,(A(this,Je),A(this,et,this._options.postProcessing?.ssao??null))),y.set(this,(A(this,tt),A(this,st,this._options.clearColor?{r:this._options.clearColor[0],g:this._options.clearColor[1],b:this._options.clearColor[2],a:this._options.clearColor[3]??1}:null))),S.set(this,(A(this,it),A(this,rt,this._options.cameraAutoOrbit?.enabled??!1))),v.set(this,(A(this,nt),A(this,at,this._options.cameraAutoOrbit?.speed??null))),I.set(this,(A(this,ot),A(this,ht,this._options.cameraAutoOrbit?.delay??null))),P.set(this,(A(this,lt),A(this,ct,this._options.hotSpots??{}))),C.set(this,(A(this,ut),A(this,dt,!!this._options.animationAutoPlay))),O.set(this,(A(this,_t),A(this,pt,this._options.selectedAnimation??null))),D.set(this,(A(this,ft),A(this,gt,this._options.animationSpeed??1))),w.set(this,(A(this,mt),A(this,Tt,0))),L.set(this,(A(this,Et),A(this,Rt,[]))),F.set(this,(A(this,bt),A(this,At,!1))),N.set(this,(A(this,yt),A(this,Mt,!0))),B.set(this,(A(this,xt),A(this,St,this._options.selectedMaterialVariant??null))),U.set(this,(A(this,vt),A(this,It,!1))),k.set(this,(A(this,Pt),A(this,Ct,"auto"))),G.set(this,(A(this,Ot),A(this,Dt,void 0))),V.set(this,(A(this,wt),A(this,Lt,void 0))),A(this,Ft),this._options=e}static get observedAttributes(){return[...super.observedAttributes,"camera-orbit","camera-target"]}queryHotSpot(e,t){return!!this._viewer&&this._viewer.queryHotSpot(e,t)}focusHotSpot(e){return!!this._viewer&&this._viewer.focusHotSpot(e)}get _isFaultedBacking(){return M(this,t,"f")}set _isFaultedBacking(e){x(this,t,e,"f")}get _isFaulted(){return this._isFaultedBacking}get renderWhenIdle(){return M(this,s,"f")}set renderWhenIdle(e){x(this,s,e,"f")}get source(){return M(this,r,"f")}set source(e){x(this,r,e,"f")}get extension(){return M(this,o,"f")}set extension(e){x(this,o,e,"f")}get useOpenPBR(){return M(this,h,"f")}set useOpenPBR(e){x(this,h,e,"f")}get environment(){return{lighting:this.environmentLighting,skybox:this.environmentSkybox}}set environment(e){this.environmentLighting=e||null,this.environmentSkybox=e||null}get environmentLighting(){return M(this,l,"f")}set environmentLighting(e){x(this,l,e,"f")}get environmentSkybox(){return M(this,c,"f")}set environmentSkybox(e){x(this,c,e,"f")}get environmentIntensity(){return M(this,u,"f")}set environmentIntensity(e){x(this,u,e,"f")}get environmentRotation(){return M(this,d,"f")}set environmentRotation(e){x(this,d,e,"f")}get shadowQuality(){return M(this,_,"f")}set shadowQuality(e){x(this,_,e,"f")}get _loadingProgress(){return M(this,p,"f")}set _loadingProgress(e){x(this,p,e,"f")}get loadingProgress(){return this._loadingProgress}get skyboxBlur(){return M(this,g,"f")}set skyboxBlur(e){x(this,g,e,"f")}get toneMapping(){return M(this,m,"f")}set toneMapping(e){x(this,m,e,"f")}get contrast(){return M(this,T,"f")}set contrast(e){x(this,T,e,"f")}get exposure(){return M(this,E,"f")}set exposure(e){x(this,E,e,"f")}get ssao(){return M(this,R,"f")}set ssao(e){x(this,R,e,"f")}get clearColor(){return M(this,y,"f")}set clearColor(e){x(this,y,e,"f")}get cameraAutoOrbit(){return M(this,S,"f")}set cameraAutoOrbit(e){x(this,S,e,"f")}get cameraAutoOrbitSpeed(){return M(this,v,"f")}set cameraAutoOrbitSpeed(e){x(this,v,e,"f")}get cameraAutoOrbitDelay(){return M(this,I,"f")}set cameraAutoOrbitDelay(e){x(this,I,e,"f")}get hotSpots(){return M(this,P,"f")}set hotSpots(e){x(this,P,e,"f")}get _hasHotSpots(){return Object.keys(this.hotSpots).length>0}get animationAutoPlay(){return M(this,C,"f")}set animationAutoPlay(e){x(this,C,e,"f")}get animations(){return this._animations}get _hasAnimations(){return this._animations.length>0}get selectedAnimation(){return M(this,O,"f")}set selectedAnimation(e){x(this,O,e,"f")}get isAnimationPlaying(){return this._isAnimationPlaying}get animationSpeed(){return M(this,D,"f")}set animationSpeed(e){x(this,D,e,"f")}get animationProgress(){return M(this,w,"f")}set animationProgress(e){x(this,w,e,"f")}get _animations(){return M(this,L,"f")}set _animations(e){x(this,L,e,"f")}get _isAnimationPlaying(){return M(this,F,"f")}set _isAnimationPlaying(e){x(this,F,e,"f")}get _showAnimationSlider(){return M(this,N,"f")}set _showAnimationSlider(e){x(this,N,e,"f")}get materialVariants(){return this._viewer?.materialVariants??[]}get selectedMaterialVariant(){return M(this,B,"f")}set selectedMaterialVariant(e){x(this,B,e,"f")}get camerasAsHotSpots(){return M(this,U,"f")}set camerasAsHotSpots(e){x(this,U,e,"f")}get resetMode(){return M(this,k,"f")}set resetMode(e){x(this,k,e,"f")}get _canvasContainer(){return M(this,G,"f")}set _canvasContainer(e){x(this,G,e,"f")}get _hotSpotSelect(){return M(this,V,"f")}set _hotSpotSelect(e){x(this,V,e,"f")}toggleAnimation(){this._viewer?.toggleAnimation()}reset(){this._reset(this.resetMode)}_reset(e){switch(e){case"auto":this._viewer?.resetCamera(void 0);break;case"reframe":this._viewer?.resetCamera(!0);break;default:this._viewer?.reset(...e)}}resetCamera(){this._reset("reframe")}reload(){this._tearDownViewer(),this._setupViewer()}connectedCallback(){super.connectedCallback(),this._setupViewer()}disconnectedCallback(){super.disconnectedCallback(),this._tearDownViewer()}attributeChangedCallback(e,t,s){if(super.attributeChangedCallback(e,t,s),this.hasUpdated)if("camera-orbit"==e){const e=qd(s);e?this._viewer?.updateCamera({alpha:e[0],beta:e[1],radius:e[2]}):this._viewer?.resetCamera(!1)}else if("camera-target"==e){const e=qd(s);e?this._viewer?.updateCamera({targetX:e[0],targetY:e[1],targetZ:e[2]}):this._viewer?.resetCamera(!1)}}update(e){super.update(e),this._hotSpotSelect&&(this._hotSpotSelect.value=""),this._needsReload(e)?(this._tearDownViewer(),this._setupViewer()):(this._propertyBindings.filter(t=>e.has(t.property)).forEach(e=>e.updateViewer()),(e.has("source")||e.has("useOpenPBR"))&&this._updateModel(),(e.has("environmentLighting")||e.has("environmentSkybox"))&&this._updateEnv({lighting:e.has("environmentLighting"),skybox:e.has("environmentSkybox")}),e.has("shadowQuality")&&this._updateShadows(this.shadowQuality))}_needsReload(e){return null!=e.get("renderWhenIdle")}render(){return ld`<div class="full-size"><div id="canvasContainer" class="full-size"></div>${this._renderOverlay()}</div>`}_renderProgressBar(){const e=!1!==this.loadingProgress,t="boolean"==typeof this.loadingProgress?0:100*this.loadingProgress,s=!0===this.loadingProgress;return ld`<div part="progress-bar" class="bar loading-progress-outer ${e?"":"loading-progress-outer-inactive"}" aria-label="Loading Progress"><div class="loading-progress-inner ${s?"loading-progress-inner-indeterminate":""}" style="${s?"":`width: ${t}%`}"></div></div>`}_renderToolbar(){let e=[];if(this._viewer?.isModelLoaded){this._hasAnimations&&e.push(ld`<div class="animation-timeline"><button aria-label="${this.isAnimationPlaying?"Pause":"Play"}" @click="${this.toggleAnimation}">${this.isAnimationPlaying?ld`<svg viewBox="0 0 24 24"><path d="${"M5.74609 3C4.7796 3 3.99609 3.7835 3.99609 4.75V19.25C3.99609 20.2165 4.7796 21 5.74609 21H9.24609C10.2126 21 10.9961 20.2165 10.9961 19.25V4.75C10.9961 3.7835 10.2126 3 9.24609 3H5.74609ZM14.7461 3C13.7796 3 12.9961 3.7835 12.9961 4.75V19.25C12.9961 20.2165 13.7796 21 14.7461 21H18.2461C19.2126 21 19.9961 20.2165 19.9961 19.25V4.75C19.9961 3.7835 19.2126 3 18.2461 3H14.7461Z"}" fill="currentColor"></path></svg>`:ld`<svg viewBox="0 0 24 24"><path d="${"M5 5.27368C5 3.56682 6.82609 2.48151 8.32538 3.2973L20.687 10.0235C22.2531 10.8756 22.2531 13.124 20.687 13.9762L8.32538 20.7024C6.82609 21.5181 5 20.4328 5 18.726V5.27368Z"}" fill="currentColor"></path></svg>`}</button> <input ${Xd(this._onAnimationSliderChanged)} aria-label="Animation Progress" class="animation-timeline-input" style="${this._showAnimationSlider?"":"visibility: hidden"}" type="range" min="0" max="1" step="0.0001" .value="${this.animationProgress}" @input="${this._onAnimationTimelineChanged}" @pointerdown="${this._onAnimationTimelinePointerDown}"></div><select aria-label="Select Animation Speed" @change="${this._onAnimationSpeedChanged}">${Kd.map(e=>ld`<option value="${e}" .selected="${this.animationSpeed===e}">${e}x</option>`)}</select> ${this.animations.length>1?ld`<select aria-label="Select Animation" @change="${this._onSelectedAnimationChanged}">${this.animations.map((e,t)=>ld`<option value="${t}" .selected="${this.selectedAnimation===t}">${e}</option>`)}</select>`:""}`),this.materialVariants.length>1&&e.push(ld`<select aria-label="Select Material Variant" @change="${this._onMaterialVariantChanged}">${this.materialVariants.map(e=>ld`<option value="${e}" .selected="${this.selectedMaterialVariant===e}">${e}</option>`)}</select>`),e.push(ld`<button aria-label="Reset Camera Pose" @click="${this.reset}"><svg viewBox="0 0 24 24"><path d="${"M7.20711 2.54289C7.59763 2.93342 7.59763 3.56658 7.20711 3.95711L5.41421 5.75H13.25C17.6683 5.75 21.25 9.33172 21.25 13.75C21.25 18.1683 17.6683 21.75 13.25 21.75C8.83172 21.75 5.25 18.1683 5.25 13.75C5.25 13.1977 5.69772 12.75 6.25 12.75C6.80228 12.75 7.25 13.1977 7.25 13.75C7.25 17.0637 9.93629 19.75 13.25 19.75C16.5637 19.75 19.25 17.0637 19.25 13.75C19.25 10.4363 16.5637 7.75 13.25 7.75H5.41421L7.20711 9.54289C7.59763 9.93342 7.59763 10.5666 7.20711 10.9571C6.81658 11.3476 6.18342 11.3476 5.79289 10.9571L2.29289 7.45711C1.90237 7.06658 1.90237 6.43342 2.29289 6.04289L5.79289 2.54289C6.18342 2.15237 6.81658 2.15237 7.20711 2.54289Z"}" fill="currentColor"></path></svg></button>`),this._hasHotSpots&&e.push(ld`<div class="select-container"><select id="hotSpotSelect" aria-label="Select HotSpot" @change="${this._onHotSpotsChanged}">${Object.keys(this.hotSpots).map(e=>ld`<option value="${e}">${e} </option>`)}</select> <button style="pointer-events:none"><svg viewBox="0 0 24 24"><path d="${"M12 14C13.1046 14 14 13.1046 14 12C14 10.8954 13.1046 10 12 10C10.8954 10 10 10.8954 10 12C10 13.1046 10.8954 14 12 14ZM6 12C6 8.68629 8.68629 6 12 6C15.3137 6 18 8.68629 18 12C18 15.3137 15.3137 18 12 18C8.68629 18 6 15.3137 6 12ZM12 8C9.79086 8 8 9.79086 8 12C8 14.2091 9.79086 16 12 16C14.2091 16 16 14.2091 16 12C16 9.79086 14.2091 8 12 8ZM2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12ZM12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4Z"}" fill="currentColor"></path></svg></button></div>`);const t=e.length,s=ld`<div class="divider"></div>`;e=e.reduce((e,i,r)=>r<t-1?[...e,i,s]:[...e,i],new Array)}return e.length>0?ld`<div part="tool-bar" class="bar ${this._hasAnimations?"":"bar-min"} tool-bar">${e}</div>`:ld``}_renderReloadButton(){return ld`${this._isFaulted?ld`<button aria-label="Reload" part="reload-button" class="reload-button" @click="${this.reload}"><svg viewBox="0 0 24 24"><path d="${"M5 12C5 8.13401 8.13401 5 12 5C13.32 5 14.5542 5.36484 15.608 6H15C14.4477 6 14 6.44772 14 7C14 7.55228 14.4477 8 15 8H18C18.5523 8 19 7.55228 19 7C19 6 19 5 19 4C19 3.44772 18.5523 3 18 3C17.4477 3 17 3.44772 17 4V4.51575C15.5702 3.5588 13.85 3 12 3C7.02944 3 3 7.02944 3 12C3 16.9706 7.02944 21 12 21C16.9706 21 21 16.9706 21 12C21 11.6199 20.9764 11.2448 20.9304 10.8763C20.8621 10.3282 20.3624 9.93935 19.8144 10.0077C19.2663 10.076 18.8775 10.5757 18.9458 11.1237C18.9815 11.4104 19 11.7028 19 12C19 15.866 15.866 19 12 19C8.13401 19 5 15.866 5 12Z"}" fill="currentColor"></path></svg></button>`:""}`}_renderOverlay(){return ld`<slot class="full-size children-slot"></slot><slot name="progress-bar">${this._renderProgressBar()}</slot><slot name="tool-bar">${this._renderToolbar()}</slot><slot name="reload-button">${this._renderReloadButton()}</slot>`}_dispatchCustomEvent(e,t){this.dispatchEvent(t(e))}_onSelectedAnimationChanged(e){const t=e.target;this.selectedAnimation=Number(t.value)}_onAnimationSpeedChanged(e){const t=e.target;this.animationSpeed=Number(t.value)}_onAnimationTimelineChanged(e){if(this._viewer){const t=e.target,s=Number(t.value);s!==this.animationProgress&&(this._viewer.animationProgress=s)}}_onAnimationTimelinePointerDown(e){if(this._viewer?.isAnimationPlaying){this._viewer.pauseAnimation();e.target.addEventListener("pointerup",()=>this._viewer?.playAnimation(),{once:!0})}}_onMaterialVariantChanged(e){const t=e.target;this.selectedMaterialVariant=t.value}_onHotSpotsChanged(e){const t=e.target,s=t.value;t.value="",this.focusHotSpot(s)}_onAnimationSliderChanged(e){this._animationSliderResizeObserver?.disconnect(),e&&(this._animationSliderResizeObserver=new ResizeObserver(()=>{this._showAnimationSlider=e.clientWidth>=80}),this._animationSliderResizeObserver.observe(e))}_createPropertyBinding(e,t,s,i){const r=e=>{try{s(e)}catch(e){a.Error(e)}};return{property:e,onInitialized:e=>{t(e).add(()=>{i(e)}),r(e)},updateViewer:()=>{this._viewer&&r(this._viewer)}}}async _setupViewer(){await this._viewerLock.lockAsync(async()=>{if(this._canvasContainer||await this.updateComplete,this._canvasContainer&&!this._viewer){const e=document.createElement("canvas");e.className="full-size canvas",e.setAttribute("touch-action","none"),this._canvasContainer.appendChild(e);const t=this,s=new Proxy(this._options,{get(e,s){switch(s){case"autoSuspendRendering":return!(t.hasAttribute("render-when-idle")||!1===e.autoSuspendRendering);case"source":return t.getAttribute("source")??e.source;case"pluginExtension":return t.extension??e.pluginExtension;case"useOpenPBR":return!!t.hasAttribute("use-open-pbr")||(t.useOpenPBR??e.useOpenPBR);case"environmentLighting":return t.getAttribute("environment-lighting")??t.getAttribute("environment")??e.environmentLighting;case"environmentSkybox":return t.getAttribute("environment-skybox")??t.getAttribute("environment")??e.environmentSkybox;case"environmentConfig":return{intensity:jd(t.getAttribute("environment-intensity"))??e.environmentConfig?.intensity,blur:jd(t.getAttribute("skybox-blur"))??e.environmentConfig?.blur,rotation:jd(t.getAttribute("environment-rotation"))??e.environmentConfig?.rotation};case"shadowConfig":return{quality:$d(t.getAttribute("shadow-quality"))??e.shadowConfig?.quality};case"cameraOrbit":return qd(t.getAttribute("camera-orbit"))??e.cameraOrbit;case"cameraTarget":return qd(t.getAttribute("camera-target"))??e.cameraTarget;case"cameraAutoOrbit":return{enabled:t.hasAttribute("camera-auto-orbit")||e.cameraAutoOrbit?.enabled,speed:jd(t.getAttribute("camera-auto-orbit-speed"))??e.cameraAutoOrbit?.speed,delay:jd(t.getAttribute("camera-auto-orbit-delay"))??e.cameraAutoOrbit?.delay};case"animationAutoPlay":return t.hasAttribute("animation-auto-play")||e.animationAutoPlay;case"animationSpeed":return jd(t.getAttribute("animation-speed"))??e.animationSpeed;case"selectedAnimation":return jd(t.getAttribute("selected-animation"))??e.selectedAnimation;case"postProcessing":return{toneMapping:(i=t.getAttribute("tone-mapping"),(i&&f(i)?i:null)??e.postProcessing?.toneMapping),contrast:jd(t.getAttribute("contrast"))??e.postProcessing?.contrast,exposure:jd(t.getAttribute("exposure"))??e.postProcessing?.exposure,ssao:t.hasAttribute("ssao")||e.postProcessing?.ssao};case"selectedMaterialVariant":return t.getAttribute("material-variant")??e.selectedMaterialVariant;case"onFaulted":return s=>{t._isFaultedBacking=!0,e.onFaulted?.(s),t._tearDownViewer()};default:return e[s]}var i}}),i=await this._createViewer(e,s);this._viewer=i,i.onEnvironmentChanged.add(()=>{this._dispatchCustomEvent("environmentchange",e=>new Event(e))}),i.onEnvironmentConfigurationChanged.add(()=>{this._dispatchCustomEvent("environmentconfigurationchange",e=>new Event(e))}),i.onEnvironmentError.add(e=>{this._dispatchCustomEvent("environmenterror",t=>new ErrorEvent(t,{error:e}))}),i.onShadowsConfigurationChanged.add(()=>{this._dispatchCustomEvent("shadowsconfigurationchange",e=>new Event(e))}),i.onModelChanged.add(e=>{this._animations=[...i.animations],this._dispatchCustomEvent("modelchange",t=>new CustomEvent(t,{detail:e}))}),i.onModelError.add(e=>{this._animations=[...i.animations],this._dispatchCustomEvent("modelerror",t=>new ErrorEvent(t,{error:e}))}),i.onLoadingProgressChanged.add(()=>{this._loadingProgress=i.loadingProgress,this._dispatchCustomEvent("loadingprogresschange",e=>new Event(e))}),i.onSelectedAnimationChanged.add(()=>{this._dispatchCustomEvent("selectedanimationchange",e=>new Event(e))}),i.onIsAnimationPlayingChanged.add(()=>{this._isAnimationPlaying=i.isAnimationPlaying??!1,this._dispatchCustomEvent("animationplayingchange",e=>new Event(e))}),i.onAnimationProgressChanged.add(()=>{this.animationProgress=i.animationProgress??0,this._dispatchCustomEvent("animationprogresschange",e=>new Event(e))}),i.onSelectedMaterialVariantChanged.add(()=>{this._dispatchCustomEvent("selectedmaterialvariantchange",e=>new Event(e))}),i.onAfterRenderObservable.add(()=>{this._dispatchCustomEvent("viewerrender",e=>new Event(e))}),this._propertyBindings.forEach(e=>e.onInitialized(i)),this._dispatchCustomEvent("viewerready",e=>new Event(e))}this._isFaultedBacking=!1})}async _tearDownViewer(){await this._viewerLock.lockAsync(async()=>{this._viewer&&(this._viewer.dispose(),this._viewer=void 0),this._onViewerTornDown(),this._loadingProgress=!1,this._canvasContainer&&this._canvasContainer.firstElementChild&&this._canvasContainer.removeChild(this._canvasContainer.firstElementChild)})}_onViewerTornDown(){}async _updateModel(){if(this._viewer)try{this.source?await this._viewer.loadModel(this.source,{pluginExtension:this.extension??void 0,useOpenPBR:this.useOpenPBR}):await this._viewer.resetModel()}catch(e){e instanceof i||a.Error(e)}}async _updateEnv(e){if(this._viewer)try{const t=[];e.lighting&&e.skybox&&this.environmentLighting===this.environmentSkybox?t.push([this.environmentLighting,{lighting:!0,skybox:!0}]):(e.lighting&&t.push([this.environmentLighting,{lighting:!0}]),e.skybox&&t.push([this.environmentSkybox,{skybox:!0}]));const s=t.map(async([e,t])=>{e?await(this._viewer?.loadEnvironment(e,t)):await(this._viewer?.resetEnvironment(t))});await Promise.all(s)}catch(e){e instanceof i||a.Error(e)}}async _updateShadows(e){if(e)try{const t={quality:e};await(this._viewer?.updateShadows(t))}catch(e){e instanceof i||a.Error(e)}}},t=new WeakMap,s=new WeakMap,r=new WeakMap,o=new WeakMap,h=new WeakMap,l=new WeakMap,c=new WeakMap,u=new WeakMap,d=new WeakMap,_=new WeakMap,p=new WeakMap,g=new WeakMap,m=new WeakMap,T=new WeakMap,E=new WeakMap,R=new WeakMap,y=new WeakMap,S=new WeakMap,v=new WeakMap,I=new WeakMap,P=new WeakMap,C=new WeakMap,O=new WeakMap,D=new WeakMap,w=new WeakMap,L=new WeakMap,F=new WeakMap,N=new WeakMap,B=new WeakMap,U=new WeakMap,k=new WeakMap,G=new WeakMap,V=new WeakMap,(()=>{const t="function"==typeof Symbol&&Symbol.metadata?Object.create(Ae[Symbol.metadata]??null):void 0;H=[wd()],z=[Dd({attribute:"render-when-idle",type:Boolean})],W=[Dd()],X=[Dd()],K=[Dd({attribute:"use-open-pbr",type:Boolean})],Y=[Dd({hasChanged:(e,t)=>{const s=e||null;return s!==t.lighting||s!==t.skybox}})],j=[Dd({attribute:"environment-lighting"})],q=[Dd({attribute:"environment-skybox"})],$=[Dd({type:Number,attribute:"environment-intensity"})],Z=[Dd({type:Number,attribute:"environment-rotation"})],Q=[Dd({attribute:"shadow-quality"})],J=[wd()],ee=[Dd({attribute:"skybox-blur"})],te=[Dd({attribute:"tone-mapping",converter:e=>e&&f(e)?e:"neutral"})],se=[Dd()],ie=[Dd()],re=[Dd({type:String})],ne=[Dd({attribute:"clear-color",converter:{fromAttribute:Yd,toAttribute:e=>e?function(e){const t=e=>Math.round(255*e).toString(16).padStart(2,"0");return`#${t(e.r)}${t(e.g)}${t(e.b)}${t(e.a)}`}(e):null}})],ae=[Dd({attribute:"camera-auto-orbit",type:Boolean})],oe=[Dd({attribute:"camera-auto-orbit-speed",type:Number})],he=[Dd({attribute:"camera-auto-orbit-delay",type:Number})],le=[Dd({attribute:"hotspots",converter:e=>e?JSON.parse(e):{}})],ce=[Dd({attribute:"animation-auto-play",type:Boolean})],ue=[Dd({attribute:"selected-animation",type:Number})],de=[Dd({attribute:"animation-speed"})],_e=[Dd({attribute:!1})],pe=[wd()],fe=[wd()],ge=[wd()],me=[Dd({attribute:"material-variant"})],Te=[Dd({attribute:"cameras-as-hotspots",type:Boolean})],Ee=[Dd({attribute:"reset-mode",converter:Zd})],Re=[Ld("#canvasContainer")],be=[Ld("#hotSpotSelect")],b(e,null,H,{kind:"accessor",name:"_isFaultedBacking",static:!1,private:!1,access:{has:e=>"_isFaultedBacking"in e,get:e=>e._isFaultedBacking,set:(e,t)=>{e._isFaultedBacking=t}},metadata:t},Me,xe),b(e,null,z,{kind:"accessor",name:"renderWhenIdle",static:!1,private:!1,access:{has:e=>"renderWhenIdle"in e,get:e=>e.renderWhenIdle,set:(e,t)=>{e.renderWhenIdle=t}},metadata:t},Se,ve),b(e,null,W,{kind:"accessor",name:"source",static:!1,private:!1,access:{has:e=>"source"in e,get:e=>e.source,set:(e,t)=>{e.source=t}},metadata:t},Ie,Pe),b(e,null,X,{kind:"accessor",name:"extension",static:!1,private:!1,access:{has:e=>"extension"in e,get:e=>e.extension,set:(e,t)=>{e.extension=t}},metadata:t},Ce,Oe),b(e,null,K,{kind:"accessor",name:"useOpenPBR",static:!1,private:!1,access:{has:e=>"useOpenPBR"in e,get:e=>e.useOpenPBR,set:(e,t)=>{e.useOpenPBR=t}},metadata:t},De,we),b(e,null,Y,{kind:"setter",name:"environment",static:!1,private:!1,access:{has:e=>"environment"in e,set:(e,t)=>{e.environment=t}},metadata:t},null,ye),b(e,null,j,{kind:"accessor",name:"environmentLighting",static:!1,private:!1,access:{has:e=>"environmentLighting"in e,get:e=>e.environmentLighting,set:(e,t)=>{e.environmentLighting=t}},metadata:t},Le,Fe),b(e,null,q,{kind:"accessor",name:"environmentSkybox",static:!1,private:!1,access:{has:e=>"environmentSkybox"in e,get:e=>e.environmentSkybox,set:(e,t)=>{e.environmentSkybox=t}},metadata:t},Ne,Be),b(e,null,$,{kind:"accessor",name:"environmentIntensity",static:!1,private:!1,access:{has:e=>"environmentIntensity"in e,get:e=>e.environmentIntensity,set:(e,t)=>{e.environmentIntensity=t}},metadata:t},Ue,ke),b(e,null,Z,{kind:"accessor",name:"environmentRotation",static:!1,private:!1,access:{has:e=>"environmentRotation"in e,get:e=>e.environmentRotation,set:(e,t)=>{e.environmentRotation=t}},metadata:t},Ge,Ve),b(e,null,Q,{kind:"accessor",name:"shadowQuality",static:!1,private:!1,access:{has:e=>"shadowQuality"in e,get:e=>e.shadowQuality,set:(e,t)=>{e.shadowQuality=t}},metadata:t},He,ze),b(e,null,J,{kind:"accessor",name:"_loadingProgress",static:!1,private:!1,access:{has:e=>"_loadingProgress"in e,get:e=>e._loadingProgress,set:(e,t)=>{e._loadingProgress=t}},metadata:t},We,Xe),b(e,null,ee,{kind:"accessor",name:"skyboxBlur",static:!1,private:!1,access:{has:e=>"skyboxBlur"in e,get:e=>e.skyboxBlur,set:(e,t)=>{e.skyboxBlur=t}},metadata:t},Ke,Ye),b(e,null,te,{kind:"accessor",name:"toneMapping",static:!1,private:!1,access:{has:e=>"toneMapping"in e,get:e=>e.toneMapping,set:(e,t)=>{e.toneMapping=t}},metadata:t},je,qe),b(e,null,se,{kind:"accessor",name:"contrast",static:!1,private:!1,access:{has:e=>"contrast"in e,get:e=>e.contrast,set:(e,t)=>{e.contrast=t}},metadata:t},$e,Ze),b(e,null,ie,{kind:"accessor",name:"exposure",static:!1,private:!1,access:{has:e=>"exposure"in e,get:e=>e.exposure,set:(e,t)=>{e.exposure=t}},metadata:t},Qe,Je),b(e,null,re,{kind:"accessor",name:"ssao",static:!1,private:!1,access:{has:e=>"ssao"in e,get:e=>e.ssao,set:(e,t)=>{e.ssao=t}},metadata:t},et,tt),b(e,null,ne,{kind:"accessor",name:"clearColor",static:!1,private:!1,access:{has:e=>"clearColor"in e,get:e=>e.clearColor,set:(e,t)=>{e.clearColor=t}},metadata:t},st,it),b(e,null,ae,{kind:"accessor",name:"cameraAutoOrbit",static:!1,private:!1,access:{has:e=>"cameraAutoOrbit"in e,get:e=>e.cameraAutoOrbit,set:(e,t)=>{e.cameraAutoOrbit=t}},metadata:t},rt,nt),b(e,null,oe,{kind:"accessor",name:"cameraAutoOrbitSpeed",static:!1,private:!1,access:{has:e=>"cameraAutoOrbitSpeed"in e,get:e=>e.cameraAutoOrbitSpeed,set:(e,t)=>{e.cameraAutoOrbitSpeed=t}},metadata:t},at,ot),b(e,null,he,{kind:"accessor",name:"cameraAutoOrbitDelay",static:!1,private:!1,access:{has:e=>"cameraAutoOrbitDelay"in e,get:e=>e.cameraAutoOrbitDelay,set:(e,t)=>{e.cameraAutoOrbitDelay=t}},metadata:t},ht,lt),b(e,null,le,{kind:"accessor",name:"hotSpots",static:!1,private:!1,access:{has:e=>"hotSpots"in e,get:e=>e.hotSpots,set:(e,t)=>{e.hotSpots=t}},metadata:t},ct,ut),b(e,null,ce,{kind:"accessor",name:"animationAutoPlay",static:!1,private:!1,access:{has:e=>"animationAutoPlay"in e,get:e=>e.animationAutoPlay,set:(e,t)=>{e.animationAutoPlay=t}},metadata:t},dt,_t),b(e,null,ue,{kind:"accessor",name:"selectedAnimation",static:!1,private:!1,access:{has:e=>"selectedAnimation"in e,get:e=>e.selectedAnimation,set:(e,t)=>{e.selectedAnimation=t}},metadata:t},pt,ft),b(e,null,de,{kind:"accessor",name:"animationSpeed",static:!1,private:!1,access:{has:e=>"animationSpeed"in e,get:e=>e.animationSpeed,set:(e,t)=>{e.animationSpeed=t}},metadata:t},gt,mt),b(e,null,_e,{kind:"accessor",name:"animationProgress",static:!1,private:!1,access:{has:e=>"animationProgress"in e,get:e=>e.animationProgress,set:(e,t)=>{e.animationProgress=t}},metadata:t},Tt,Et),b(e,null,pe,{kind:"accessor",name:"_animations",static:!1,private:!1,access:{has:e=>"_animations"in e,get:e=>e._animations,set:(e,t)=>{e._animations=t}},metadata:t},Rt,bt),b(e,null,fe,{kind:"accessor",name:"_isAnimationPlaying",static:!1,private:!1,access:{has:e=>"_isAnimationPlaying"in e,get:e=>e._isAnimationPlaying,set:(e,t)=>{e._isAnimationPlaying=t}},metadata:t},At,yt),b(e,null,ge,{kind:"accessor",name:"_showAnimationSlider",static:!1,private:!1,access:{has:e=>"_showAnimationSlider"in e,get:e=>e._showAnimationSlider,set:(e,t)=>{e._showAnimationSlider=t}},metadata:t},Mt,xt),b(e,null,me,{kind:"accessor",name:"selectedMaterialVariant",static:!1,private:!1,access:{has:e=>"selectedMaterialVariant"in e,get:e=>e.selectedMaterialVariant,set:(e,t)=>{e.selectedMaterialVariant=t}},metadata:t},St,vt),b(e,null,Te,{kind:"accessor",name:"camerasAsHotSpots",static:!1,private:!1,access:{has:e=>"camerasAsHotSpots"in e,get:e=>e.camerasAsHotSpots,set:(e,t)=>{e.camerasAsHotSpots=t}},metadata:t},It,Pt),b(e,null,Ee,{kind:"accessor",name:"resetMode",static:!1,private:!1,access:{has:e=>"resetMode"in e,get:e=>e.resetMode,set:(e,t)=>{e.resetMode=t}},metadata:t},Ct,Ot),b(e,null,Re,{kind:"accessor",name:"_canvasContainer",static:!1,private:!1,access:{has:e=>"_canvasContainer"in e,get:e=>e._canvasContainer,set:(e,t)=>{e._canvasContainer=t}},metadata:t},Dt,wt),b(e,null,be,{kind:"accessor",name:"_hotSpotSelect",static:!1,private:!1,access:{has:e=>"_hotSpotSelect"in e,get:e=>e._hotSpotSelect,set:(e,t)=>{e._hotSpotSelect=t}},metadata:t},Lt,Ft),t&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:t})})(),e.styles=Su`:host{--ui-foreground-color:white;--ui-background-hue:233;--ui-background-saturation:8%;--ui-background-lightness:39%;--ui-background-opacity:0.75;--ui-background-color:hsla(var(--ui-background-hue), var(--ui-background-saturation), var(--ui-background-lightness), var(--ui-background-opacity));--ui-background-color-hover:hsla(
var(--ui-background-hue),
var(--ui-background-saturation),
calc(var(--ui-background-lightness) - 10%),
calc(var(--ui-background-opacity) - 0.1)
);all:inherit;overflow:hidden}.full-size{display:block;position:relative;width:100%;height:100%}.canvas{outline:0}.children-slot{position:absolute;top:0;background:0 0;pointer-events:none}.reload-button{position:absolute;top:50%;left:50%;width:25%;transform:translate(-50%,-50%);color:var(--ui-foreground-color);background-color:var(--ui-background-color);border:1px solid transparent;border-radius:24px;padding:0;cursor:pointer;outline:0}.reload-button:hover{background-color:var(--ui-background-color-hover)}.bar{position:absolute;width:calc(100% - 24px);min-width:370px;max-width:1280px;left:50%;transform:translateX(-50%);background-color:var(--ui-background-color)}.bar-min{width:unset;min-width:unset;max-width:unset}.loading-progress-outer{height:4px;border-radius:4px;border:1px solid var(--ui-background-color);outline:0;top:12px;pointer-events:none;transition:opacity .5s ease}.loading-progress-outer-inactive{opacity:0;background-color:var(--ui-foreground-color)}.loading-progress-inner{width:0;height:100%;border-radius:inherit;background-color:var(--ui-foreground-color);transition:width .3s linear}@keyframes indeterminate{0%{left:0;width:0%}23%{left:0;width:30%}77%{left:70%;width:30%}100%{left:100%;width:0%}}.loading-progress-inner-indeterminate{position:absolute;animation:indeterminate 1.5s infinite;animation-timing-function:linear}.tool-bar{display:flex;flex-direction:row;align-items:center;border-radius:12px;border-color:var(--ui-foreground-color);height:48px;bottom:12px;color:var(--ui-foreground-color);-webkit-tap-highlight-color:transparent}.tool-bar *{height:100%;min-width:48px}.tool-bar .divider{min-width:1px;margin:0 6px;height:66%;background-color:var(--ui-foreground-color)}.tool-bar select{background:0 0;min-width:52px;max-width:128px;border:1px solid transparent;border-radius:inherit;color:inherit;font-size:14px;padding:0 12px;cursor:pointer;outline:0;appearance:none;-webkit-appearance:none}.tool-bar .select-container{position:relative;display:flex;border-radius:inherit;border-width:0;padding:0}.tool-bar .select-container select{position:absolute;min-width:0;width:100%}.tool-bar .select-container button{position:absolute;border-width:0}.tool-bar select:focus,.tool-bar select:hover{background-color:var(--ui-background-color-hover)}.tool-bar select option{background-color:var(--ui-background-color);color:var(--ui-foreground-color)}.tool-bar select:focus-visible{border-color:inherit}.tool-bar button{background:0 0;border:1px solid transparent;border-radius:inherit;color:inherit;padding:0;cursor:pointer;outline:0}.tool-bar button:hover{background-color:var(--ui-background-color-hover)}.tool-bar button:focus-visible{border-color:inherit}.tool-bar button svg{width:32px;height:32px}.animation-timeline{display:flex;flex:1;position:relative;overflow:hidden;cursor:pointer;align-items:center;border-radius:inherit;border-color:inherit}.animation-timeline-input{-webkit-appearance:none;cursor:pointer;width:100%;height:100%;outline:0;border:1px solid transparent;border-radius:inherit;padding:0 12px;background-color:transparent}.animation-timeline-input:focus-visible{border-color:inherit}.animation-timeline-input::-webkit-slider-thumb{-webkit-appearance:none;width:20px;height:20px;border:2px solid;color:var(--ui-foreground-color);border-radius:50%;background:hsla(var(--ui-background-hue),var(--ui-background-saturation),var(--ui-background-lightness),1);margin-top:-10px}.animation-timeline-input::-webkit-slider-runnable-track{height:2px;-webkit-appearance:none;background-color:var(--ui-foreground-color)}.animation-timeline-input::-moz-range-progress{height:2px;background-color:var(--ui-foreground-color)}.animation-timeline-input::-moz-range-thumb{width:16px;height:16px;border:2px solid var(--ui-foreground-color);border-radius:50%;background:hsla(var(--ui-background-hue),var(--ui-background-saturation),var(--ui-background-lightness),1)}.animation-timeline-input::-moz-range-track{height:2px;background:var(--ui-foreground-color)}`,e})();function Jd(e){if("WebGL"===e||"WebGPU"===e)return e}function e_(e){const t=Yd(e);return t?new Ke(t.r,t.g,t.b,t.a):null}let t_=(()=>{var e,t,s;let i,n,a=Qd,o=[],h=[],l=[],c=[];return e=class extends a{constructor(e,i={}){super(i),this._viewerClass=e,t.set(this,A(this,o,this._options.clearColor?new Ke(this._options.clearColor[0],this._options.clearColor[1],this._options.clearColor[2],this._options.clearColor[3]??1):null)),s.set(this,(A(this,h),A(this,l,this._options.engine))),A(this,c),this._viewerClass=e}get viewerDetails(){return this._viewerDetails}get clearColor(){return M(this,t,"f")}set clearColor(e){x(this,t,e,"f")}get engine(){return M(this,s,"f")}set engine(e){x(this,s,e,"f")}_needsReload(e){if(super._needsReload(e))return!0;if(e.has("engine")){const t=e.get("engine");if(t&&this.engine!==t)return!0}return!1}async _createViewer(e,t){const s=new r,i=new Proxy(t,{get:(e,t)=>{switch(t){case"engine":return this.engine??e.engine;case"onInitialized":return t=>{e.onInitialized?.(t),s.resolve(t)};default:return e[t]}}}),n=await Ru(e,Object.assign(i,{viewerClass:this._viewerClass})),a=await s.promise;return this._viewerDetails=Object.assign(a,{viewer:n}),n}_onViewerTornDown(){this._viewerDetails=void 0}},t=new WeakMap,s=new WeakMap,(()=>{const t="function"==typeof Symbol&&Symbol.metadata?Object.create(a[Symbol.metadata]??null):void 0;i=[Dd({attribute:"clear-color",converter:{fromAttribute:e_,toAttribute:e=>e?e.toHexString():null}})],n=[Dd({converter:Jd})],b(e,null,i,{kind:"accessor",name:"clearColor",static:!1,private:!1,access:{has:e=>"clearColor"in e,get:e=>e.clearColor,set:(e,t)=>{e.clearColor=t}},metadata:t},o,h),b(e,null,n,{kind:"accessor",name:"engine",static:!1,private:!1,access:{has:e=>"engine"in e,get:e=>e.engine,set:(e,t)=>{e.engine=t}},metadata:t},l,c),t&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:t})})(),e})(),s_=(()=>{let e,t,s=[Pd("babylon-viewer")],i=[],r=t_;return t=class extends r{constructor(e){super(fu,e)}},y(t,"HTML3DElement"),(()=>{const n="function"==typeof Symbol&&Symbol.metadata?Object.create(r[Symbol.metadata]??null):void 0;b(null,e={value:t},s,{kind:"class",name:t.name,metadata:n},null,i),t=e.value,n&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:n}),A(t,i)})(),t})();function i_(e,t){customElements.define(e,class extends s_{constructor(){super(t)}})}let r_=(()=>{var e;let t,s,i,r=[Pd("babylon-viewer-annotation")],n=[],a=vd,o=[],h=[];return s=class extends a{get hotSpot(){return M(this,e,"f")}set hotSpot(t){x(this,e,t,"f")}connectedCallback(){super.connectedCallback(),this._internals.states?.add("invalid"),this._connectingAbortController?.abort(),this._connectingAbortController=new AbortController;const e=this._connectingAbortController.signal;(async()=>{if(this.parentElement?.matches(":not(:defined)")&&(await customElements.whenDefined(this.parentElement?.tagName.toLowerCase()),e.aborted))return;if(!(this.parentElement instanceof Qd))return void console.warn("The babylon-viewer-annotation element must be a child of a babylon-viewer element.");this._mutationObserver.observe(this,{childList:!0,characterData:!0}),this._sanitizeInnerHTML();const t=this.parentElement,s=new g,i=this._updateAnnotation=()=>{if(this.hotSpot)if(t.queryHotSpot(this.hotSpot,s)){const[e,t]=s.screenPosition;this.style.transform=`translate(${e}px, ${t}px)`,this._internals.states?.delete("invalid"),s.visibility<=0?this._internals.states?.add("back-facing"):this._internals.states?.delete("back-facing")}else this._internals.states?.add("invalid")};this._updateAnnotation(),t.addEventListener("viewerrender",i),this._viewerAttachment={dispose(){t.removeEventListener("viewerrender",i)}}})()}disconnectedCallback(){super.disconnectedCallback(),this._connectingAbortController?.abort(),this._connectingAbortController=null,this._viewerAttachment?.dispose(),this._viewerAttachment=null,this._internals.states?.add("invalid"),this._updateAnnotation=null}render(){return ld`<slot><div aria-label="${this.hotSpot} annotation" part="annotation" class="annotation">${this.hotSpot}</div></slot>`}update(e){super.update(e),e.has("hotSpot")&&this._updateAnnotation?.()}_sanitizeInnerHTML(){0===this.innerHTML.trim().length&&(this.innerHTML="")}constructor(){super(...arguments),this._internals=this.attachInternals(),this._mutationObserver=new MutationObserver(e=>{e.some(e=>"childList"===e.type)&&this._sanitizeInnerHTML()}),this._viewerAttachment=null,this._connectingAbortController=null,this._updateAnnotation=null,e.set(this,A(this,o,"")),A(this,h)}},e=new WeakMap,y(s,"HTML3DAnnotationElement"),(()=>{const e="function"==typeof Symbol&&Symbol.metadata?Object.create(a[Symbol.metadata]??null):void 0;i=[Dd({attribute:"hotspot"})],b(s,null,i,{kind:"accessor",name:"hotSpot",static:!1,private:!1,access:{has:e=>"hotSpot"in e,get:e=>e.hotSpot,set:(e,t)=>{e.hotSpot=t}},metadata:e},o,h),b(null,t={value:s},r,{kind:"class",name:s.name,metadata:e},null,n),s=t.value,e&&Object.defineProperty(s,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:e})})(),s.styles=Su`:host{--annotation-foreground-color:black;--annotation-background-color:white;display:inline-block;position:absolute;transition:opacity .25s}:host([hidden]){display:none}:host(:state(back-facing)){opacity:.2}:host(:state(invalid)){display:none}.annotation{transform:translate(-50%,-135%);font-size:14px;padding:0 6px;border-radius:6px;color:var(--annotation-foreground-color);background-color:var(--annotation-background-color)}.annotation::after{content:"";position:absolute;left:50%;height:60%;aspect-ratio:1;transform:translate(-50%,110%) rotate(-45deg);background-color:inherit;clip-path:polygon(0 0,100% 100%,0 100%,0 0)}`,A(s,n),s})();export{rn as $,Ti as A,q as B,dt as C,x as D,j as E,Cn as F,Ae as G,w as H,ji as I,F as J,N as K,_s as L,Ie as M,Ao as N,c as O,ur as P,Ws as Q,Al as R,qs as S,Ce as T,gn as U,xe as V,fn as W,yn as X,xn as Y,Mn as Z,zo as _,ee as a,U as a$,mn as a0,pn as a1,En as a2,An as a3,Th as a4,_n as a5,un as a6,Gi as a7,dn as a8,Zr as a9,Tl as aA,Ca as aB,Qe as aC,ve as aD,Ne as aE,ha as aF,Ta as aG,pl as aH,rt as aI,xa as aJ,Us as aK,ro as aL,no as aM,Is as aN,he as aO,vl as aP,as as aQ,ma as aR,Qt as aS,Zt as aT,bi as aU,Xn as aV,or as aW,Yo as aX,Fs as aY,Fn as aZ,Oc as a_,an as aa,vn as ab,Eo as ac,In as ad,Vr as ae,Gh as af,Pn as ag,on as ah,Vh as ai,Ye as aj,nn as ak,tn as al,zr as am,cn as an,Qo as ao,qr as ap,Jr as aq,Kr as ar,Xr as as,mh as at,Eh as au,gh as av,fh as aw,B as ax,Ue as ay,Rl as az,qh as b,zi as b$,Ir as b0,Ke as b1,vo as b2,Me as b3,rr as b4,en as b5,$r as b6,Hr as b7,Qr as b8,Lr as b9,na as bA,ra as bB,ia as bC,sa as bD,ta as bE,oa as bF,Yc as bG,Ht as bH,at as bI,lr as bJ,Zc as bK,fa as bL,pa as bM,_a as bN,da as bO,ua as bP,ca as bQ,nt as bR,ht as bS,$c as bT,qc as bU,bs as bV,s as bW,t as bX,tu as bY,hc as bZ,lc as b_,Le as ba,Yt as bb,Se as bc,rc as bd,yl as be,sn as bf,X as bg,Ar as bh,cr as bi,Ge as bj,ki as bk,tr as bl,Jc as bm,dh as bn,iu as bo,su as bp,ic as bq,Zl as br,ao as bs,Ln as bt,On as bu,r as bv,ie as bw,Ea as bx,Yn as by,aa as bz,zh as c,ol as c$,Wi as c0,ms as c1,Es as c2,hs as c3,ss as c4,Sl as c5,xl as c6,K as c7,Ih as c8,Ph as c9,Ni as cA,ws as cB,mt as cC,Ui as cD,Ci as cE,cl as cF,ts as cG,wi as cH,et as cI,Ko as cJ,dr as cK,Ft as cL,Nt as cM,Bt as cN,xi as cO,Vi as cP,ui as cQ,ci as cR,el as cS,$h as cT,_i as cU,Qh as cV,il as cW,sl as cX,rl as cY,nl as cZ,al as c_,se as ca,Dl as cb,$t as cc,Wa as cd,ka as ce,qa as cf,Ga as cg,Ua as ch,Je as ci,ll as cj,Ri as ck,gl as cl,xs as cm,Li as cn,jc as co,nr as cp,ec as cq,ac as cr,Mi as cs,Un as ct,Ll as cu,Ys as cv,js as cw,zs as cx,Gs as cy,Qc as cz,Yh as d,li as d0,Si as d1,oi as d2,Jh as d3,lt as d4,W as d5,i_ as d6,_u as d7,Ru as d8,pu as d9,r_ as da,s_ as db,fu as dc,t_ as dd,g as de,Wh as e,Xh as f,Kh as g,Yi as h,Xe as i,ne as j,Y as k,A as l,Ch as m,Xt as n,$e as o,Sh as p,b as q,k as r,L as s,H as t,be as u,vs as v,gi as w,Kc as x,a as y,M as z};
//# sourceMappingURL=index-OM-TXt9s.esm.min.js.map