@babylonjs/viewer 7.18.0-alpha → 7.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/configuration/configuration.d.ts +107 -0
- package/configuration/configuration.js +16 -0
- package/configuration/configuration.js.map +1 -0
- package/configuration/configurationCompatibility.d.ts +8 -0
- package/configuration/configurationCompatibility.js +66 -0
- package/configuration/configurationCompatibility.js.map +1 -0
- package/configuration/configurationContainer.d.ts +10 -0
- package/configuration/configurationContainer.js +10 -0
- package/configuration/configurationContainer.js.map +1 -0
- package/configuration/globals.d.ts +6 -0
- package/configuration/globals.js +18 -0
- package/configuration/globals.js.map +1 -0
- package/configuration/index.d.ts +2 -0
- package/configuration/index.js +4 -0
- package/configuration/index.js.map +1 -0
- package/configuration/interfaces/cameraConfiguration.d.ts +31 -0
- package/configuration/interfaces/cameraConfiguration.js +2 -0
- package/configuration/interfaces/cameraConfiguration.js.map +1 -0
- package/configuration/interfaces/colorGradingConfiguration.d.ts +81 -0
- package/configuration/interfaces/colorGradingConfiguration.js +2 -0
- package/configuration/interfaces/colorGradingConfiguration.js.map +1 -0
- package/configuration/interfaces/defaultRenderingPipelineConfiguration.d.ts +20 -0
- package/configuration/interfaces/defaultRenderingPipelineConfiguration.js +2 -0
- package/configuration/interfaces/defaultRenderingPipelineConfiguration.js.map +1 -0
- package/configuration/interfaces/environmentMapConfiguration.d.ts +22 -0
- package/configuration/interfaces/environmentMapConfiguration.js +2 -0
- package/configuration/interfaces/environmentMapConfiguration.js.map +1 -0
- package/configuration/interfaces/groundConfiguration.d.ts +24 -0
- package/configuration/interfaces/groundConfiguration.js +2 -0
- package/configuration/interfaces/groundConfiguration.js.map +1 -0
- package/configuration/interfaces/imageProcessingConfiguration.d.ts +45 -0
- package/configuration/interfaces/imageProcessingConfiguration.js +2 -0
- package/configuration/interfaces/imageProcessingConfiguration.js.map +1 -0
- package/configuration/interfaces/index.d.ts +15 -0
- package/configuration/interfaces/index.js +16 -0
- package/configuration/interfaces/index.js.map +1 -0
- package/configuration/interfaces/lightConfiguration.d.ts +60 -0
- package/configuration/interfaces/lightConfiguration.js +2 -0
- package/configuration/interfaces/lightConfiguration.js.map +1 -0
- package/configuration/interfaces/modelAnimationConfiguration.d.ts +26 -0
- package/configuration/interfaces/modelAnimationConfiguration.js +2 -0
- package/configuration/interfaces/modelAnimationConfiguration.js.map +1 -0
- package/configuration/interfaces/modelConfiguration.d.ts +65 -0
- package/configuration/interfaces/modelConfiguration.js +2 -0
- package/configuration/interfaces/modelConfiguration.js.map +1 -0
- package/configuration/interfaces/observersConfiguration.d.ts +5 -0
- package/configuration/interfaces/observersConfiguration.js +2 -0
- package/configuration/interfaces/observersConfiguration.js.map +1 -0
- package/configuration/interfaces/sceneConfiguration.d.ts +48 -0
- package/configuration/interfaces/sceneConfiguration.js +2 -0
- package/configuration/interfaces/sceneConfiguration.js.map +1 -0
- package/configuration/interfaces/sceneOptimizerConfiguration.d.ts +23 -0
- package/configuration/interfaces/sceneOptimizerConfiguration.js +2 -0
- package/configuration/interfaces/sceneOptimizerConfiguration.js.map +1 -0
- package/configuration/interfaces/skyboxConfiguration.d.ts +21 -0
- package/configuration/interfaces/skyboxConfiguration.js +2 -0
- package/configuration/interfaces/skyboxConfiguration.js.map +1 -0
- package/configuration/interfaces/templateConfiguration.d.ts +67 -0
- package/configuration/interfaces/templateConfiguration.js +2 -0
- package/configuration/interfaces/templateConfiguration.js.map +1 -0
- package/configuration/interfaces/vrConfiguration.d.ts +16 -0
- package/configuration/interfaces/vrConfiguration.js +2 -0
- package/configuration/interfaces/vrConfiguration.js.map +1 -0
- package/configuration/loader.d.ts +4 -0
- package/configuration/loader.js +17 -0
- package/configuration/loader.js.map +1 -0
- package/configuration/mappers.d.ts +43 -0
- package/configuration/mappers.js +192 -0
- package/configuration/mappers.js.map +1 -0
- package/configuration/renderOnlyLoader.d.ts +33 -0
- package/configuration/renderOnlyLoader.js +162 -0
- package/configuration/renderOnlyLoader.js.map +1 -0
- package/configuration/types/default.d.ts +6 -0
- package/configuration/types/default.js +121 -0
- package/configuration/types/default.js.map +1 -0
- package/configuration/types/environmentMap.d.ts +5 -0
- package/configuration/types/environmentMap.js +14 -0
- package/configuration/types/environmentMap.js.map +1 -0
- package/configuration/types/extended.d.ts +6 -0
- package/configuration/types/extended.js +317 -0
- package/configuration/types/extended.js.map +1 -0
- package/configuration/types/index.d.ts +14 -0
- package/configuration/types/index.js +51 -0
- package/configuration/types/index.js.map +1 -0
- package/configuration/types/minimal.d.ts +6 -0
- package/configuration/types/minimal.js +43 -0
- package/configuration/types/minimal.js.map +1 -0
- package/configuration/types/renderOnlyDefault.d.ts +30 -0
- package/configuration/types/renderOnlyDefault.js +31 -0
- package/configuration/types/renderOnlyDefault.js.map +1 -0
- package/configuration/types/shadowLight.d.ts +9 -0
- package/configuration/types/shadowLight.js +64 -0
- package/configuration/types/shadowLight.js.map +1 -0
- package/helper/index.d.ts +29 -0
- package/helper/index.js +66 -0
- package/helper/index.js.map +1 -0
- package/index.d.ts +30 -0
- package/index.js +46 -0
- package/index.js.map +1 -0
- package/initializer.d.ts +11 -0
- package/initializer.js +35 -0
- package/initializer.js.map +1 -0
- package/interfaces.d.ts +5 -0
- package/interfaces.js +7 -0
- package/interfaces.js.map +1 -0
- package/labs/environmentSerializer.d.ts +126 -0
- package/labs/environmentSerializer.js +191 -0
- package/labs/environmentSerializer.js.map +1 -0
- package/labs/texture.d.ts +183 -0
- package/labs/texture.js +351 -0
- package/labs/texture.js.map +1 -0
- package/labs/viewerLabs.d.ts +51 -0
- package/labs/viewerLabs.js +134 -0
- package/labs/viewerLabs.js.map +1 -0
- package/loader/modelLoader.d.ts +56 -0
- package/loader/modelLoader.js +199 -0
- package/loader/modelLoader.js.map +1 -0
- package/loader/plugins/applyMaterialConfig.d.ts +12 -0
- package/loader/plugins/applyMaterialConfig.js +16 -0
- package/loader/plugins/applyMaterialConfig.js.map +1 -0
- package/loader/plugins/extendedMaterialLoaderPlugin.d.ts +9 -0
- package/loader/plugins/extendedMaterialLoaderPlugin.js +16 -0
- package/loader/plugins/extendedMaterialLoaderPlugin.js.map +1 -0
- package/loader/plugins/index.d.ts +19 -0
- package/loader/plugins/index.js +44 -0
- package/loader/plugins/index.js.map +1 -0
- package/loader/plugins/loaderPlugin.d.ts +24 -0
- package/loader/plugins/loaderPlugin.js +2 -0
- package/loader/plugins/loaderPlugin.js.map +1 -0
- package/loader/plugins/msftLodLoaderPlugin.d.ts +12 -0
- package/loader/plugins/msftLodLoaderPlugin.js +21 -0
- package/loader/plugins/msftLodLoaderPlugin.js.map +1 -0
- package/loader/plugins/telemetryLoaderPlugin.d.ts +12 -0
- package/loader/plugins/telemetryLoaderPlugin.js +36 -0
- package/loader/plugins/telemetryLoaderPlugin.js.map +1 -0
- package/managers/observablesManager.d.ts +66 -0
- package/managers/observablesManager.js +35 -0
- package/managers/observablesManager.js.map +1 -0
- package/managers/sceneManager.d.ts +245 -0
- package/managers/sceneManager.js +1375 -0
- package/managers/sceneManager.js.map +1 -0
- package/managers/telemetryManager.d.ts +78 -0
- package/managers/telemetryManager.js +117 -0
- package/managers/telemetryManager.js.map +1 -0
- package/model/modelAnimation.d.ts +215 -0
- package/model/modelAnimation.js +237 -0
- package/model/modelAnimation.js.map +1 -0
- package/model/viewerModel.d.ts +233 -0
- package/model/viewerModel.js +673 -0
- package/model/viewerModel.js.map +1 -0
- package/optimizer/custom/extended.d.ts +13 -0
- package/optimizer/custom/extended.js +101 -0
- package/optimizer/custom/extended.js.map +1 -0
- package/optimizer/custom/index.d.ts +9 -0
- package/optimizer/custom/index.js +26 -0
- package/optimizer/custom/index.js.map +1 -0
- package/package.json +29 -16
- package/readme.md +23 -22
- package/renderOnlyIndex.d.ts +11 -0
- package/renderOnlyIndex.js +18 -0
- package/renderOnlyIndex.js.map +1 -0
- package/templating/eventManager.d.ts +35 -0
- package/templating/eventManager.js +66 -0
- package/templating/eventManager.js.map +1 -0
- package/templating/plugins/hdButtonPlugin.d.ts +9 -0
- package/templating/plugins/hdButtonPlugin.js +21 -0
- package/templating/plugins/hdButtonPlugin.js.map +1 -0
- package/templating/plugins/printButton.d.ts +9 -0
- package/templating/plugins/printButton.js +40 -0
- package/templating/plugins/printButton.js.map +1 -0
- package/templating/templateManager.d.ts +197 -0
- package/templating/templateManager.js +561 -0
- package/templating/templateManager.js.map +1 -0
- package/templating/viewerTemplatePlugin.d.ts +21 -0
- package/templating/viewerTemplatePlugin.js +69 -0
- package/templating/viewerTemplatePlugin.js.map +1 -0
- package/viewer/defaultViewer.d.ts +130 -0
- package/viewer/defaultViewer.js +675 -0
- package/viewer/defaultViewer.js.map +1 -0
- package/viewer/renderOnlyViewer.d.ts +9 -0
- package/viewer/renderOnlyViewer.js +46 -0
- package/viewer/renderOnlyViewer.js.map +1 -0
- package/viewer/viewer.d.ts +258 -0
- package/viewer/viewer.js +783 -0
- package/viewer/viewer.js.map +1 -0
- package/viewer/viewerManager.d.ts +58 -0
- package/viewer/viewerManager.js +91 -0
- package/viewer/viewerManager.js.map +1 -0
- package/viewer/viewerWithTemplate.d.ts +9 -0
- package/viewer/viewerWithTemplate.js +20 -0
- package/viewer/viewerWithTemplate.js.map +1 -0
- package/dist/babylon-viewer.esm.js +0 -107281
- package/dist/babylon-viewer.esm.js.map +0 -1
- package/dist/babylon-viewer.esm.min.js +0 -2
- package/dist/babylon-viewer.esm.min.js.map +0 -1
- package/lib/index.d.ts +0 -113
- package/lib/index.js +0 -338
- package/lib/index.js.map +0 -1
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function e(e,t,i,s){var n,r=arguments.length,a=r<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,s);else for(var o=e.length-1;o>=0;o--)(n=e[o])&&(a=(r<3?n(a):r>3?n(t,i,a):n(t,i))||a);return r>3&&a&&Object.defineProperty(t,i,a),a}"function"==typeof SuppressedError&&SuppressedError;const t={},i={};function s(e){const s=e.getClassName();if(t[s])return t[s];t[s]={};const n=t[s];let r=e,a=s;for(;a;){const e=i[a];for(const t in e)n[t]=e[t];let t,s=!1;do{if(t=Object.getPrototypeOf(r),!t.getClassName){s=!0;break}if(t.getClassName()!==a)break;r=t}while(t);if(s)break;a=t.getClassName(),r=t}return n}function n(e,t){return(s,n)=>{const r=function(e){const t=e.getClassName();return i[t]||(i[t]={}),i[t]}(s);r[n]||(r[n]={type:e,sourceName:t})}}function r(e,t=null){return function(e,t=null){return(i,s)=>{const n=t||"_"+s;Object.defineProperty(i,s,{get:function(){return this[n]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[n]!==t&&(this[n]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function a(e){return n(0,e)}function o(e){return n(1,e)}function l(e){return n(2,e)}function h(e){return n(4,e)}function c(e){return n(5,e)}function u(e){return n(6,e)}function d(e){return n(8,e)}function _(e){return n(12,e)}function f(e,t,i,s){const n=i.value;i.value=(...i)=>{let r=n;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];r=s?(...t)=>s(...t)?e(...t):n(...t):e}return e[t]=r,r(...i)}}f.filter=function(e){return(t,i,s)=>f(t,i,s,e)};class m{constructor(e,t=!1,i,s){this.initialize(e,t,i,s)}initialize(e,t=!1,i,s){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=s,this}}class p{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class g{static FromPromise(e,t){const i=new g;return e.then((e=>{i.notifyObservers(e)})).catch((e=>{if(!t)throw e;t.notifyObservers(e)})),i}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 m(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,n=!1){if(!e)return null;const r=new p(e,t,s);return r.unregisterOnNextCall=n,i?this._observers.unshift(r):this._observers.push(r),this._onObserverAdded&&this._onObserverAdded(r),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(r,this._lastNotifiedValue),r._remove=()=>{this.remove(r)},r}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 i=0;i<this._observers.length;i++){const s=this._observers[i];if(!s._willBeUnregistered&&(s.callback===e&&(!t||t===s.scope)))return this._deferUnregister(s),!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 i=this._observers.indexOf(e);return-1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,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,i,s,n){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const r=this._eventState;r.mask=t,r.target=i,r.currentTarget=s,r.skipNextObservers=!1,r.lastReturnValue=e,r.userInfo=n;for(const i of this._observers)if(!i._willBeUnregistered&&(i.mask&t&&(i.unregisterOnNextCall&&this._deferUnregister(i),i.scope?r.lastReturnValue=i.callback.apply(i.scope,[e,r]):r.lastReturnValue=i.callback(e,r)),r.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const s=this._eventState;s.mask=i,s.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,s)}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 g;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}}const E=1/2.2,T=2.2,A=.001;class R{static BuildArray(e,t){const i=[];for(let s=0;s<e;++s)i.push(t());return i}static BuildTuple(e,t){return R.BuildArray(e,t)}}const v=["push","splice","pop","shift","unshift"];function I(e,t){const i=v.map((i=>function(e,t,i){const s=e[t];if("function"!=typeof s)return null;const n=function(){const s=e.length,r=n.previous.apply(e,arguments);return i(t,s),r};return s.next=n,n.previous=s,e[t]=n,()=>{const i=n.previous;if(!i)return;const s=n.next;s?(i.next=s,s.previous=i):(i.next=void 0,e[t]=i),n.next=void 0,n.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{e?.()}))}}const S={};function C(e,t){S[e]=t}function b(e){return S[e]}class y{static SetMatrixPrecision(e){if(y.MatrixTrackPrecisionChange=!1,e&&!y.MatrixUse64Bits&&y.MatrixTrackedMatrices)for(let e=0;e<y.MatrixTrackedMatrices.length;++e){const t=y.MatrixTrackedMatrices[e],i=t._m;t._m=new Array(16);for(let e=0;e<16;++e)t._m[e]=i[e]}y.MatrixUse64Bits=e,y.MatrixCurrentType=y.MatrixUse64Bits?Array:Float32Array,y.MatrixTrackedMatrices=null}}y.MatrixUse64Bits=!1,y.MatrixTrackPrecisionChange=!0,y.MatrixCurrentType=Float32Array,y.MatrixTrackedMatrices=[];class M{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}function x(e,t,i=1401298e-51){return Math.abs(e-t)<=i}function O(e,t){return e===t?e:Math.random()*(t-e)+e}function D(e,t,i){return e+(t-e)*i}function P(e,t=0,i=1){return Math.min(i,Math.max(t,e))}function N(e){return e-=2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function L(e){const t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}M.Instances=[],M.OnEnginesDisposedObservable=new g,M._LastCreatedScene=null,M.UseFallbackTexture=!0,M.FallbackTexture="";const F=e=>parseInt(e.toString().replace(/\W/g,""));class w{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=F(this.x);return e=397*e^F(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return w.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 w(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 w(this.x+e.x,this.y+e.y)}subtract(e){return new w(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 w(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 w(this.x*e,this.y*t)}divide(e){return new w(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 w(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.x=this.x-e,i.y=this.y-t,i}negate(){return new w(-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 w(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=A){return e&&x(this.x,e.x,t)&&x(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new w(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 w(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}rotateToRef(e,t){const i=Math.cos(e),s=Math.sin(e),n=i*this.x-s*this.y,r=s*this.x+i*this.y;return t.x=n,t.y=r,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 w;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new w(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new w(0,0)}static One(){return new w(1,1)}static Random(e=0,t=1){return new w(O(e,t),O(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(O(e,t),O(e,t))}static get ZeroReadOnly(){return w._ZeroReadOnly}static FromArray(e,t=0){return new w(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,s,n){const r=n*n,a=n*r,o=.5*(2*t.x+(-e.x+i.x)*n+(2*e.x-5*t.x+4*i.x-s.x)*r+(-e.x+3*t.x-3*i.x+s.x)*a),l=.5*(2*t.y+(-e.y+i.y)*n+(2*e.y-5*t.y+4*i.y-s.y)*r+(-e.y+3*t.y-3*i.y+s.y)*a);return new w(o,l)}static ClampToRef(e,t,i,s){return s.x=P(e.x,t.x,i.x),s.y=P(e.y,t.y,i.y),s}static Clamp(e,t,i){const s=P(e.x,t.x,i.x),n=P(e.y,t.y,i.y);return new w(s,n)}static Hermite(e,t,i,s,n){const r=n*n,a=n*r,o=2*a-3*r+1,l=-2*a+3*r,h=a-2*r+n,c=a-r,u=e.x*o+i.x*l+t.x*h+s.x*c,d=e.y*o+i.y*l+t.y*h+s.y*c;return new w(u,d)}static Hermite1stDerivative(e,t,i,s,n){return this.Hermite1stDerivativeToRef(e,t,i,s,n,new w)}static Hermite1stDerivativeToRef(e,t,i,s,n,r){const a=n*n;return r.x=6*(a-n)*e.x+(3*a-4*n+1)*t.x+6*(-a+n)*i.x+(3*a-2*n)*s.x,r.y=6*(a-n)*e.y+(3*a-4*n+1)*t.y+6*(-a+n)*i.y+(3*a-2*n)*s.y,r}static Lerp(e,t,i){return w.LerpToRef(e,t,i,new w)}static LerpToRef(e,t,i,s){return s.x=e.x+(t.x-e.x)*i,s.y=e.y+(t.y-e.y)*i,s}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return w.NormalizeToRef(e,new w)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.x<t.x?e.x:t.x,s=e.y<t.y?e.y:t.y;return new w(i,s)}static Maximize(e,t){const i=e.x>t.x?e.x:t.x,s=e.y>t.y?e.y:t.y;return new w(i,s)}static Transform(e,t){return w.TransformToRef(e,t,new w)}static TransformToRef(e,t,i){const s=t.m,n=e.x*s[0]+e.y*s[4]+s[12],r=e.x*s[1]+e.y*s[5]+s[13];return i.x=n,i.y=r,i}static PointInTriangle(e,t,i,s){const n=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),r=n<0?-1:1,a=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*r,o=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*r;return a>0&&o>0&&a+o<2*n*r}static Distance(e,t){return Math.sqrt(w.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y;return i*i+s*s}static Center(e,t){return w.CenterToRef(e,t,new w)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const s=w.DistanceSquared(t,i);if(0===s)return w.Distance(e,t);const n=i.subtract(t),r=Math.max(0,Math.min(1,w.Dot(e.subtract(t),n)/s)),a=t.add(n.multiplyByFloats(r,r));return w.Distance(e,a)}}w._ZeroReadOnly=w.Zero(),Object.defineProperties(w.prototype,{dimension:{value:[2]},rank:{value:1}});class B{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,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=F(this._x);return e=397*e^F(this._y),e=397*e^F(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 B.FromArrayToRef(e,t,this),this}toQuaternion(){return k.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,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new B(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new B(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,i){return new B(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new B(-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.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new B(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const s=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const n=t*Math.sin(i)*Math.cos(s),r=t*Math.cos(i),a=t*Math.sin(i)*Math.sin(s);return e.set(n,r,a),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,n=this._z,r=e._x,a=e._y,o=e._z,l=e._w,h=2*(a*n-o*s),c=2*(o*i-r*n),u=2*(r*s-a*i);return t._x=i+l*h+a*u-o*c,t._y=s+l*c+o*h-r*u,t._z=n+l*u+r*c-a*h,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new B)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new B)}projectOnPlaneToRef(e,t,i){const s=e.normal,n=e.d,r=V.Vector3[0];this.subtractToRef(t,r),r.normalize();const a=B.Dot(r,s);if(Math.abs(a)<1e-10)i.setAll(1/0);else{const e=-(B.Dot(t,s)+n)/a,o=r.scaleInPlace(e);t.addToRef(o,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=A){return e&&x(this._x,e._x,t)&&x(this._y,e._y,t)&&x(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}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.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new B(this._x*e,this._y*t,this._z*i)}divide(e){return new B(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}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,i){return e<this._x&&(this.x=e),t<this._y&&(this.y=t),i<this._z&&(this.z=i),this}maximizeInPlaceFromFloats(e,t,i){return e>this._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!x(t,i,e))return!0;const s=Math.abs(this._z);return!x(t,s,e)||!x(i,s,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 B(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 B(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=V.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(V.Matrix[0]),B.TransformCoordinatesToRef(this,V.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,V.Vector3[0]),V.Vector3[0].rotateByQuaternionToRef(e,V.Vector3[0]),t.addToRef(V.Vector3[0],i),i}cross(e){return B.CrossToRef(this,e,new B)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new B)}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new B(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,s){const n=B.Dot(e,i);return(n-s)/(n-B.Dot(t,i))}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(V.Vector3[1]),n=t.normalizeToRef(V.Vector3[2]);let r=B.Dot(s,n);r=P(r,-1,1);const a=Math.acos(r),o=V.Vector3[3];return B.CrossToRef(s,n,o),B.Dot(o,i)>0?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(r)}static GetAngleBetweenVectorsOnPlane(e,t,i){V.Vector3[0].copyFrom(e);const s=V.Vector3[0];V.Vector3[1].copyFrom(t);const n=V.Vector3[1];V.Vector3[2].copyFrom(i);const r=V.Vector3[2],a=V.Vector3[3],o=V.Vector3[4];s.normalize(),n.normalize(),r.normalize(),B.CrossToRef(r,s,a),B.CrossToRef(a,r,o);return N(Math.atan2(B.Dot(n,a),B.Dot(n,o)))}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=X.Vector3[0];return t.subtractToRef(e,s),i._y=Math.atan2(s.x,s.z)||0,i._x=Math.atan2(Math.sqrt(s.x**2+s.z**2),s.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=B.Zero();return B.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=P(i,0,1);const n=V.Vector3[0],r=V.Vector3[1];n.copyFrom(e);const a=n.length();n.normalizeFromLength(a),r.copyFrom(t);const o=r.length();r.normalizeFromLength(o);const l=B.Dot(n,r);let h,c;if(l<1-A){const e=Math.acos(l),t=1/Math.sin(e);h=Math.sin((1-i)*e)*t,c=Math.sin(i*e)*t}else h=1-i,c=i;return n.scaleInPlace(h),r.scaleInPlace(c),s.copyFrom(n).addInPlace(r),s.scaleInPlace(D(a,o,i)),s}static SmoothToRef(e,t,i,s,n){return B.SlerpToRef(e,t,0===s?1:i/s,n),n}static FromArray(e,t=0){return new B(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return B.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return B.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new B(0,0,0)}static One(){return new B(1,1,1)}static Up(){return new B(0,1,0)}static get UpReadOnly(){return B._UpReadOnly}static get DownReadOnly(){return B._DownReadOnly}static get RightReadOnly(){return B._RightReadOnly}static get LeftReadOnly(){return B._LeftReadOnly}static get LeftHandedForwardReadOnly(){return B._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return B._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return B._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return B._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return B._ZeroReadOnly}static get OneReadOnly(){return B._OneReadOnly}static Down(){return new B(0,-1,0)}static Forward(e=!1){return new B(0,0,e?-1:1)}static Backward(e=!1){return new B(0,0,e?1:-1)}static Right(){return new B(1,0,0)}static Left(){return new B(-1,0,0)}static Random(e=0,t=1){return new B(O(e,t),O(e,t),O(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(O(e,t),O(e,t),O(e,t))}static TransformCoordinates(e,t){const i=B.Zero();return B.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return B.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,n){const r=s.m,a=e*r[0]+t*r[4]+i*r[8]+r[12],o=e*r[1]+t*r[5]+i*r[9]+r[13],l=e*r[2]+t*r[6]+i*r[10]+r[14],h=1/(e*r[3]+t*r[7]+i*r[11]+r[15]);return n._x=a*h,n._y=o*h,n._z=l*h,n._isDirty=!0,n}static TransformNormal(e,t){const i=B.Zero();return B.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,s,n){const r=s.m;return n._x=e*r[0]+t*r[4]+i*r[8],n._y=e*r[1]+t*r[5]+i*r[9],n._z=e*r[2]+t*r[6]+i*r[10],n._isDirty=!0,n}static CatmullRom(e,t,i,s,n){const r=n*n,a=n*r,o=.5*(2*t._x+(-e._x+i._x)*n+(2*e._x-5*t._x+4*i._x-s._x)*r+(-e._x+3*t._x-3*i._x+s._x)*a),l=.5*(2*t._y+(-e._y+i._y)*n+(2*e._y-5*t._y+4*i._y-s._y)*r+(-e._y+3*t._y-3*i._y+s._y)*a),h=.5*(2*t._z+(-e._z+i._z)*n+(2*e._z-5*t._z+4*i._z-s._z)*r+(-e._z+3*t._z-3*i._z+s._z)*a);return new B(o,l,h)}static Clamp(e,t,i){const s=new B;return B.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let n=e._x;n=n>i._x?i._x:n,n=n<t._x?t._x:n;let r=e._y;r=r>i._y?i._y:r,r=r<t._y?t._y:r;let a=e._z;return a=a>i._z?i._z:a,a=a<t._z?t._z:a,s.copyFromFloats(n,r,a),s}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static Hermite(e,t,i,s,n){const r=n*n,a=n*r,o=2*a-3*r+1,l=-2*a+3*r,h=a-2*r+n,c=a-r,u=e._x*o+i._x*l+t._x*h+s._x*c,d=e._y*o+i._y*l+t._y*h+s._y*c,_=e._z*o+i._z*l+t._z*h+s._z*c;return new B(u,d,_)}static Hermite1stDerivative(e,t,i,s,n){const r=new B;return this.Hermite1stDerivativeToRef(e,t,i,s,n,r),r}static Hermite1stDerivativeToRef(e,t,i,s,n,r){const a=n*n;return r._x=6*(a-n)*e._x+(3*a-4*n+1)*t._x+6*(-a+n)*i._x+(3*a-2*n)*s._x,r._y=6*(a-n)*e._y+(3*a-4*n+1)*t._y+6*(-a+n)*i._y+(3*a-2*n)*s._y,r._z=6*(a-n)*e._z+(3*a-4*n+1)*t._z+6*(-a+n)*i._z+(3*a-2*n)*s._z,r._isDirty=!0,r}static Lerp(e,t,i){const s=new B(0,0,0);return B.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){return s._x=e._x+(t._x-e._x)*i,s._y=e._y+(t._y-e._y)*i,s._z=e._z+(t._z-e._z)*i,s._isDirty=!0,s}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 i=new B;return B.CrossToRef(e,t,i),i}static CrossToRef(e,t,i){const s=e._y*t._z-e._z*t._y,n=e._z*t._x-e._x*t._z,r=e._x*t._y-e._y*t._x;return i.copyFromFloats(s,n,r),i}static Normalize(e){const t=B.Zero();return B.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Project(e,t,i,s){const n=new B;return B.ProjectToRef(e,t,i,s,n),n}static ProjectToRef(e,t,i,s,n){const r=s.width,a=s.height,o=s.x,l=s.y,h=V.Matrix[1],c=M.LastCreatedEngine?.isNDCHalfZRange,u=c?1:.5,d=c?0:.5;G.FromValuesToRef(r/2,0,0,0,0,-a/2,0,0,0,0,u,0,o+r/2,a/2+l,d,1,h);const _=V.Matrix[0];return t.multiplyToRef(i,_),_.multiplyToRef(h,_),B.TransformCoordinatesToRef(e,_,n),n}static Reflect(e,t){return this.ReflectToRef(e,t,new B)}static ReflectToRef(e,t,i){const s=X.Vector3[0];return s.copyFrom(t).scaleInPlace(2*B.Dot(e,t)),i.copyFrom(e).subtractInPlace(s)}static _UnprojectFromInvertedMatrixToRef(e,t,i){B.TransformCoordinatesToRef(e,t,i);const s=t.m,n=e._x*s[3]+e._y*s[7]+e._z*s[11]+s[15];return x(n,1)&&i.scaleInPlace(1/n),i}static UnprojectFromTransform(e,t,i,s,n){return this.Unproject(e,t,i,s,n,G.IdentityReadOnly)}static Unproject(e,t,i,s,n,r){const a=new B;return B.UnprojectToRef(e,t,i,s,n,r,a),a}static UnprojectToRef(e,t,i,s,n,r,a){return B.UnprojectFloatsToRef(e._x,e._y,e._z,t,i,s,n,r,a),a}static UnprojectFloatsToRef(e,t,i,s,n,r,a,o,l){const h=V.Matrix[0];r.multiplyToRef(a,h),h.multiplyToRef(o,h),h.invert();const c=V.Vector3[0];return c.x=e/s*2-1,c.y=-(t/n*2-1),M.LastCreatedEngine?.isNDCHalfZRange?c.z=i:c.z=2*i-1,B._UnprojectFromInvertedMatrixToRef(c,h,l),l}static Minimize(e,t){const i=new B;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new B;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(B.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e._x-t._x,s=e._y-t._y,n=e._z-t._z;return i*i+s*s+n*n}static ProjectOnTriangleToRef(e,t,i,s,n){const r=V.Vector3[0],a=V.Vector3[1],o=V.Vector3[2],l=V.Vector3[3],h=V.Vector3[4];i.subtractToRef(t,r),s.subtractToRef(t,a),s.subtractToRef(i,o);const c=r.length(),u=a.length(),d=o.length();if(c<A||u<A||d<A)return n.copyFrom(t),B.Distance(e,t);e.subtractToRef(t,h),B.CrossToRef(r,a,l);const _=l.length();if(_<A)return n.copyFrom(t),B.Distance(e,t);l.normalizeFromLength(_);let f=h.length();if(f<A)return n.copyFrom(t),0;h.normalizeFromLength(f);const m=B.Dot(l,h),p=V.Vector3[5],g=V.Vector3[6];p.copyFrom(l).scaleInPlace(-f*m),g.copyFrom(e).addInPlace(p);const E=V.Vector3[4],T=V.Vector3[5],R=V.Vector3[7],v=V.Vector3[8];E.copyFrom(r).scaleInPlace(1/c),v.copyFrom(a).scaleInPlace(1/u),E.addInPlace(v).scaleInPlace(-1),T.copyFrom(r).scaleInPlace(-1/c),v.copyFrom(o).scaleInPlace(1/d),T.addInPlace(v).scaleInPlace(-1),R.copyFrom(o).scaleInPlace(-1/d),v.copyFrom(a).scaleInPlace(-1/u),R.addInPlace(v).scaleInPlace(-1);const I=V.Vector3[9];let S;I.copyFrom(g).subtractInPlace(t),B.CrossToRef(E,I,v),S=B.Dot(v,l);const C=S;I.copyFrom(g).subtractInPlace(i),B.CrossToRef(T,I,v),S=B.Dot(v,l);const b=S;I.copyFrom(g).subtractInPlace(s),B.CrossToRef(R,I,v),S=B.Dot(v,l);const y=S,M=V.Vector3[10];let x,O;C>0&&b<0?(M.copyFrom(r),x=t,O=i):b>0&&y<0?(M.copyFrom(o),x=i,O=s):(M.copyFrom(a).scaleInPlace(-1),x=s,O=t);const D=V.Vector3[9],N=V.Vector3[4];x.subtractToRef(g,v),O.subtractToRef(g,D),B.CrossToRef(v,D,N);if(!(B.Dot(N,l)<0))return n.copyFrom(g),Math.abs(f*m);const L=V.Vector3[5];B.CrossToRef(M,N,L),L.normalize();const F=V.Vector3[9];F.copyFrom(x).subtractInPlace(g);const w=F.length();if(w<A)return n.copyFrom(x),B.Distance(e,x);F.normalizeFromLength(w);const U=B.Dot(L,F),k=V.Vector3[7];k.copyFrom(g).addInPlace(L.scaleInPlace(w*U)),v.copyFrom(k).subtractInPlace(x),f=M.length(),M.normalizeFromLength(f);let G=B.Dot(v,M)/Math.max(f,A);return G=P(G,0,1),k.copyFrom(x).addInPlace(M.scaleInPlace(G*f)),n.copyFrom(k),B.Distance(e,k)}static Center(e,t){return B.CenterToRef(e,t,B.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e._x+t._x)/2,(e._y+t._y)/2,(e._z+t._z)/2)}static RotationFromAxis(e,t,i){const s=new B;return B.RotationFromAxisToRef(e,t,i,s),s}static RotationFromAxisToRef(e,t,i,s){const n=V.Quaternion[0];return k.RotationQuaternionFromAxisToRef(e,t,i,n),n.toEulerAnglesToRef(s),s}}B._UpReadOnly=B.Up(),B._DownReadOnly=B.Down(),B._LeftHandedForwardReadOnly=B.Forward(!1),B._RightHandedForwardReadOnly=B.Forward(!0),B._LeftHandedBackwardReadOnly=B.Backward(!1),B._RightHandedBackwardReadOnly=B.Backward(!0),B._RightReadOnly=B.Right(),B._LeftReadOnly=B.Left(),B._ZeroReadOnly=B.Zero(),B._OneReadOnly=B.One(),Object.defineProperties(B.prototype,{dimension:{value:[3]},rank:{value:1}});class U{constructor(e=0,t=0,i=0,s=0){this.x=e,this.y=t,this.z=i,this.w=s}toString(){return`{X: ${this.x} Y: ${this.y} Z: ${this.z} W: ${this.w}}`}getClassName(){return"Vector4"}getHashCode(){let e=F(this.x);return e=397*e^F(this.y),e=397*e^F(this.z),e=397*e^F(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 U.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,i,s){return this.x+=e,this.y+=t,this.z+=i,this.w+=s,this}add(e){return new U(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 U(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,i,s){return new U(this.x-e,this.y-t,this.z-i,this.w-s)}subtractFromFloatsToRef(e,t,i,s,n){return n.x=this.x-e,n.y=this.y-t,n.z=this.z-i,n.w=this.w-s,n}negate(){return new U(-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 U(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=A){return e&&x(this.x,e.x,t)&&x(this.y,e.y,t)&&x(this.z,e.z,t)&&x(this.w,e.w,t)}equalsToFloats(e,t,i,s){return this.x===e&&this.y===t&&this.z===i&&this.w===s}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiply(e){return new U(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,i,s){return new U(this.x*e,this.y*t,this.z*i,this.w*s)}divide(e){return new U(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,i,s){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(s,this.w),this}maximizeInPlaceFromFloats(e,t,i,s){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(s,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 U(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 U(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 U)}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 B(this.x,this.y,this.z)}clone(){return new U(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,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}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 U(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return U.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,n){return n.x=e,n.y=t,n.z=i,n.w=s,n}static Zero(){return new U(0,0,0,0)}static One(){return new U(1,1,1,1)}static Random(e=0,t=1){return new U(O(e,t),O(e,t),O(e,t),O(e,t))}static RandomToRef(e=0,t=1,i){return i.x=O(e,t),i.y=O(e,t),i.z=O(e,t),i.w=O(e,t),i}static Clamp(e,t,i){return U.ClampToRef(e,t,i,new U)}static ClampToRef(e,t,i,s){return s.x=P(e.x,t.x,i.x),s.y=P(e.y,t.y,i.y),s.z=P(e.z,t.z,i.z),s.w=P(e.w,t.w,i.w),s}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return U._ZeroReadOnly}static Normalize(e){return U.NormalizeToRef(e,new U)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new U;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new U;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(U.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,n=e.z-t.z,r=e.w-t.w;return i*i+s*s+n*n+r*r}static Center(e,t){return U.CenterToRef(e,t,new U)}static CenterToRef(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i}static TransformCoordinates(e,t){return U.TransformCoordinatesToRef(e,t,new U)}static TransformCoordinatesToRef(e,t,i){return U.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,n){const r=s.m,a=e*r[0]+t*r[4]+i*r[8]+r[12],o=e*r[1]+t*r[5]+i*r[9]+r[13],l=e*r[2]+t*r[6]+i*r[10]+r[14],h=e*r[3]+t*r[7]+i*r[11]+r[15];return n.x=a,n.y=o,n.z=l,n.w=h,n}static TransformNormal(e,t){return U.TransformNormalToRef(e,t,new U)}static TransformNormalToRef(e,t,i){const s=t.m,n=e.x*s[0]+e.y*s[4]+e.z*s[8],r=e.x*s[1]+e.y*s[5]+e.z*s[9],a=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=n,i.y=r,i.z=a,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,n,r){const a=n.m;return r.x=e*a[0]+t*a[4]+i*a[8],r.y=e*a[1]+t*a[5]+i*a[9],r.z=e*a[2]+t*a[6]+i*a[10],r.w=s,r}static FromVector3(e,t=0){return new U(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}}U._ZeroReadOnly=U.Zero(),Object.defineProperties(U.prototype,{dimension:{value:[4]},rank:{value:1}});class k{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,i=0,s=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=F(this._x);return e=397*e^F(this._y),e=397*e^F(this._z),e=397*e^F(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 k.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=A){return e&&x(this._x,e._x,t)&&x(this._y,e._y,t)&&x(this._z,e._z,t)&&x(this._w,e._w,t)}clone(){return new k(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,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._isDirty=!0,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new k(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,i,s){return this._x+=e,this._y+=t,this._z+=i,this._w+=s,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,i,s){return this.subtractFromFloatsToRef(e,t,i,s,new k)}subtractFromFloatsToRef(e,t,i,s,n){return n._x=this._x-e,n._y=this._y-t,n._z=this._z-i,n._w=this._w-s,n._isDirty=!0,n}subtract(e){return new k(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 k(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 k(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,s=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,n=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,r=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,n,r),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,s){return this._x*=e,this._y*=t,this._z*=i,this._w*=s,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 k)}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,i,s){return this._x===e&&this._y===t&&this._z===i&&this._w===s}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 k(-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 k(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=B.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,n=this._w,r=s*t-i*n,a=.4999999;if(r<-a)e._y=2*Math.atan2(s,n),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(r>a)e._y=2*Math.atan2(s,n),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const a=n*n,o=t*t,l=i*i,h=s*s;e._z=Math.atan2(2*(i*s+t*n),-o-l+h+a),e._x=Math.asin(-2*r),e._y=Math.atan2(2*(t*i+s*n),o-l-h+a),e._isDirty=!0}return e}toAlphaBetaGammaToRef(e){const t=this._z,i=this._x,s=this._y,n=this._w,r=Math.sqrt(i*i+s*s),a=Math.sqrt(t*t+n*n),o=2*Math.atan2(r,a),l=2*Math.atan2(t,n),h=2*Math.atan2(s,i),c=(l+h)/2,u=(l-h)/2;return e.set(u,o,c),e}toRotationMatrix(e){return G.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return k.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}static FromRotationMatrix(e){const t=new k;return k.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],n=i[4],r=i[8],a=i[1],o=i[5],l=i[9],h=i[2],c=i[6],u=i[10],d=s+o+u;let _;return d>0?(_=.5/Math.sqrt(d+1),t._w=.25/_,t._x=(c-l)*_,t._y=(r-h)*_,t._z=(a-n)*_,t._isDirty=!0):s>o&&s>u?(_=2*Math.sqrt(1+s-o-u),t._w=(c-l)/_,t._x=.25*_,t._y=(n+a)/_,t._z=(r+h)/_,t._isDirty=!0):o>u?(_=2*Math.sqrt(1+o-s-u),t._w=(r-h)/_,t._x=(n+a)/_,t._y=.25*_,t._z=(l+c)/_,t._isDirty=!0):(_=2*Math.sqrt(1+u-s-o),t._w=(a-n)/_,t._x=(r+h)/_,t._y=(l+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,i=.1){const s=k.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,n){let r=0===s?1:i/s;return r=P(r,0,1),k.SlerpToRef(e,t,r,n),n}static Zero(){return new k(0,0,0,0)}static Inverse(e){return new k(-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 k(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 k.RotationAxisToRef(e,t,new k)}static RotationAxisToRef(e,t,i){const s=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*s,i._y=e._y*s,i._z=e._z*s,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new k(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,s,n){return n.copyFromFloats(e,t,i,s),n}static FromEulerAngles(e,t,i){const s=new k;return k.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return k.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new k;return k.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return k.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=A){const n=B.Dot(e,t)+1;return n<s?Math.abs(e.x)>Math.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(B.CrossToRef(e,t,X.Vector3[0]),i.set(X.Vector3[0].x,X.Vector3[0].y,X.Vector3[0].z,n)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new k;return k.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const n=.5*i,r=.5*t,a=.5*e,o=Math.sin(n),l=Math.cos(n),h=Math.sin(r),c=Math.cos(r),u=Math.sin(a),d=Math.cos(a);return s._x=d*h*l+u*c*o,s._y=u*c*l-d*h*o,s._z=d*c*o-u*h*l,s._w=d*c*l+u*h*o,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new k;return k.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const n=.5*(i+e),r=.5*(i-e),a=.5*t;return s._x=Math.cos(r)*Math.sin(a),s._y=Math.sin(r)*Math.sin(a),s._z=Math.sin(n)*Math.cos(a),s._w=Math.cos(n)*Math.cos(a),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new k(0,0,0,0);return k.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const n=V.Matrix[0];return G.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),n),k.FromRotationMatrixToRef(n,s),s}static FromLookDirectionLH(e,t){const i=new k;return k.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=V.Matrix[0];return G.LookDirectionLHToRef(e,t,s),k.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new k;return k.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=V.Matrix[0];return G.LookDirectionRHToRef(e,t,s),k.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=k.Identity();return k.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let n,r,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)r=1-i,n=o?-i:i;else{const e=Math.acos(a),t=1/Math.sin(e);r=Math.sin((1-i)*e)*t,n=o?-Math.sin(i*e)*t:Math.sin(i*e)*t}return s._x=r*e._x+n*t._x,s._y=r*e._y+n*t._y,s._z=r*e._z+n*t._z,s._w=r*e._w+n*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,n){const r=n*n,a=n*r,o=2*a-3*r+1,l=-2*a+3*r,h=a-2*r+n,c=a-r,u=e._x*o+i._x*l+t._x*h+s._x*c,d=e._y*o+i._y*l+t._y*h+s._y*c,_=e._z*o+i._z*l+t._z*h+s._z*c,f=e._w*o+i._w*l+t._w*h+s._w*c;return new k(u,d,_,f)}static Hermite1stDerivative(e,t,i,s,n){const r=new k;return this.Hermite1stDerivativeToRef(e,t,i,s,n,r),r}static Hermite1stDerivativeToRef(e,t,i,s,n,r){const a=n*n;return r._x=6*(a-n)*e._x+(3*a-4*n+1)*t._x+6*(-a+n)*i._x+(3*a-2*n)*s._x,r._y=6*(a-n)*e._y+(3*a-4*n+1)*t._y+6*(-a+n)*i._y+(3*a-2*n)*s._y,r._z=6*(a-n)*e._z+(3*a-4*n+1)*t._z+6*(-a+n)*i._z+(3*a-2*n)*s._z,r._w=6*(a-n)*e._w+(3*a-4*n+1)*t._w+6*(-a+n)*i._w+(3*a-2*n)*s._w,r._isDirty=!0,r}static Normalize(e){const t=k.Zero();return k.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const s=new k;return k.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(P(e.x,t.x,i.x),P(e.y,t.y,i.y),P(e.z,t.z,i.z),P(e.w,t.w,i.w))}static Random(e=0,t=1){return new k(O(e,t),O(e,t),O(e,t),O(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(O(e,t),O(e,t),O(e,t),O(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(k.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,n=e.z-t.z,r=e.w-t.w;return i*i+s*s+n*n+r*r}static Center(e,t){return k.CenterToRef(e,t,k.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}Object.defineProperties(k.prototype,{dimension:{value:[4]},rank:{value:1}});class G{static get Use64Bits(){return y.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=G._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,s=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&s}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,y.MatrixTrackPrecisionChange&&y.MatrixTrackedMatrices.push(this),this._m=new y.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],i=e[1],s=e[2],n=e[3],r=e[4],a=e[5],o=e[6],l=e[7],h=e[8],c=e[9],u=e[10],d=e[11],_=e[12],f=e[13],m=e[14],p=e[15],g=u*p-m*d,E=c*p-f*d,T=c*m-f*u,A=h*p-_*d,R=h*m-u*_,v=h*f-_*c;return t*+(a*g-o*E+l*T)+i*-(r*g-o*A+l*R)+s*+(r*E-a*A+l*v)+n*-(r*T-a*R+o*v)}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 i=this._m;for(let s=0;s<16;s++)e[t+s]=i[s];return this}asArray(){return this._m}fromArray(e,t=0){return G.FromArrayToRef(e,t,this)}copyFromFloats(...e){return G.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return G.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 G;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,s=t._m,n=e.m;for(let e=0;e<16;e++)s[e]=i[e]+n[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;return t[0]+=i[0],t[1]+=i[1],t[2]+=i[2],t[3]+=i[3],t[4]+=i[4],t[5]+=i[5],t[6]+=i[6],t[7]+=i[7],t[8]+=i[8],t[9]+=i[9],t[10]+=i[10],t[11]+=i[11],t[12]+=i[12],t[13]+=i[13],t[14]+=i[14],t[15]+=i[15],this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,s=e.m,n=t._m;for(let e=0;e<16;e++)n[e]=i[e]-s[e];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new G)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,n=e;for(let e=0;e<16;e++)s[e]=i[e]-n[e];return t.markAsUpdated(),t}invertToRef(e){if(!0===this._isIdentity)return G.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],n=t[2],r=t[3],a=t[4],o=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],_=t[11],f=t[12],m=t[13],p=t[14],g=t[15],E=d*g-p*_,T=u*g-m*_,A=u*p-m*d,R=c*g-f*_,v=c*p-d*f,I=c*m-f*u,S=+(o*E-l*T+h*A),C=-(a*E-l*R+h*v),b=+(a*T-o*R+h*I),y=-(a*A-o*v+l*I),M=i*S+s*C+n*b+r*y;if(0===M)return e.copyFrom(this),e;const x=1/M,O=l*g-p*h,D=o*g-m*h,P=o*p-m*l,N=a*g-f*h,L=a*p-f*l,F=a*m-f*o,w=l*_-d*h,B=o*_-u*h,U=o*d-u*l,k=a*_-c*h,V=a*d-c*l,X=a*u-c*o,H=-(s*E-n*T+r*A),z=+(i*E-n*R+r*v),W=-(i*T-s*R+r*I),Y=+(i*A-s*v+n*I),K=+(s*O-n*D+r*P),q=-(i*O-n*N+r*L),Q=+(i*D-s*N+r*F),j=-(i*P-s*L+n*F),Z=-(s*w-n*B+r*U),$=+(i*w-n*k+r*V),J=-(i*B-s*k+r*X),ee=+(i*U-s*V+n*X);return G.FromValuesToRef(S*x,H*x,K*x,Z*x,C*x,z*x,q*x,$*x,b*x,W*x,Q*x,J*x,y*x,Y*x,j*x,ee*x,e),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,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new B(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 G.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){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiply(e){const t=new G;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]*=i[e];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,n=e;for(let e=0;e<16;e++)s[e]=i[e]*n[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,i){const s=this._m,n=e.m,r=s[0],a=s[1],o=s[2],l=s[3],h=s[4],c=s[5],u=s[6],d=s[7],_=s[8],f=s[9],m=s[10],p=s[11],g=s[12],E=s[13],T=s[14],A=s[15],R=n[0],v=n[1],I=n[2],S=n[3],C=n[4],b=n[5],y=n[6],M=n[7],x=n[8],O=n[9],D=n[10],P=n[11],N=n[12],L=n[13],F=n[14],w=n[15];return t[i]=r*R+a*C+o*x+l*N,t[i+1]=r*v+a*b+o*O+l*L,t[i+2]=r*I+a*y+o*D+l*F,t[i+3]=r*S+a*M+o*P+l*w,t[i+4]=h*R+c*C+u*x+d*N,t[i+5]=h*v+c*b+u*O+d*L,t[i+6]=h*I+c*y+u*D+d*F,t[i+7]=h*S+c*M+u*P+d*w,t[i+8]=_*R+f*C+m*x+p*N,t[i+9]=_*v+f*b+m*O+p*L,t[i+10]=_*I+f*y+m*D+p*F,t[i+11]=_*S+f*M+m*P+p*w,t[i+12]=g*R+E*C+T*x+A*N,t[i+13]=g*v+E*b+T*O+A*L,t[i+14]=g*I+E*y+T*D+A*F,t[i+15]=g*S+E*M+T*P+A*w,this}divide(e){return this.divideToRef(e,new G)}divideToRef(e,t){const i=this._m,s=e.m,n=t._m;for(let e=0;e<16;e++)n[e]=i[e]/s[e];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]/=i[e];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new G)}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,i=e._m;for(let e=0;e<16;e++)i[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 i=this.m,s=t.m;return i[0]===s[0]&&i[1]===s[1]&&i[2]===s[2]&&i[3]===s[3]&&i[4]===s[4]&&i[5]===s[5]&&i[6]===s[6]&&i[7]===s[7]&&i[8]===s[8]&&i[9]===s[9]&&i[10]===s[10]&&i[11]===s[11]&&i[12]===s[12]&&i[13]===s[13]&&i[14]===s[14]&&i[15]===s[15]}equalsWithEpsilon(e,t=0){const i=this._m,s=e.m;for(let e=0;e<16;e++)if(!x(i[e],s[e],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new G)}floorToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=Math.floor(t[e]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new G)}fractToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=t[e]-Math.floor(t[e]);return e.markAsUpdated(),e}clone(){const e=new G;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=F(this._m[0]);for(let t=1;t<16;t++)e=397*e^F(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new k,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s,n=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const r=this._m;if(i&&i.copyFromFloats(r[12],r[13],r[14]),(e=e||V.Vector3[0]).x=Math.sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]),e.y=Math.sqrt(r[4]*r[4]+r[5]*r[5]+r[6]*r[6]),e.z=Math.sqrt(r[8]*r[8]+r[9]*r[9]+r[10]*r[10]),s){const t=(n?s.absoluteScaling.x:s.scaling.x)<0?-1:1,i=(n?s.absoluteScaling.y:s.scaling.y)<0?-1:1,r=(n?s.absoluteScaling.z:s.scaling.z)<0?-1:1;e.x*=t,e.y*=i,e.z*=r}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 i=1/e._x,s=1/e._y,n=1/e._z;G.FromValuesToRef(r[0]*i,r[1]*i,r[2]*i,0,r[4]*s,r[5]*s,r[6]*s,0,r[8]*n,r[9]*n,r[10]*n,0,0,0,0,1,V.Matrix[0]),k.FromRotationMatrixToRef(V.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new U(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 i=4*e;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){const e=new G;return G.TransposeToRef(this,e),e}transposeToRef(e){return G.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,n){if(e<0||e>3)return this;const r=4*e;return this._m[r+0]=t,this._m[r+1]=i,this._m[r+2]=s,this._m[r+3]=n,this.markAsUpdated(),this}scale(e){const t=new G;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=V.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return G.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){const e=new G;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=V.Vector3[0];if(!this.decompose(t))return G.IdentityToRef(e),e;const i=this._m,s=1/t._x,n=1/t._y,r=1/t._z;return G.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*n,i[5]*n,i[6]*n,0,i[8]*r,i[9]*r,i[10]*r,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}static FromArray(e,t=0){const i=new G;return G.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let s=0;s<16;s++)i._m[s]=e[s+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,s){return s._m[0]=e[0+t]*i,s._m[1]=e[1+t]*i,s._m[2]=e[2+t]*i,s._m[3]=e[3+t]*i,s._m[4]=e[4+t]*i,s._m[5]=e[5+t]*i,s._m[6]=e[6+t]*i,s._m[7]=e[7+t]*i,s._m[8]=e[8+t]*i,s._m[9]=e[9+t]*i,s._m[10]=e[10+t]*i,s._m[11]=e[11+t]*i,s._m[12]=e[12+t]*i,s._m[13]=e[13+t]*i,s._m[14]=e[14+t]*i,s._m[15]=e[15+t]*i,s.markAsUpdated(),s}static get IdentityReadOnly(){return G._IdentityReadOnly}static FromValuesToRef(e,t,i,s,n,r,a,o,l,h,c,u,d,_,f,m,p){const g=p._m;g[0]=e,g[1]=t,g[2]=i,g[3]=s,g[4]=n,g[5]=r,g[6]=a,g[7]=o,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=f,g[15]=m,p.markAsUpdated()}static FromValues(e,t,i,s,n,r,a,o,l,h,c,u,d,_,f,m){const p=new G,g=p._m;return g[0]=e,g[1]=t,g[2]=i,g[3]=s,g[4]=n,g[5]=r,g[6]=a,g[7]=o,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=f,g[15]=m,p.markAsUpdated(),p}static Compose(e,t,i){const s=new G;return G.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const n=s._m,r=t._x,a=t._y,o=t._z,l=t._w,h=r+r,c=a+a,u=o+o,d=r*h,_=r*c,f=r*u,m=a*c,p=a*u,g=o*u,E=l*h,T=l*c,A=l*u,R=e._x,v=e._y,I=e._z;return n[0]=(1-(m+g))*R,n[1]=(_+A)*R,n[2]=(f-T)*R,n[3]=0,n[4]=(_-A)*v,n[5]=(1-(d+g))*v,n[6]=(p+E)*v,n[7]=0,n[8]=(f+T)*I,n[9]=(p-E)*I,n[10]=(1-(d+m))*I,n[11]=0,n[12]=i._x,n[13]=i._y,n[14]=i._z,n[15]=1,s.markAsUpdated(),s}static Identity(){const e=G.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 G.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=G.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 G;return G.RotationXToRef(e,t),t}static Invert(e){const t=new G;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return G.FromValuesToRef(1,0,0,0,0,s,i,0,0,-i,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationY(e){const t=new G;return G.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return G.FromValuesToRef(s,0,-i,0,0,1,0,0,i,0,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationZ(e){const t=new G;return G.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return G.FromValuesToRef(s,i,0,0,-i,s,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationAxis(e,t){const i=new G;return G.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),n=Math.cos(-t),r=1-n;e.normalize();const a=i._m;return a[0]=e._x*e._x*r+n,a[1]=e._x*e._y*r-e._z*s,a[2]=e._x*e._z*r+e._y*s,a[3]=0,a[4]=e._y*e._x*r+e._z*s,a[5]=e._y*e._y*r+n,a[6]=e._y*e._z*r-e._x*s,a[7]=0,a[8]=e._z*e._x*r-e._y*s,a[9]=e._z*e._y*r+e._x*s,a[10]=e._z*e._z*r+n,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const n=B.Dot(t,e),r=i._m;if(n<-1+A)r[0]=-1,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=s?1:-1,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=s?-1:1,r[11]=0;else{const i=B.Cross(t,e),s=1/(1+n);r[0]=i._x*i._x*s+n,r[1]=i._y*i._x*s-i._z,r[2]=i._z*i._x*s+i._y,r[3]=0,r[4]=i._x*i._y*s+i._z,r[5]=i._y*i._y*s+n,r[6]=i._z*i._y*s-i._x,r[7]=0,r[8]=i._x*i._z*s-i._y,r[9]=i._y*i._z*s+i._x,r[10]=i._z*i._z*s+n,r[11]=0}return r[12]=0,r[13]=0,r[14]=0,r[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new G;return G.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return k.RotationYawPitchRollToRef(e,t,i,V.Quaternion[0]),V.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new G;return G.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return G.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,s),s._updateIdentityStatus(1===e&&1===t&&1===i),s}static Translation(e,t,i){const s=new G;return G.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return G.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,s),s._updateIdentityStatus(0===e&&0===t&&0===i),s}static Lerp(e,t,i){const s=new G;return G.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const n=s._m,r=e.m,a=t.m;for(let e=0;e<16;e++)n[e]=r[e]*(1-i)+a[e]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new G;return G.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const n=V.Vector3[0],r=V.Quaternion[0],a=V.Vector3[1];e.decompose(n,r,a);const o=V.Vector3[2],l=V.Quaternion[1],h=V.Vector3[3];t.decompose(o,l,h);const c=V.Vector3[4];B.LerpToRef(n,o,i,c);const u=V.Quaternion[2];k.SlerpToRef(r,l,i,u);const d=V.Vector3[5];return B.LerpToRef(a,h,i,d),G.ComposeToRef(c,u,d,s),s}static LookAtLH(e,t,i){const s=new G;return G.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const n=V.Vector3[0],r=V.Vector3[1],a=V.Vector3[2];t.subtractToRef(e,a),a.normalize(),B.CrossToRef(i,a,n);const o=n.lengthSquared();0===o?n.x=1:n.normalizeFromLength(Math.sqrt(o)),B.CrossToRef(a,n,r),r.normalize();const l=-B.Dot(n,e),h=-B.Dot(r,e),c=-B.Dot(a,e);return G.FromValuesToRef(n._x,r._x,a._x,0,n._y,r._y,a._y,0,n._z,r._z,a._z,0,l,h,c,1,s),s}static LookAtRH(e,t,i){const s=new G;return G.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const n=V.Vector3[0],r=V.Vector3[1],a=V.Vector3[2];e.subtractToRef(t,a),a.normalize(),B.CrossToRef(i,a,n);const o=n.lengthSquared();0===o?n.x=1:n.normalizeFromLength(Math.sqrt(o)),B.CrossToRef(a,n,r),r.normalize();const l=-B.Dot(n,e),h=-B.Dot(r,e),c=-B.Dot(a,e);return G.FromValuesToRef(n._x,r._x,a._x,0,n._y,r._y,a._y,0,n._z,r._z,a._z,0,l,h,c,1,s),s}static LookDirectionLH(e,t){const i=new G;return G.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=V.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const n=V.Vector3[1];return B.CrossToRef(t,s,n),G.FromValuesToRef(n._x,n._y,n._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new G;return G.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=V.Vector3[2];return B.CrossToRef(t,e,s),G.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,s,n){const r=new G;return G.OrthoLHToRef(e,t,i,s,r,n),r}static OrthoLHToRef(e,t,i,s,n,r){const a=2/e,o=2/t,l=2/(s-i),h=-(s+i)/(s-i);return G.FromValuesToRef(a,0,0,0,0,o,0,0,0,0,l,0,0,0,h,1,n),r&&n.multiplyToRef(H,n),n._updateIdentityStatus(1===a&&1===o&&1===l&&0===h),n}static OrthoOffCenterLH(e,t,i,s,n,r,a){const o=new G;return G.OrthoOffCenterLHToRef(e,t,i,s,n,r,o,a),o}static OrthoOffCenterLHToRef(e,t,i,s,n,r,a,o){const l=2/(t-e),h=2/(s-i),c=2/(r-n),u=-(r+n)/(r-n),d=(e+t)/(e-t),_=(s+i)/(i-s);return G.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,0,d,_,u,1,a),o&&a.multiplyToRef(H,a),a.markAsUpdated(),a}static ObliqueOffCenterLHToRef(e,t,i,s,n,r,a,o,l,h,c){const u=-a*Math.cos(o),d=-a*Math.sin(o);return G.TranslationToRef(0,0,-l,V.Matrix[1]),G.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,V.Matrix[0]),V.Matrix[1].multiplyToRef(V.Matrix[0],V.Matrix[0]),G.TranslationToRef(0,0,l,V.Matrix[1]),V.Matrix[0].multiplyToRef(V.Matrix[1],V.Matrix[0]),G.OrthoOffCenterLHToRef(e,t,i,s,n,r,h,c),V.Matrix[0].multiplyToRef(h,h),h}static OrthoOffCenterRH(e,t,i,s,n,r,a){const o=new G;return G.OrthoOffCenterRHToRef(e,t,i,s,n,r,o,a),o}static OrthoOffCenterRHToRef(e,t,i,s,n,r,a,o){return G.OrthoOffCenterLHToRef(e,t,i,s,n,r,a,o),a._m[10]*=-1,a}static ObliqueOffCenterRHToRef(e,t,i,s,n,r,a,o,l,h,c){const u=a*Math.cos(o),d=a*Math.sin(o);return G.TranslationToRef(0,0,l,V.Matrix[1]),G.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,V.Matrix[0]),V.Matrix[1].multiplyToRef(V.Matrix[0],V.Matrix[0]),G.TranslationToRef(0,0,-l,V.Matrix[1]),V.Matrix[0].multiplyToRef(V.Matrix[1],V.Matrix[0]),G.OrthoOffCenterRHToRef(e,t,i,s,n,r,h,c),V.Matrix[0].multiplyToRef(h,h),h}static PerspectiveLH(e,t,i,s,n,r=0){const a=new G,o=2*i/e,l=2*i/t,h=(s+i)/(s-i),c=-2*s*i/(s-i),u=Math.tan(r);return G.FromValuesToRef(o,0,0,0,0,l,0,u,0,0,h,1,0,0,c,0,a),n&&a.multiplyToRef(H,a),a._updateIdentityStatus(!1),a}static PerspectiveFovLH(e,t,i,s,n,r=0,a=!1){const o=new G;return G.PerspectiveFovLHToRef(e,t,i,s,o,!0,n,r,a),o}static PerspectiveFovLHToRef(e,t,i,s,n,r=!0,a,o=0,l=!1){const h=i,c=s,u=1/Math.tan(.5*e),d=r?u/t:u,_=r?u:u*t,f=l&&0===h?-1:0!==c?(c+h)/(c-h):1,m=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,p=Math.tan(o);return G.FromValuesToRef(d,0,0,0,0,_,0,p,0,0,f,1,0,0,m,0,n),a&&n.multiplyToRef(H,n),n._updateIdentityStatus(!1),n}static PerspectiveFovReverseLHToRef(e,t,i,s,n,r=!0,a,o=0){const l=1/Math.tan(.5*e),h=r?l/t:l,c=r?l:l*t,u=Math.tan(o);return G.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,1,0,0,1,0,n),a&&n.multiplyToRef(H,n),n._updateIdentityStatus(!1),n}static PerspectiveFovRH(e,t,i,s,n,r=0,a=!1){const o=new G;return G.PerspectiveFovRHToRef(e,t,i,s,o,!0,n,r,a),o}static PerspectiveFovRHToRef(e,t,i,s,n,r=!0,a,o=0,l=!1){const h=i,c=s,u=1/Math.tan(.5*e),d=r?u/t:u,_=r?u:u*t,f=l&&0===h?1:0!==c?-(c+h)/(c-h):-1,m=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,p=Math.tan(o);return G.FromValuesToRef(d,0,0,0,0,_,0,p,0,0,f,-1,0,0,m,0,n),a&&n.multiplyToRef(H,n),n._updateIdentityStatus(!1),n}static PerspectiveFovReverseRHToRef(e,t,i,s,n,r=!0,a,o=0){const l=1/Math.tan(.5*e),h=r?l/t:l,c=r?l:l*t,u=Math.tan(o);return G.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,-1,0,0,-1,0,n),a&&n.multiplyToRef(H,n),n._updateIdentityStatus(!1),n}static GetFinalMatrix(e,t,i,s,n,r){const a=e.width,o=e.height,l=e.x,h=e.y,c=G.FromValues(a/2,0,0,0,0,-o/2,0,0,0,0,r-n,0,l+a/2,o/2+h,n,1),u=new G;return t.multiplyToRef(i,u),u.multiplyToRef(s,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return y.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){const t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return y.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new G;return G.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],n=i[4],r=i[8],a=i[12],o=i[1],l=i[5],h=i[9],c=i[13],u=i[2],d=i[6],_=i[10],f=i[14],m=i[3],p=i[7],g=i[11],E=i[15],T=t._m;return T[0]=s,T[1]=n,T[2]=r,T[3]=a,T[4]=o,T[5]=l,T[6]=h,T[7]=c,T[8]=u,T[9]=d,T[10]=_,T[11]=f,T[12]=m,T[13]=p,T[14]=g,T[15]=E,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new G;return G.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,n=e.normal.z,r=-2*i,a=-2*s,o=-2*n;return G.FromValuesToRef(r*i+1,a*i,o*i,0,r*s,a*s+1,o*s,0,r*n,a*n,o*n+1,0,r*e.d,a*e.d,o*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return G.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,s),s}static FromQuaternionToRef(e,t){const i=e._x*e._x,s=e._y*e._y,n=e._z*e._z,r=e._x*e._y,a=e._z*e._w,o=e._z*e._x,l=e._y*e._w,h=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(s+n),t._m[1]=2*(r+a),t._m[2]=2*(o-l),t._m[3]=0,t._m[4]=2*(r-a),t._m[5]=1-2*(n+i),t._m[6]=2*(h+c),t._m[7]=0,t._m[8]=2*(o+l),t._m[9]=2*(h-c),t._m[10]=1-2*(s+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}G._UpdateFlagSeed=0,G._IdentityReadOnly=G.Identity(),Object.defineProperties(G.prototype,{dimension:{value:[4,4]},rank:{value:2}});class V{}V.Vector3=R.BuildTuple(11,B.Zero),V.Matrix=R.BuildTuple(2,G.Identity),V.Quaternion=R.BuildTuple(3,k.Zero);class X{}X.Vector2=R.BuildTuple(3,w.Zero),X.Vector3=R.BuildTuple(13,B.Zero),X.Vector4=R.BuildTuple(3,U.Zero),X.Quaternion=R.BuildTuple(3,k.Zero),X.Matrix=R.BuildTuple(8,G.Identity),C("BABYLON.Vector2",w),C("BABYLON.Vector3",B),C("BABYLON.Vector4",U),C("BABYLON.Matrix",G);const H=G.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1),z={};function W(e,t=!1){if(!t||!z[e])return z[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}class Y{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),Y._HandleParenthesisContent(e,t)))):Y._HandleParenthesisContent(e,t))||"false"!==e&&Y.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const s=e.split("||");for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){let n=Y._SimplifyNegation(s[e].trim());const r=n.split("&&");if(r.length>1)for(let e=0;e<r.length;++e){const s=Y._SimplifyNegation(r[e].trim());if(i="true"!==s&&"false"!==s?"!"===s[0]?!t(s.substring(1)):t(s):"true"===s,!i){n="false";break}}if(i||"true"===n){i=!0;break}i="true"!==n&&"false"!==n?"!"===n[0]?!t(n.substring(1)):t(n):"true"===n}return i?"true":"false"}static _SimplifyNegation(e){return"!true"===(e=(e=e.replace(/^[\s!]+/,(e=>(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}class K{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>K.HasTags(e),e.addTags=t=>K.AddTagsTo(e,t),e.removeTags=t=>K.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>K.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 i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}return e._tags}static AddTagsTo(e,t){if(!t)return;if("string"!=typeof t)return;t.split(" ").forEach((function(t){K._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(K.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!K.HasTags(e))return;const i=t.split(" ");for(const t in i)K._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?K.HasTags(e):Y.Eval(t,(t=>K.HasTags(e)&&e._tags[t])))}}class q{static Sign(e){return 0===(e=+e)||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(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}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=q.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=q.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=q.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return s=Math.abs(t-e)<=i?t:e+q.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=q.DeltaAngle(e,t);let n=0;return-i<s&&s<i?n=t:(t=e+s,n=q.MoveTowards(e,t,i)),n}static LerpAngle(e,t,i){let s=q.Repeat(t-e,360);return s>180&&(s-=360),e+s*P(i)}static InverseLerp(e,t,i){let s=0;return s=e!=t?P((i-e)/(t-e)):0,s}static Hermite(e,t,i,s,n){const r=n*n,a=n*r;return e*(2*a-3*r+1)+i*(-2*a+3*r)+t*(a-2*r+n)+s*(a-r)}static Hermite1stDerivative(e,t,i,s,n){const r=n*n;return 6*(r-n)*e+(3*r-4*n+1)*t+6*(-r+n)*i+(3*r-2*n)*s}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static HCF(e,t){const i=e%t;return 0===i?t:q.HCF(t,i)}}function Q(e){return Math.pow(e,T)}function j(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function Z(e){return Math.pow(e,E)}function $(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}q.TwoPi=2*Math.PI,q.WithinEpsilon=x,q.ToHex=L,q.Clamp=P,q.Lerp=D,q.RandomRange=O,q.NormalizeRadians=N;class J{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}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 J.FromArrayToRef(e,t,this),this}toColor4(e=1){return new ee(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 J(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,i){return new J(this.r*e,this.g*t,this.b*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.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,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,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=A){return q.WithinEpsilon(this.r,e.r,t)&&q.WithinEpsilon(this.g,e.g,t)&&q.WithinEpsilon(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 J(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,i){return i.r=P(this.r,e,t),i.g=P(this.g,e,t),i.b=P(this.b,e,t),i}add(e){return new J(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,i){return this.r+=e,this.g+=t,this.b+=i,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 J(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,i){return new J(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s}clone(){return new J(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,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}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),i=Math.round(255*this.b);return"#"+L(e)+L(t)+L(i)}toHSV(){return this.toHSVToRef(new J)}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,n=Math.max(t,i,s),r=Math.min(t,i,s);let a=0,o=0;const l=n,h=n-r;return 0!==n&&(o=h/n),n!=r&&(n==t?(a=(i-s)/h,i<s&&(a+=6)):n==i?a=(s-t)/h+2:n==s&&(a=(t-i)/h+4),a*=60),e.r=a,e.g=o,e.b=l,e}toLinearSpace(e=!1){const t=new J;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=j(this.r),e.g=j(this.g),e.b=j(this.b)):(e.r=Q(this.r),e.g=Q(this.g),e.b=Q(this.b)),this}toGammaSpace(e=!1){const t=new J;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=$(this.r),e.g=$(this.g),e.b=$(this.b)):(e.r=Z(this.r),e.g=Z(this.g),e.b=Z(this.b)),this}static HSVtoRGBToRef(e,t,i,s){const n=i*t,r=e/60,a=n*(1-Math.abs(r%2-1));let o=0,l=0,h=0;r>=0&&r<=1?(o=n,l=a):r>=1&&r<=2?(o=a,l=n):r>=2&&r<=3?(l=n,h=a):r>=3&&r<=4?(l=a,h=n):r>=4&&r<=5?(o=a,h=n):r>=5&&r<=6&&(o=n,h=a);const c=i-n;return s.r=o+c,s.g=l+c,s.b=h+c,s}static FromHSV(e,t,i){const s=new J(0,0,0);return J.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new J(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16);return J.FromInts(t,i,s)}static FromArray(e,t=0){return new J(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new J(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new J(0,0,0);return J.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,s,n){const r=n*n,a=n*r,o=2*a-3*r+1,l=-2*a+3*r,h=a-2*r+n,c=a-r,u=e.r*o+i.r*l+t.r*h+s.r*c,d=e.g*o+i.g*l+t.g*h+s.g*c,_=e.b*o+i.b*l+t.b*h+s.b*c;return new J(u,d,_)}static Hermite1stDerivative(e,t,i,s,n){const r=J.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,n,r),r}static Hermite1stDerivativeToRef(e,t,i,s,n,r){const a=n*n;r.r=6*(a-n)*e.r+(3*a-4*n+1)*t.r+6*(-a+n)*i.r+(3*a-2*n)*s.r,r.g=6*(a-n)*e.g+(3*a-4*n+1)*t.g+6*(-a+n)*i.g+(3*a-2*n)*s.g,r.b=6*(a-n)*e.b+(3*a-4*n+1)*t.b+6*(-a+n)*i.b+(3*a-2*n)*s.b}static Red(){return new J(1,0,0)}static Green(){return new J(0,1,0)}static Blue(){return new J(0,0,1)}static Black(){return new J(0,0,0)}static get BlackReadOnly(){return J._BlackReadOnly}static White(){return new J(1,1,1)}static Purple(){return new J(.5,0,.5)}static Magenta(){return new J(1,0,1)}static Yellow(){return new J(1,1,0)}static Gray(){return new J(.5,.5,.5)}static Teal(){return new J(0,1,1)}static Random(){return new J(Math.random(),Math.random(),Math.random())}}J._BlackReadOnly=J.Black(),Object.defineProperties(J.prototype,{dimension:{value:[3]},rank:{value:1}});class ee{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}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 ee(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,i,s){return this.r+=e,this.g+=t,this.b+=i,this.a+=s,this}subtract(e){return new ee(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,i,s){return new ee(this.r-e,this.g-t,this.b-i,this.a-s)}subtractFromFloatsToRef(e,t,i,s,n){return n.r=this.r-e,n.g=this.g-t,n.b=this.b-i,n.a=this.a-s,n}scale(e){return new ee(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,i){return i.r=P(this.r,e,t),i.g=P(this.g,e,t),i.b=P(this.b,e,t),i.a=P(this.a,e,t),i}multiply(e){return new ee(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,i,s){return new ee(this.r*e,this.g*t,this.b*i,this.a*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.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,i,s){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(s,this.a),this}maximizeInPlaceFromFloats(e,t,i,s){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(s,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=A){return q.WithinEpsilon(this.r,e.r,t)&&q.WithinEpsilon(this.g,e.g,t)&&q.WithinEpsilon(this.b,e.b,t)&&q.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,i,s){return this.r===e&&this.g===t&&this.b===i&&this.a===s}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 ee).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,i,s){return this.r=e,this.g=t,this.b=i,this.a=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+L(t)+L(i)+L(s);const n=Math.round(255*this.a);return"#"+L(t)+L(i)+L(s)+L(n)}toLinearSpace(e=!1){const t=new ee;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=j(this.r),e.g=j(this.g),e.b=j(this.b)):(e.r=Q(this.r),e.g=Q(this.g),e.b=Q(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new ee;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=$(this.r),e.g=$(this.g),e.b=$(this.b)):(e.r=Z(this.r),e.g=Z(this.g),e.b=Z(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new ee(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16),n=9===e.length?parseInt(e.substring(7,9),16):255;return ee.FromInts(t,i,s,n)}static Lerp(e,t,i){return ee.LerpToRef(e,t,i,new ee)}static LerpToRef(e,t,i,s){return s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i,s.a=e.a+(t.a-e.a)*i,s}static Hermite(e,t,i,s,n){const r=n*n,a=n*r,o=2*a-3*r+1,l=-2*a+3*r,h=a-2*r+n,c=a-r,u=e.r*o+i.r*l+t.r*h+s.r*c,d=e.g*o+i.g*l+t.g*h+s.g*c,_=e.b*o+i.b*l+t.b*h+s.b*c,f=e.a*o+i.a*l+t.a*h+s.a*c;return new ee(u,d,_,f)}static Hermite1stDerivative(e,t,i,s,n){const r=new ee;return this.Hermite1stDerivativeToRef(e,t,i,s,n,r),r}static Hermite1stDerivativeToRef(e,t,i,s,n,r){const a=n*n;r.r=6*(a-n)*e.r+(3*a-4*n+1)*t.r+6*(-a+n)*i.r+(3*a-2*n)*s.r,r.g=6*(a-n)*e.g+(3*a-4*n+1)*t.g+6*(-a+n)*i.g+(3*a-2*n)*s.g,r.b=6*(a-n)*e.b+(3*a-4*n+1)*t.b+6*(-a+n)*i.b+(3*a-2*n)*s.b,r.a=6*(a-n)*e.a+(3*a-4*n+1)*t.a+6*(-a+n)*i.a+(3*a-2*n)*s.a}static FromColor3(e,t=1){return new ee(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new ee(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,s){return new ee(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;i<e.length;i+=3){const s=i/3*4;t[s]=e[i],t[s+1]=e[i+1],t[s+2]=e[i+2],t[s+3]=1}return t}return e}}Object.defineProperties(ee.prototype,{dimension:{value:[4]},rank:{value:1}});class te{}te.Color3=R.BuildArray(3,J.Black),te.Color4=R.BuildArray(3,(()=>new ee(0,0,0,0))),C("BABYLON.Color3",J),C("BABYLON.Color4",ee);const ie=function(e,t,i,n={}){const r=e();K&&K.HasTags(t)&&K.AddTagsTo(r,K.GetTags(t,!0));const a=s(r),o={};for(const e in a){const s=a[e],l=t[e],h=s.type;if(null!=l&&("uniqueId"!==e||se.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:r[e]=l;break;case 1:n.cloneTexturesOnlyOnce&&o[l.uniqueId]?r[e]=o[l.uniqueId]:(r[e]=i||l.isRenderTarget?l:l.clone(),o[l.uniqueId]=r[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[e]=i?l:l.clone()}}return r};class se{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i<e.animations.length;i++){const s=e.animations[i];t.animations.push(s.serialize())}}}static Serialize(e,t){t||(t={}),K&&(t.tags=K.GetTags(e));const i=s(e);for(const s in i){const n=i[s],r=n.sourceName||s,a=n.type,o=e[s];if(null!=o&&("uniqueId"!==s||se.AllowLoadingUniqueId))switch(a){case 0:t[r]=o;break;case 1:case 3:case 7:case 9:t[r]=o.serialize();break;case 2:case 4:case 5:case 8:case 10:case 12:t[r]=o.asArray();break;case 6:case 11:t[r]=o.id}}return t}static ParseProperties(e,t,i,n){n||(n="");const r=s(t);for(const s in r){const a=r[s],o=e[a.sourceName||s],l=a.type;if(null!=o&&("uniqueId"!==s||se.AllowLoadingUniqueId)){const e=t;switch(l){case 0:e[s]=o;break;case 1:i&&(e[s]=se._TextureParser(o,i,n));break;case 2:e[s]=J.FromArray(o);break;case 3:e[s]=se._FresnelParametersParser(o);break;case 4:e[s]=w.FromArray(o);break;case 5:e[s]=B.FromArray(o);break;case 6:i&&(e[s]=i.getLastMeshById(o));break;case 7:e[s]=se._ColorCurvesParser(o);break;case 8:e[s]=ee.FromArray(o);break;case 9:e[s]=se._ImageProcessingConfigurationParser(o);break;case 10:e[s]=k.FromArray(o);break;case 11:i&&(e[s]=i.getCameraById(o));break;case 12:e[s]=G.FromArray(o)}}}}static Parse(e,t,i,s=null){const n=e();return K&&K.AddTagsTo(n,t.tags),se.ParseProperties(t,n,i,s),n}static Clone(e,t,i={}){return ie(e,t,!1,i)}static Instanciate(e,t){return ie(e,t,!0)}}se.AllowLoadingUniqueId=!1,se._ImageProcessingConfigurationParser=e=>{throw W("ImageProcessingConfiguration")},se._FresnelParametersParser=e=>{throw W("FresnelParameters")},se._ColorCurvesParser=e=>{throw W("ColorCurves")},se._TextureParser=(e,t,i)=>{throw W("Texture")};class ne{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new g,this._onClonedObservable=new g}}class re{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,s){const n=this._NodeConstructors[e];return n?n(t,i,s):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}_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 onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,i=!0){this._isDirty=!1,this._nodeDataStorage=new ne,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new g,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=G.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new g,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||M.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&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((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),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}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),this._children&&this._children.forEach((e=>{e._syncParentEnabledState()}))}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))}_getDescendants(e,t=!1,i){if(this._children)for(let s=0;s<this._children.length;s++){const n=this._children[s];i&&!i(n)||e.push(n),t||n._getDescendants(e,!1,i)}}getDescendants(e,t){const i=[];return this._getDescendants(i,e,t),i}getChildMeshes(e,t){const i=[];return this._getDescendants(i,e,(e=>(!t||t(e))&&void 0!==e.cullingStrategy)),i}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 i=this.animations[t];if(i.name===e)return i}return null}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=re._AnimationRangeFactory(e,t,i);for(let s=0,n=this.animations.length;s<n;s++)this.animations[s]&&this.animations[s].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,s=this.animations.length;i<s;i++)this.animations[i]&&this.animations[i].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}clone(e,t,i){const s=se.Clone((()=>new re(e,this.getScene())),this);if(t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i<t.length;i++){const n=t[i];n.clone(e+"."+n.name,s)}}return s}getAnimationRanges(){const e=[];let t;for(t in this._ranges)e.push(this._ranges[t]);return e}beginAnimation(e,t,i,s){const n=this.getAnimationRange(e);return n?this._scene.beginAnimation(this,n.from,n.to,t,i,s):null}serializeAnimationRanges(){const e=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const s={};s.name=t,s.from=i.from,s.to=i.to,e.push(s)}return e}computeWorldMatrix(e){return this._worldMatrix||(this._worldMatrix=G.Identity()),this._worldMatrix}dispose(e,t=!1){if(this._nodeDataStorage._isDisposed=!0,!e){const i=this.getDescendants(!0);for(const s of i)s.dispose(e,t)}this.parent?this.parent=null:this._removeFromSceneRootNodes(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onEnabledStateChangedObservable.clear(),this.onClonedObservable.clear();for(const e of this._behaviors)e.detach();this._behaviors.length=0,this.metadata=null}static ParseAnimationRanges(e,t,i){if(t.ranges)for(let i=0;i<t.ranges.length;i++){const s=t.ranges[i];e.createAnimationRange(s.name,s.from,s.to)}}getHierarchyBoundingVectors(e=!0,t=null){let i,s;this.getScene().incrementRenderId(),this.computeWorldMatrix(!0);const n=this;if(n.getBoundingInfo&&n.subMeshes){const e=n.getBoundingInfo();i=e.boundingBox.minimumWorld.clone(),s=e.boundingBox.maximumWorld.clone()}else i=new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new B(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(e){const e=this.getDescendants(!1);for(const n of e){const e=n;if(e.computeWorldMatrix(!0),t&&!t(e))continue;if(!e.getBoundingInfo||0===e.getTotalVertices())continue;const r=e.getBoundingInfo().boundingBox,a=r.minimumWorld,o=r.maximumWorld;B.CheckExtends(a,i,s),B.CheckExtends(o,i,s)}}return{min:i,max:s}}}function ae(){return"undefined"!=typeof window}function oe(){return"undefined"!=typeof navigator}function le(){return"undefined"!=typeof document}function he(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}re._AnimationRangeFactory=(e,t,i)=>{throw W("AnimationRange")},re._NodeConstructors={},e([a()],re.prototype,"name",void 0),e([a()],re.prototype,"id",void 0),e([a()],re.prototype,"uniqueId",void 0),e([a()],re.prototype,"state",void 0),e([a()],re.prototype,"metadata",void 0);class ce{static _CheckLimit(e,t){let i=ce._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},ce._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){const i=ce._LogLimitOutputs[e];if(!i||!ce.MessageLimitReached)return;const s=this._Levels[t];i.current===i.limit&&ce[s.name](ce.MessageLimitReached.replace(/%LIMIT%/g,""+i.limit).replace(/%TYPE%/g,s.name??""))}static _AddLogEntry(e){ce._LogCache=e+ce._LogCache,ce.OnNewCacheEntry&&ce.OnNewCacheEntry(e)}static _FormatMessage(e){const t=e=>e<10?"0"+e:""+e,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){const s=Array.isArray(t)?t[0]:t;if(void 0!==i&&!ce._CheckLimit(s,i))return;const n=ce._FormatMessage(s),r=this._Levels[e],a=Array.isArray(t)?t.slice(1):[];r.logFunc&&r.logFunc("BJS - "+n,...a);const o=`<div style='color:${r.color}'>${n}</div><br>`;ce._AddLogEntry(o),ce._GenerateLimitMessage(s,e)}static get LogCache(){return ce._LogCache}static ClearLogCache(){ce._LogCache="",ce._LogLimitOutputs={},ce.errorsCount=0}static set LogLevels(e){ce.Log=ce._LogDisabled,ce.Warn=ce._LogDisabled,ce.Error=ce._LogDisabled,[ce.MessageLogLevel,ce.WarningLogLevel,ce.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];ce[e.name]=ce._LogEnabled.bind(ce,t)}}))}}ce.NoneLogLevel=0,ce.MessageLogLevel=1,ce.WarningLogLevel=2,ce.ErrorLogLevel=4,ce.AllLogLevel=7,ce.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",ce._LogCache="",ce._LogLimitOutputs={},ce._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],ce.errorsCount=0,ce.Log=ce._LogEnabled.bind(ce,ce.MessageLogLevel),ce.Warn=ce._LogEnabled.bind(ce,ce.WarningLogLevel),ce.Error=ce._LogEnabled.bind(ce,ce.ErrorLogLevel);const ue=(e,t,i)=>e?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?{...e}:null:e.clone(t):null;class de{static DeepCopy(e,t,i,s,n=!1){const r=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const a of r){if("_"===a[0]&&(!s||-1===s.indexOf(a)))continue;if(a.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(a))continue;const r=e[a],o=typeof r;if("function"!==o)try{if("object"===o)if(r instanceof Uint8Array)t[a]=Uint8Array.from(r);else if(r instanceof Array){if(t[a]=[],r.length>0)if("object"==typeof r[0])for(let e=0;e<r.length;e++){const i=ue(r[e],t,n);-1===t[a].indexOf(i)&&t[a].push(i)}else t[a]=r.slice(0)}else t[a]=ue(r,t,n);else t[a]=r}catch(e){ce.Warn(e.message)}}}}class _e{static get Now(){return ae()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class fe{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(fe.CustomRequestHeaders).length>0||fe.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in fe.CustomRequestHeaders){const t=fe.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return fe.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}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,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){fe.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const e of fe.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}t=(t=t.replace("file:http:","http:")).replace("file:https:","https:"),this._requestURL=t,this._xhr.open(e,t,!0)}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}fe.CustomRequestHeaders={},fe.CustomRequestModifiers=new Array,fe.SkipRequestModificationForBabylonCDN=!0;class me{}me.FilesToLoad={};class pe extends Error{}pe._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const ge=0,Ee=2e3,Te=3e3,Ae=4e3,Re=4001,ve=4002;class Ie extends pe{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",pe._setPrototypeOf(this,Ie.prototype)}}const Se=e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,s,n,r,a,o,l,h="",c=0;const u=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c<u.length;)i=u[c++],s=c<u.length?u[c++]:Number.NaN,n=c<u.length?u[c++]:Number.NaN,r=i>>2,a=(3&i)<<4|s>>4,o=(15&s)<<2|n>>6,l=63&n,isNaN(s)?o=l=64:isNaN(n)&&(l=64),h+=t.charAt(r)+t.charAt(a)+t.charAt(o)+t.charAt(l);return h},Ce=e=>atob(e);class be{constructor(){this.children=[]}isValid(e){return!0}process(e,t){let i="";if(this.line){let s=this.line;const n=t.processor;if(n){n.lineProcessor&&(s=n.lineProcessor(s,t.isFragment,t.processingContext));const i=t.processor?.attributeKeywordName??"attribute",r=t.isFragment&&t.processor?.varyingFragmentKeywordName?t.processor?.varyingFragmentKeywordName:!t.isFragment&&t.processor?.varyingVertexKeywordName?t.processor?.varyingVertexKeywordName:"varying";if(!t.isFragment&&n.attributeProcessor&&this.line.startsWith(i))s=n.attributeProcessor(this.line,e,t.processingContext);else if(n.varyingProcessor&&(n.varyingCheck?.(this.line,t.isFragment)||!n.varyingCheck&&this.line.startsWith(r)))s=n.varyingProcessor(this.line,t.isFragment,e,t.processingContext);else if(n.uniformProcessor&&n.uniformRegexp&&n.uniformRegexp.test(this.line))t.lookForClosingBracketForUniformBuffer||(s=n.uniformProcessor(this.line,t.isFragment,e,t.processingContext));else if(n.uniformBufferProcessor&&n.uniformBufferRegexp&&n.uniformBufferRegexp.test(this.line))t.lookForClosingBracketForUniformBuffer||(s=n.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0);else if(n.textureProcessor&&n.textureRegexp&&n.textureRegexp.test(this.line))s=n.textureProcessor(this.line,t.isFragment,e,t.processingContext);else if((n.uniformProcessor||n.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer){/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?n.uniformProcessor&&(s=n.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):n.uniformBufferProcessor&&(s=n.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)}t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,n.endOfUniformBufferProcessor&&(s=n.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}i+=s+"\n"}return this.children.forEach((s=>{i+=s.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class ye{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 i=e.indexOf(";");if(-1===i)this._lines.push(e);else if(i===e.length-1)e.length>1&&this._lines.push(e);else{const e=t.split(";");for(let t=0;t<e.length;t++){let i=e[t];i&&(i=i.trim(),i&&this._lines.push(i+(t!==e.length-1?";":"")))}}}}}class Me extends be{process(e,t){for(let i=0;i<this.children.length;i++){const s=this.children[i];if(s.isValid(e))return s.process(e,t)}return""}}class xe extends be{isValid(e){return this.testExpression.isTrue(e)}}class Oe{isTrue(e){return!0}static postfixToInfix(e){const t=[];for(const i of e)if(void 0===Oe._OperatorPriority[i])t.push(i);else{const e=t[t.length-1],s=t[t.length-2];t.length-=2,t.push(`(${s}${i}${e})`)}return t[t.length-1]}static infixToPostfix(e){const t=Oe._InfixToPostfixCache.get(e);if(t)return t.accessTime=Date.now(),t.result;if(!(e.includes("&&")||e.includes("||")||e.includes(")")||e.includes("(")))return[e];const i=[];let s=-1;const n=()=>{h=h.trim(),""!==h&&(i.push(h),h="")},r=e=>{s<Oe._Stack.length-1&&(Oe._Stack[++s]=e)},a=()=>Oe._Stack[s],o=()=>-1===s?"!!INVALID EXPRESSION!!":Oe._Stack[s--];let l=0,h="";for(;l<e.length;){const t=e.charAt(l),c=l<e.length-1?e.substr(l,2):"";if("("===t)h="",r(t);else if(")"===t){for(n();-1!==s&&"("!==a();)i.push(o());o()}else if(Oe._OperatorPriority[c]>1){for(n();-1!==s&&Oe._OperatorPriority[a()]>=Oe._OperatorPriority[c];)i.push(o());r(c),l++}else h+=t;l++}for(n();-1!==s;)"("===a()?o():i.push(o());return Oe._InfixToPostfixCache.size>=Oe.InfixToPostfixCacheLimitSize&&Oe.ClearCache(),Oe._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(Oe._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t<Oe.InfixToPostfixCacheCleanupSize;t++)Oe._InfixToPostfixCache.delete(e[t][0])}}Oe.InfixToPostfixCacheLimitSize=5e4,Oe.InfixToPostfixCacheCleanupSize=25e3,Oe._InfixToPostfixCache=new Map,Oe._OperatorPriority={")":0,"(":1,"||":2,"&&":3},Oe._Stack=["","","","","","","","","","","","","","","","","","","",""];class De extends Oe{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 Pe extends Oe{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}}class Ne extends Oe{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}}class Le extends Oe{constructor(e,t,i){super(),this.define=e,this.operand=t,this.testValue=i}isTrue(e){let t=e[this.define];void 0===t&&(t=this.define);let i=!1;const s=parseInt(t),n=parseInt(this.testValue);switch(this.operand){case">":i=s>n;break;case"<":i=s<n;break;case"<=":i=s<=n;break;case">=":i=s>=n;break;case"==":i=s===n;break;case"!=":i=s!==n}return i}}const Fe={};function we(e,t,i=""){return i+(t?t+"\n":"")+e}function Be(e,t,i,s,n,r,a){const o=a||Fe.loadFile;if(o){return o(e,t,i,s,n,r)}throw W("FileTools")}function Ue(e,t,i,s){if(e)return t?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,i?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(s?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return t&&(e+="#define IS_NDC_HALF_ZRANGE"),i&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),s&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}const ke=/defined\s*?\((.+?)\)/g,Ge=/defined\s*?\[(.+?)\]/g,Ve=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,Xe=/__decl__/,He=/light\{X\}.(\w*)/g,ze=/\{X\}/g,We=[],Ye=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function Ke(e,t,i,s){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),$e(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e,t.defines));const n=function(e,t,i){let s=function(e,t){if(t.processor?.noPrecision)return e;const i=t.shouldUseHighPrecisionShader;-1===e.indexOf("precision highp float")?e=i?"precision highp float;\n"+e:"precision mediump float;\n"+e:i||(e=e.replace("precision highp float","precision mediump float"));return e}(e,t);if(!t.processor)return s;if(0===t.processor.shaderLanguage&&-1!==s.indexOf("#version 3")&&(s=s.replace("#version 300 es",""),!t.processor.parseGLES3))return s;const n=t.defines,r=function(e,t){const i=e.defines,s={};for(const e of i){const t=e.replace("#define","").replace(";","").trim().split(" ");s[t[0]]=t.length>1?t[1]:""}0===e.processor?.shaderLanguage&&(s.GL_ES="true");return s.__VERSION__=e.version,s[e.platformName]="true",Ue(s,t?.isNDCHalfZRange,t?.useReverseDepthBuffer,t?.useExactSrgbConversions),s}(t,i);t.processor.preProcessor&&(s=t.processor.preProcessor(s,n,r,t.isFragment,t.processingContext));s=function(e,t,i){const s=new be,n=new ye;return n.lineIndex=-1,n.lines=e.split("\n"),Ze(n,s),s.process(t,i)}(s,r,t),t.processor.postProcessor&&(s=t.processor.postProcessor(s,n,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{}));i?._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s));return s}(e,t,s);i(n,e)}))}function qe(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new De(t[1].trim(),"!"===e[0]);const i=["==","!=",">=","<=","<",">"];let s="",n=0;for(s of i)if(n=e.indexOf(s),n>-1)break;if(-1===n)return new De(e);const r=e.substring(0,n).trim(),a=e.substring(n+s.length).trim();return new Le(r,s,a)}function Qe(e,t){const i=new xe,s=e.substring(0,t);let n=e.substring(t);return n=n.substring(0,(n.indexOf("//")+1||n.length+1)-1).trim(),i.testExpression="#ifdef"===s?new De(n):"#ifndef"===s?new De(n,!0):function(e){e=e.replace(ke,"defined[$1]");const t=Oe.infixToPostfix(e),i=[];for(const e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],s=i[i.length-2];i.length-=2;const n="&&"==e?new Ne:new Pe;"string"==typeof t&&(t=t.replace(Ge,"defined($1)")),"string"==typeof s&&(s=s.replace(Ge,"defined($1)")),n.leftOperand="string"==typeof s?qe(s):s,n.rightOperand="string"==typeof t?qe(t):t,i.push(n)}let s=i[i.length-1];return"string"==typeof s&&(s=s.replace(Ge,"defined($1)")),"string"==typeof s?qe(s):s}(n),i}function je(e,t,i){let s=e.currentLine;for(;Ze(e,i);){s=e.currentLine;const n=s.substring(0,5).toLowerCase();if("#else"===n){const i=new be;return t.children.push(i),void Ze(e,i)}if("#elif"===n){const e=Qe(s,5);t.children.push(e),i=e}}}function Ze(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const s=Ye.exec(i);if(s&&s.length){switch(s[0]){case"#ifdef":{const s=new Me;t.children.push(s);const n=Qe(i,6);s.children.push(n),je(e,s,n);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const s=new Me;t.children.push(s);const n=Qe(i,7);s.children.push(n),je(e,s,n);break}case"#if":{const s=new Me,n=Qe(i,3);t.children.push(s),s.children.push(n),je(e,s,n);break}}continue}}const s=new be;if(s.line=i,t.children.push(s),"#"===i[0]&&"d"===i[1]){const e=i.replace(";","").split(" ");s.additionalDefineKey=e[1],3===e.length&&(s.additionalDefineValue=e[2])}}return!1}function $e(e,t,i){let s;for(We.length=0;null!==(s=Ve.exec(e));)We.push(s);let n=String(e),r=[e],a=!1;for(const e of We){let s=e[1];if(-1!==s.indexOf("__decl__")&&(s=s.replace(Xe,""),t.supportsUniformBuffers&&(s=s.replace("Vertex","Ubo").replace("Fragment","Ubo")),s+="Declaration"),!t.includesShadersStore[s]){const e=t.shadersRepository+"ShadersInclude/"+s+".fx";return void Je.loadFile(e,(e=>{t.includesShadersStore[s]=e,$e(r.join(""),t,i)}))}{let i=t.includesShadersStore[s];if(e[2]){const t=e[3].split(",");for(let e=0;e<t.length;e+=2){const s=new RegExp(t[e],"g"),n=t[e+1];i=i.replace(s,n)}}if(e[4]){const s=e[5];if(-1!==s.indexOf("..")){const e=s.split(".."),n=parseInt(e[0]);let r=parseInt(e[1]),a=i.slice(0);i="",isNaN(r)&&(r=t.indexParameters[e[1]]);for(let e=n;e<r;e++)t.supportsUniformBuffers||(a=a.replace(He,((e,t)=>t+"{X}"))),i+=a.replace(ze,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(He,((e,t)=>t+"{X}"))),i=i.replace(ze,s)}const n=[];for(const t of r){const s=t.split(e[0]);for(let e=0;e<s.length-1;e++)n.push(s[e]),n.push(i);n.push(s[s.length-1])}r=n,a=a||i.indexOf("#include<")>=0||i.indexOf("#include <")>=0}}We.length=0,n=r.join(""),a?$e(n.toString(),t,i):i(n)}const Je={loadFile:(e,t,i,s,n,r)=>{throw W("FileTools")}};class et{static SetImmediate(e){ae()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}class tt{}tt.AUTOSAMPLERSUFFIX="Sampler",tt.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS",tt.ALPHA_DISABLE=0,tt.ALPHA_ADD=1,tt.ALPHA_COMBINE=2,tt.ALPHA_SUBTRACT=3,tt.ALPHA_MULTIPLY=4,tt.ALPHA_MAXIMIZED=5,tt.ALPHA_ONEONE=6,tt.ALPHA_PREMULTIPLIED=7,tt.ALPHA_PREMULTIPLIED_PORTERDUFF=8,tt.ALPHA_INTERPOLATE=9,tt.ALPHA_SCREENMODE=10,tt.ALPHA_ONEONE_ONEONE=11,tt.ALPHA_ALPHATOCOLOR=12,tt.ALPHA_REVERSEONEMINUS=13,tt.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,tt.ALPHA_ONEONE_ONEZERO=15,tt.ALPHA_EXCLUSION=16,tt.ALPHA_LAYER_ACCUMULATE=17,tt.ALPHA_EQUATION_ADD=0,tt.ALPHA_EQUATION_SUBSTRACT=1,tt.ALPHA_EQUATION_REVERSE_SUBTRACT=2,tt.ALPHA_EQUATION_MAX=3,tt.ALPHA_EQUATION_MIN=4,tt.ALPHA_EQUATION_DARKEN=5,tt.DELAYLOADSTATE_NONE=0,tt.DELAYLOADSTATE_LOADED=1,tt.DELAYLOADSTATE_LOADING=2,tt.DELAYLOADSTATE_NOTLOADED=4,tt.NEVER=512,tt.ALWAYS=519,tt.LESS=513,tt.EQUAL=514,tt.LEQUAL=515,tt.GREATER=516,tt.GEQUAL=518,tt.NOTEQUAL=517,tt.KEEP=7680,tt.ZERO=0,tt.REPLACE=7681,tt.INCR=7682,tt.DECR=7683,tt.INVERT=5386,tt.INCR_WRAP=34055,tt.DECR_WRAP=34056,tt.TEXTURE_CLAMP_ADDRESSMODE=0,tt.TEXTURE_WRAP_ADDRESSMODE=1,tt.TEXTURE_MIRROR_ADDRESSMODE=2,tt.TEXTURE_CREATIONFLAG_STORAGE=1,tt.TEXTUREFORMAT_ALPHA=0,tt.TEXTUREFORMAT_LUMINANCE=1,tt.TEXTUREFORMAT_LUMINANCE_ALPHA=2,tt.TEXTUREFORMAT_RGB=4,tt.TEXTUREFORMAT_RGBA=5,tt.TEXTUREFORMAT_RED=6,tt.TEXTUREFORMAT_R=6,tt.TEXTUREFORMAT_RG=7,tt.TEXTUREFORMAT_RED_INTEGER=8,tt.TEXTUREFORMAT_R_INTEGER=8,tt.TEXTUREFORMAT_RG_INTEGER=9,tt.TEXTUREFORMAT_RGB_INTEGER=10,tt.TEXTUREFORMAT_RGBA_INTEGER=11,tt.TEXTUREFORMAT_BGRA=12,tt.TEXTUREFORMAT_DEPTH24_STENCIL8=13,tt.TEXTUREFORMAT_DEPTH32_FLOAT=14,tt.TEXTUREFORMAT_DEPTH16=15,tt.TEXTUREFORMAT_DEPTH24=16,tt.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,tt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,tt.TEXTUREFORMAT_STENCIL8=19,tt.TEXTUREFORMAT_UNDEFINED=4294967295,tt.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,tt.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,tt.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,tt.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,tt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,tt.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,tt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,tt.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,tt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,tt.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,tt.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,tt.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,tt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,tt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,tt.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,tt.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,tt.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,tt.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,tt.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,tt.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,tt.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,tt.TEXTURETYPE_UNSIGNED_BYTE=0,tt.TEXTURETYPE_UNSIGNED_INT=0,tt.TEXTURETYPE_FLOAT=1,tt.TEXTURETYPE_HALF_FLOAT=2,tt.TEXTURETYPE_BYTE=3,tt.TEXTURETYPE_SHORT=4,tt.TEXTURETYPE_UNSIGNED_SHORT=5,tt.TEXTURETYPE_INT=6,tt.TEXTURETYPE_UNSIGNED_INTEGER=7,tt.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,tt.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,tt.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,tt.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,tt.TEXTURETYPE_UNSIGNED_INT_24_8=12,tt.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,tt.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,tt.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,tt.TEXTURETYPE_UNDEFINED=16,tt.TEXTURE_2D=3553,tt.TEXTURE_2D_ARRAY=35866,tt.TEXTURE_CUBE_MAP=34067,tt.TEXTURE_CUBE_MAP_ARRAY=3735928559,tt.TEXTURE_3D=32879,tt.TEXTURE_NEAREST_SAMPLINGMODE=1,tt.TEXTURE_NEAREST_NEAREST=1,tt.TEXTURE_BILINEAR_SAMPLINGMODE=2,tt.TEXTURE_LINEAR_LINEAR=2,tt.TEXTURE_TRILINEAR_SAMPLINGMODE=3,tt.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,tt.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,tt.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,tt.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,tt.TEXTURE_NEAREST_LINEAR=7,tt.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,tt.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,tt.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,tt.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,tt.TEXTURE_LINEAR_NEAREST=12,tt.TEXTURE_EXPLICIT_MODE=0,tt.TEXTURE_SPHERICAL_MODE=1,tt.TEXTURE_PLANAR_MODE=2,tt.TEXTURE_CUBIC_MODE=3,tt.TEXTURE_PROJECTION_MODE=4,tt.TEXTURE_SKYBOX_MODE=5,tt.TEXTURE_INVCUBIC_MODE=6,tt.TEXTURE_EQUIRECTANGULAR_MODE=7,tt.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,tt.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,tt.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,tt.TEXTURE_FILTERING_QUALITY_HIGH=64,tt.TEXTURE_FILTERING_QUALITY_MEDIUM=16,tt.TEXTURE_FILTERING_QUALITY_LOW=8,tt.SCALEMODE_FLOOR=1,tt.SCALEMODE_NEAREST=2,tt.SCALEMODE_CEILING=3,tt.MATERIAL_TextureDirtyFlag=1,tt.MATERIAL_LightDirtyFlag=2,tt.MATERIAL_FresnelDirtyFlag=4,tt.MATERIAL_AttributesDirtyFlag=8,tt.MATERIAL_MiscDirtyFlag=16,tt.MATERIAL_PrePassDirtyFlag=32,tt.MATERIAL_AllDirtyFlag=63,tt.MATERIAL_TriangleFillMode=0,tt.MATERIAL_WireFrameFillMode=1,tt.MATERIAL_PointFillMode=2,tt.MATERIAL_PointListDrawMode=3,tt.MATERIAL_LineListDrawMode=4,tt.MATERIAL_LineLoopDrawMode=5,tt.MATERIAL_LineStripDrawMode=6,tt.MATERIAL_TriangleStripDrawMode=7,tt.MATERIAL_TriangleFanDrawMode=8,tt.MATERIAL_ClockWiseSideOrientation=0,tt.MATERIAL_CounterClockWiseSideOrientation=1,tt.ACTION_NothingTrigger=0,tt.ACTION_OnPickTrigger=1,tt.ACTION_OnLeftPickTrigger=2,tt.ACTION_OnRightPickTrigger=3,tt.ACTION_OnCenterPickTrigger=4,tt.ACTION_OnPickDownTrigger=5,tt.ACTION_OnDoublePickTrigger=6,tt.ACTION_OnPickUpTrigger=7,tt.ACTION_OnPickOutTrigger=16,tt.ACTION_OnLongPressTrigger=8,tt.ACTION_OnPointerOverTrigger=9,tt.ACTION_OnPointerOutTrigger=10,tt.ACTION_OnEveryFrameTrigger=11,tt.ACTION_OnIntersectionEnterTrigger=12,tt.ACTION_OnIntersectionExitTrigger=13,tt.ACTION_OnKeyDownTrigger=14,tt.ACTION_OnKeyUpTrigger=15,tt.PARTICLES_BILLBOARDMODE_Y=2,tt.PARTICLES_BILLBOARDMODE_ALL=7,tt.PARTICLES_BILLBOARDMODE_STRETCHED=8,tt.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,tt.MESHES_CULLINGSTRATEGY_STANDARD=0,tt.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,tt.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,tt.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,tt.SCENELOADER_NO_LOGGING=0,tt.SCENELOADER_MINIMAL_LOGGING=1,tt.SCENELOADER_SUMMARY_LOGGING=2,tt.SCENELOADER_DETAILED_LOGGING=3,tt.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,tt.PREPASS_POSITION_TEXTURE_TYPE=1,tt.PREPASS_VELOCITY_TEXTURE_TYPE=2,tt.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,tt.PREPASS_COLOR_TEXTURE_TYPE=4,tt.PREPASS_DEPTH_TEXTURE_TYPE=5,tt.PREPASS_NORMAL_TEXTURE_TYPE=6,tt.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,tt.BUFFER_CREATIONFLAG_READ=1,tt.BUFFER_CREATIONFLAG_WRITE=2,tt.BUFFER_CREATIONFLAG_READWRITE=3,tt.BUFFER_CREATIONFLAG_UNIFORM=4,tt.BUFFER_CREATIONFLAG_VERTEX=8,tt.BUFFER_CREATIONFLAG_INDEX=16,tt.BUFFER_CREATIONFLAG_STORAGE=32,tt.BUFFER_CREATIONFLAG_INDIRECT=64,tt.RENDERPASS_MAIN=0,tt.INPUT_ALT_KEY=18,tt.INPUT_CTRL_KEY=17,tt.INPUT_META_KEY1=91,tt.INPUT_META_KEY2=92,tt.INPUT_META_KEY3=93,tt.INPUT_SHIFT_KEY=16,tt.SNAPSHOTRENDERING_STANDARD=0,tt.SNAPSHOTRENDERING_FAST=1,tt.PERSPECTIVE_CAMERA=0,tt.ORTHOGRAPHIC_CAMERA=1,tt.FOVMODE_VERTICAL_FIXED=0,tt.FOVMODE_HORIZONTAL_FIXED=1,tt.RIG_MODE_NONE=0,tt.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,tt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,tt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,tt.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,tt.RIG_MODE_STEREOSCOPIC_INTERLACED=14,tt.RIG_MODE_VR=20,tt.RIG_MODE_CUSTOM=22,tt.MAX_SUPPORTED_UV_SETS=6,tt.GL_ALPHA_EQUATION_ADD=32774,tt.GL_ALPHA_EQUATION_MIN=32775,tt.GL_ALPHA_EQUATION_MAX=32776,tt.GL_ALPHA_EQUATION_SUBTRACT=32778,tt.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,tt.GL_ALPHA_FUNCTION_SRC=768,tt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,tt.GL_ALPHA_FUNCTION_SRC_ALPHA=770,tt.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,tt.GL_ALPHA_FUNCTION_DST_ALPHA=772,tt.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,tt.GL_ALPHA_FUNCTION_DST_COLOR=774,tt.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,tt.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,tt.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,tt.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,tt.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,tt.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,tt.SnippetUrl="https://snippet.babylonjs.com",tt.FOGMODE_NONE=0,tt.FOGMODE_EXP=1,tt.FOGMODE_EXP2=2,tt.FOGMODE_LINEAR=3,tt.BYTE=5120,tt.UNSIGNED_BYTE=5121,tt.SHORT=5122,tt.UNSIGNED_SHORT=5123,tt.INT=5124,tt.UNSIGNED_INT=5125,tt.FLOAT=5126,tt.PositionKind="position",tt.NormalKind="normal",tt.TangentKind="tangent",tt.UVKind="uv",tt.UV2Kind="uv2",tt.UV3Kind="uv3",tt.UV4Kind="uv4",tt.UV5Kind="uv5",tt.UV6Kind="uv6",tt.ColorKind="color",tt.ColorInstanceKind="instanceColor",tt.MatricesIndicesKind="matricesIndices",tt.MatricesWeightsKind="matricesWeights",tt.MatricesIndicesExtraKind="matricesIndicesExtra",tt.MatricesWeightsExtraKind="matricesWeightsExtra";class it{static GetShadersRepository(e=0){return 0===e?it.ShadersRepository:it.ShadersRepositoryWGSL}static GetShadersStore(e=0){return 0===e?it.ShadersStore:it.ShadersStoreWGSL}static GetIncludesShadersStore(e=0){return 0===e?it.IncludesShadersStore:it.IncludesShadersStoreWGSL}}it.ShadersRepository="src/Shaders/",it.ShadersStore={},it.IncludesShadersStore={},it.ShadersRepositoryWGSL="src/ShadersWGSL/",it.ShadersStoreWGSL={},it.IncludesShadersStoreWGSL={};class st{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,i,s,n,r,a,o){const l=this.engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,h=0;h<n.length;h++){null==e.getUniform(n[h])&&(n.splice(h,1),h--)}n.forEach(((e,t)=>{r[e]=t}));for(const e of l.getAttributes(this,a))o.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||2!==s.length)return s=[t,i],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),n}_cacheFloat3(e,t,i,s){let n=this._valueCache[e];if(!n||3!==n.length)return n=[t,i,s],this._valueCache[e]=n,!0;let r=!1;return n[0]!==t&&(n[0]=t,r=!0),n[1]!==i&&(n[1]=i,r=!0),n[2]!==s&&(n[2]=s,r=!0),r}_cacheFloat4(e,t,i,s,n){let r=this._valueCache[e];if(!r||4!==r.length)return r=[t,i,s,n],this._valueCache[e]=r,!0;let a=!1;return r[0]!==t&&(r[0]=t,a=!0),r[1]!==i&&(r[1]=i,a=!0),r[2]!==s&&(r[2]=s,a=!0),r[3]!==n&&(r[3]=n,a=!0),a}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,n){this._cacheFloat4(e,t,i,s,n)&&(this.engine.setInt4(this._uniforms[e],t,i,s,n)||(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 i=this._valueCache[e];void 0!==i&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,n){this._cacheFloat4(e,t,i,s,n)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,n)||(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 i=this._valueCache[e];void 0!==i&&i===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,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(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,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setFloat3(this._uniforms[e],t,i,s)||(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,i,s,n){this._cacheFloat4(e,t,i,s,n)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,n)||(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,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(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 nt=new WeakMap,rt={_webGLVersion:2,cachedPipelines:{}};function at(e){let t=nt.get(e);if(!t){if(!e)return rt;t={_webGLVersion:e.TEXTURE_BINDING_3D?2:1,_context:e,cachedPipelines:{}},nt.set(e,t)}return t}function ot(e,t,i,s,n,r){const a=at(s);r||(r=a._createShaderProgramInjection??ht);return r(e,dt(t,"vertex",s,a._contextWasLost),dt(i,"fragment",s,a._contextWasLost),s,n,a.validateShaderPrograms)}function lt(e,t,i,s,n,r=null,a){const o=at(n);a||(a=o._createShaderProgramInjection??ht);const l=o._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"";return a(e,ut(t,"vertex",s,l,n,o._contextWasLost),ut(i,"fragment",s,l,n,o._contextWasLost),n,r,o.validateShaderPrograms)}function ht(e,t,i,s,n=null,r){const a=s.createProgram();if(e.program=a,!a)throw new Error("Unable to create program");return s.attachShader(a,t),s.attachShader(a,i),s.linkProgram(a),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||ct(e,s,r),a}function ct(e,t,i){const s=e.context,n=e.vertexShader,r=e.fragmentShader,a=e.program;if(!s.getProgramParameter(a,s.LINK_STATUS)){if(!t.getShaderParameter(n,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(n);if(i)throw e.vertexCompilationError=i,new Error("VERTEX SHADER "+i)}if(!t.getShaderParameter(r,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(r);if(i)throw e.fragmentCompilationError=i,new Error("FRAGMENT SHADER "+i)}const i=s.getProgramInfoLog(a);if(i)throw e.programLinkError=i,new Error(i)}if(i){s.validateProgram(a);if(!s.getProgramParameter(a,s.VALIDATE_STATUS)){const t=s.getProgramInfoLog(a);if(t)throw e.programValidationError=t,new Error(t)}}s.deleteShader(n),s.deleteShader(r),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}function ut(e,t,i,s,n,r){return dt(we(e,i,s),t,n,r)}function dt(e,t,i,s){const n=i.createShader("vertex"===t?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!n){let e=i.NO_ERROR,n=i.NO_ERROR;for(;(n=i.getError())!==i.NO_ERROR;)e=n;throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${i.isContextLost()}, _contextWasLost=${s}`)}return i.shaderSource(n,e),i.compileShader(n),n}function _t(e){const t=e._name,i=e.context;if(t&&i){const e=at(i),s=e.cachedPipelines[t];s?.dispose(),delete e.cachedPipelines[t]}}function ft(e,t,i,s,n,r){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){return void s(he(e))}if("source:"===e.substr(0,7))return void s(e.substr(7));if("base64:"===e.substr(0,7)){return void s(window.atob(e.substr(7)))}const a=it.GetShadersStore(n);if(a[e+t+"Shader"])return void s(a[e+t+"Shader"]);if(i&&a[e+i+"Shader"])return void s(a[e+i+"Shader"]);let o;if(o="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:it.GetShadersRepository(n)+e,!(r=r||Be))throw new Error("loadFileInjection is not defined");r(o+"."+t.toLowerCase()+".fx",s)}class mt{static get ShadersRepository(){return it.ShadersRepository}static set ShadersRepository(e){it.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new g),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,s=null,n,r=null,a=null,o=null,l=null,h,c="",u=0){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new g,this.onErrorObservable=new g,this._onBindObservable=null,this._isDisposed=!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._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=c;const d=this._key.replace(/\r/g,"").replace(/\n/g,"|");let _;if(t.attributes){const e=t;if(this._engine=i,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,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.existingPipelineContext}else this._engine=n,this.defines=null==r?"":r,this._uniformsNames=i.concat(s),this._samplerList=s?s.slice():[],this._attributesNames=t,this._uniformBuffersNamesList=[],this._shaderLanguage=u,this.onError=l,this.onCompiled=o,this._indexParameters=h,this._fallbacks=a;"WEBGL2"===this._engine.shaderPlatformName&&(_=function(e,t){return at(t).cachedPipelines[e]}(d,this._engine._gl)??_),this._attributeLocationByName={},this.uniqueId=mt._UniqueIdSeed++,_?(this._pipelineContext=_,this._pipelineContext.setEngine(this._engine),this._onRenderingStateCompiled(this._pipelineContext),this._pipelineContext.program&&(this._pipelineContext.program.__SPECTOR_rebuildProgram=this._rebuildProgram.bind(this))):this._processShaderCode()}_processShaderCode(e=null,t=!1,i=null){this._processingContext=i||this._engine._getShaderProcessingContext(this._shaderLanguage);!function(e,t,i,s,n,r,a){let o,l;const h=ae()?r?.getHostDocument():null;o="string"==typeof t?t:t.vertexSource?"source:"+t.vertexSource:t.vertexElement?h?.getElementById(t.vertexElement)||t.vertexElement:t.vertex||t,l="string"==typeof t?t:t.fragmentSource?"source:"+t.fragmentSource:t.fragmentElement?h?.getElementById(t.fragmentElement)||t.fragmentElement:t.fragment||t;const c=[void 0,void 0],u=()=>{if(c[0]&&c[1]){e.isFragment=!0;const[o,l]=c;Ke(l,e,((r,l)=>{a&&(a._fragmentSourceCodeBeforeMigration=l),i&&(r=i("fragment",r));const h=function(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}(o,r,e);e=null;const c=function(e,t,i,s){return i?{vertexSourceCode:(1===s?"//":"")+"#define SHADER_NAME vertex:"+(i.vertexElement||i.vertex||i.spectorName||i)+"\n"+e,fragmentSourceCode:(1===s?"//":"")+"#define SHADER_NAME fragment:"+(i.fragmentElement||i.fragment||i.spectorName||i)+"\n"+t}:{vertexSourceCode:e,fragmentSourceCode:t}}(h.vertexCode,h.fragmentCode,t,n);s?.(c.vertexSourceCode,c.fragmentSourceCode)}),r)}};ft(o,"Vertex","",(t=>{var s;(s=e).processor&&s.processor.initializeShaders&&s.processor.initializeShaders(s.processingContext),Ke(t,e,((e,s)=>{a&&(a._rawVertexSourceCode=t,a._vertexSourceCodeBeforeMigration=s),i&&(e=i("vertex",e)),c[0]=e,u()}),r)}),n),ft(l,"Fragment","Pixel",(e=>{a&&(a._rawFragmentSourceCode=e),c[1]=e,u()}),n)}({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:it.GetShadersRepository(this._shaderLanguage),includesShadersStore:it.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,i)=>{this._vertexSourceCode=e,this._fragmentSourceCode=i,this._prepareEffect(t)}),this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!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}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}this._isDisposed||setTimeout((()=>{this._checkIsReady(e)}),16)}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,i,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{s&&s(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;t<e.length;t++)e[t].markAllMaterialsAsDirty(tt.MATERIAL_AllDirtyFlag);this._pipelineContext._handlesSpectorRebuildCallback?.(i)},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()}_prepareEffect(e=!1){const t=this._pipelineContext;this._isReady=!1;try{const i=!(!this._vertexSourceCodeOverride||!this._fragmentSourceCodeOverride),s=i?null:this.defines,n=i?this._vertexSourceCodeOverride:this._vertexSourceCode,r=i?this._fragmentSourceCodeOverride:this._fragmentSourceCode,a=this._engine;this._pipelineContext=((e,t,i,s)=>{try{const n=e.existingPipelineContext||t(e.shaderProcessingContext);return n._name=e.name,e.name&&e.context&&(at(e.context).cachedPipelines[e.name]=n),i(n,e.vertex,e.fragment,!!e.createAsRaw,"","",e.rebuildRebind,e.defines,e.transformFeedbackVaryings,""),s(n,(()=>{e.onRenderingStateCompiled?.(n)})),n}catch(e){throw ce.Error("Error compiling effect"),e}})({existingPipelineContext:e?t:null,vertex:n,fragment:r,context:"WEBGL2"===a.shaderPlatformName?a._gl:void 0,rebuildRebind:(e,t,i,s)=>this._rebuildProgram(e,t,i,s),defines:s,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,parallelShaderCompile:a._caps.parallelShaderCompile,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:i=>{t&&!e&&this._engine._deletePipelineContext(t),i&&this._onRenderingStateCompiled(i)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContext.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t,i){const s=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let n=null;if(t&&e){const r=t.match(s);if(r&&2===r.length){const t=parseInt(r[1]),s=e.split("\n",-1);s.length>=t&&(n=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${s[t-1]}`)}}return[e,n]}_processCompilationErrors(e,t=null){this._compilationError=e.message;const i=this._attributesNames,s=this._fallbacks;if(ce.Error("Unable to compile effect:"),ce.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),ce.Error("Attributes: "+i.map((function(e){return" "+e}))),ce.Error("Defines:\n"+this.defines),mt.LogShaderCodeOnCompilationError){let e=null,t=null,i=null;this._pipelineContext?._getVertexShaderCode()&&([i,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),i&&(ce.Error("Vertex code:"),ce.Error(i))),this._pipelineContext?._getFragmentShaderCode()&&([i,t]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),i&&(ce.Error("Fragment code:"),ce.Error(i))),e&&ce.Error(e),t&&ce.Error(t)}ce.Error("Error: "+this._compilationError);const n=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,n()),s?(this._pipelineContext=null,s.hasMoreFallbacks?(this._allFallbacksProcessed=!1,ce.Error("Trying next fallback."),this.defines=s.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,n(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||n())}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 i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){const s=this._samplerList.indexOf(e);for(let e=1;e<t.length;e++){const t=i+(e-1).toString();this._samplerList.splice(s+e,0,t)}let n=0;for(const e of this._samplerList)this._samplers[e]=n,n+=1}this._engine.setTextureArray(this._samplers[e],this._uniforms[e],t,e)}bindUniformBuffer(e,t){const i=this._uniformBuffersNames[t];void 0===i||mt._BaseCache[i]===e&&this._engine._features.useUBOBindingCache||(mt._BaseCache[i]=e,this._engine.bindUniformBufferBase(e,i,t))}bindUniformBlock(e,t){this._engine.bindUniformBlock(this._pipelineContext,e,t)}setInt(e,t){return this._pipelineContext.setInt(e,t),this}setInt2(e,t,i){return this._pipelineContext.setInt2(e,t,i),this}setInt3(e,t,i,s){return this._pipelineContext.setInt3(e,t,i,s),this}setInt4(e,t,i,s,n){return this._pipelineContext.setInt4(e,t,i,s,n),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,i){return this._pipelineContext.setUInt2(e,t,i),this}setUInt3(e,t,i,s){return this._pipelineContext.setUInt3(e,t,i,s),this}setUInt4(e,t,i,s,n){return this._pipelineContext.setUInt4(e,t,i,s,n),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,i){return this._pipelineContext.setFloat2(e,t,i),this}setVector3(e,t){return this._pipelineContext.setVector3(e,t),this}setFloat3(e,t,i,s){return this._pipelineContext.setFloat3(e,t,i,s),this}setVector4(e,t){return this._pipelineContext.setVector4(e,t),this}setQuaternion(e,t){return this._pipelineContext.setQuaternion(e,t),this}setFloat4(e,t,i,s,n){return this._pipelineContext.setFloat4(e,t,i,s,n),this}setColor3(e,t){return this._pipelineContext.setColor3(e,t),this}setColor4(e,t,i){return this._pipelineContext.setColor4(e,t,i),this}setDirectColor4(e,t){return this._pipelineContext.setDirectColor4(e,t),this}dispose(){this._pipelineContext&&_t(this._pipelineContext),this._engine._releaseEffect(this),this._isDisposed=!0}static RegisterShader(e,t,i,s=0){t&&(it.GetShadersStore(s)[`${e}PixelShader`]=t),i&&(it.GetShadersStore(s)[`${e}VertexShader`]=i)}static ResetCache(){mt._BaseCache={}}}mt.LogShaderCodeOnCompilationError=!0,mt._UniqueIdSeed=0,mt._BaseCache={},mt.ShadersStore=it.ShadersStore,mt.IncludesShadersStore=it.IncludesShadersStore;class pt{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 gt{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 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 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.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.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.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}}class Et{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=Et.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=Et.KEEP,this.opDepthFail=Et.KEEP,this.opStencilDepthPass=Et.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=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 stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}}Et.ALWAYS=tt.ALWAYS,Et.KEEP=tt.KEEP,Et.REPLACE=tt.REPLACE;class Tt{constructor(){this._blendFunctionParameters=new Array(4),this._blendEquationParameters=new Array(2),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._alphaBlend}set alphaBlend(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,s){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===s||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=s,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,s){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===s||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=s,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t){this._blendEquationParameters[0]===e&&this._blendEquationParameters[1]===t||(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=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){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?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),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))}}class At{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=tt.TEXTURE_WRAP_ADDRESSMODE,t=tt.TEXTURE_WRAP_ADDRESSMODE,i=tt.TEXTURE_WRAP_ADDRESSMODE,s=1,n=tt.TEXTURE_BILINEAR_SAMPLINGMODE,r=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=s,this.samplingMode=n,this._comparisonFunction=r,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 Rt;!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"}(Rt||(Rt={}));class vt extends At{get useMipMaps(){return this.generateMipMaps}set useMipMaps(e){this.generateMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new g,this.onErrorObservable=new g,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._engine=e,this._source=t,this._uniqueId=vt._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_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: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),e._swapAndDie(this,!1),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:e=this._engine.createRawTexture2DArray(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 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,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 i=this._engine.getLoadedTexturesCache();let s=i.indexOf(this);-1!==s&&i.splice(s,1),s=i.indexOf(e),-1===s&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}function It(e,t){if(ae()){const{requestAnimationFrame:i}=t||window;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}vt._Counter=0;class St{get frameId(){return this._frameId}get isWebGPU(){return this._isWebGPU}_getShaderProcessor(e){return this._shaderProcessor}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?tt.GEQUAL:tt.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._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}mt.ResetCache()}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){ce.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout((async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,n=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=n,this._flagContextRestored()}),0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return tt.SNAPSHOTRENDERING_STANDARD}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,tt.TEXTUREFORMAT_RGBA,!1,!1,tt.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,tt.TEXTUREFORMAT_RGBA,!1,!1,tt.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,tt.TEXTUREFORMAT_RGBA,!1,!1,tt.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,tt.TEXTUREFORMAT_RGBA,tt.TEXTURETYPE_UNSIGNED_INT,!1,!1,tt.TEXTURE_NEAREST_SAMPLINGMODE)}return this._emptyCubeTexture}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(0!==this._frameHandler){const e=this._frameHandler;if(this._frameHandler=0,ae()){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)}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e<this._activeRenderLoops.length;e++){(0,this._activeRenderLoops[e])()}}_renderViews(){return!1}_queueNewFrame(e,t){return It(e,t)}runRenderLoop(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),1===this._activeRenderLoops.length&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}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 ae()?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,i){const s=t||this.getRenderWidth(),n=i||this.getRenderHeight(),r=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(r*s,a*n,s*e.width,n*e.height)}createCanvasImage(){return document.createElement("img")}get description(){let e=this.name+this.version;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}_createTextureBase(e,t,i,s,n=tt.TEXTURE_TRILINEAR_SAMPLINGMODE,r=null,a=null,o,l,h=null,c=null,u=null,d=null,_,f,m){const p="data:"===(e=e||"").substr(0,5),g="blob:"===e.substr(0,5),E=p&&-1!==e.indexOf(";base64,"),T=c||new vt(this,1);T!==c&&(T.label=e.substring(0,60));const A=e;!this._transformTextureUrl||E||c||h||(e=this._transformTextureUrl(e)),A!==e&&(T._originalUrl=A);const R=e.lastIndexOf(".");let v=d||(R>-1?e.substring(R).toLowerCase():""),I=null;v.indexOf("?")>-1&&(v=v.split("?")[0]);for(const e of St._TextureLoaders)if(e.canLoad(v,_)){I=e;break}s&&s.addPendingData(T),T.url=e,T.generateMipMaps=!t,T.samplingMode=n,T.invertY=i,T._useSRGBBuffer=this._getUseSRGBBuffer(!!m,t),this._doNotHandleContextLost||(T._buffer=h);let S=null;r&&!c&&(S=T.onLoadedObservable.add(r)),c||this._internalTexturesCache.push(T);const C=(i,c)=>{s&&s.removePendingData(T),e===A?(S&&T.onLoadedObservable.remove(S),M.UseFallbackTexture&&e!==M.FallbackTexture&&this._createTextureBase(M.FallbackTexture,t,T.invertY,s,n,null,a,o,l,h,T),i=(i||"Unknown error")+(M.UseFallbackTexture?" - Fallback texture was used":""),T.onErrorObservable.notifyObservers({message:i,exception:c}),a&&a(i,c)):(ce.Warn(`Failed to load ${e}, falling back to ${A}`),this._createTextureBase(A,t,T.invertY,s,n,r,a,o,l,h,T,u,d,_,f,m))};if(I){const t=e=>{I.loadData(e,T,((e,t,i,r,a,l)=>{l?C("TextureLoader failed to load data"):o(T,v,s,{width:e,height:t},T.invertY,!i,r,(()=>(a(),!1)),n)}),f)};h?h instanceof ArrayBuffer?t(new Uint8Array(h)):ArrayBuffer.isView(h)?t(h):a&&a("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,s?s.offlineProvider:void 0,!0,((e,t)=>{C("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{g&&!this._doNotHandleContextLost&&(T._buffer=e),o(T,v,s,e,T.invertY,t,!1,l,n)};!p||E?h&&("string"==typeof h.decoding||h.close)?i(h):St._FileToolsLoadImage(e||"",i,C,s?s.offlineProvider:null,_,T.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof h||h instanceof ArrayBuffer||ArrayBuffer.isView(h)||h instanceof Blob?St._FileToolsLoadImage(h,i,C,s?s.offlineProvider:null,_,T.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):h&&i(h)}return T}_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:le()?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@7.18.0"}static get Version(){return"7.18.0"}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,i){this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new pt,this._stencilStateComposer=new gt,this._stencilState=new Et,this._alphaState=new Tt,this._alphaMode=tt.ALPHA_ADD,this._alphaEquation=tt.ALPHA_DISABLE,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.onCanvasBlurObservable=new g,this.onCanvasFocusObservable=new g,this.onNewSceneAddedObservable=new g,this.onResizeObservable=new g,this.onCanvasPointerOutObservable=new g,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=tt.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 g,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new g,this.onAfterShaderCompilationObservable=new g,this.onBeginFrameObservable=new g,this.onEndFrameObservable=new g,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new g,this.onContextRestoredObservable=new g,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 g,M.Instances.push(this),this.startTime=_e.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,y.SetMatrixPrecision(!!t.useHighPrecisionMatrix),oe()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),this.adaptToDeviceRatio=i??!1,t.antialias=e??t.antialias,t.deterministicLockstep=t.deterministicLockstep??!1,t.lockstepMaxSteps=t.lockstepMaxSteps??4,t.timeStep=t.timeStep??1/60,t.audioEngine=t.audioEngine??!0,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;const s=ae()&&window.devicePixelRatio||1,n=t.limitDeviceRatio||s;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(n,s):1,this._lastDevicePixelRatio=s,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const e=ae()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if(ae()&&le())if(this._renderingCanvas){const e=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||e.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||e.height||this._renderingCanvas.height||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){if(!this._renderingCanvas)return!1;if(e|=0,t|=0,!i&&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,i,s,n,r,a,o,l,h,c){throw W("engine.rawTexture")}createRawCubeTexture(e,t,i,s,n,r,a,o){throw W("engine.rawTexture")}createRawTexture3D(e,t,i,s,n,r,a,o,l,h,c){throw W("engine.rawTexture")}createRawTexture2DArray(e,t,i,s,n,r,a,o,l,h,c){throw W("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")&&le()&&"ontouchend"in document},this._checkForMobile(),ae()&&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,i){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 i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return St._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,s,n,r){throw W("FileTools")}_loadFile(e,t,i,s,n,r){const a=Be(e,t,i,s,n,r);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,i,s,n,r){if(Fe.loadFile)return Fe.loadFile(e,t,i,s,n,r);throw W("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?.(),mt.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(),ae()&&window.removeEventListener("resize",this._checkForMobile);const e=M.Instances.indexOf(this);e>=0&&M.Instances.splice(e,1),M.Instances.length||(M.OnEnginesDisposedObservable.notifyObservers(this),M.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw W("LoadingScreen")}}St._TextureLoaders=[],St._RenderPassIdCounter=0,St._RescalePostProcessFactory=null;const Ct=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class bt extends Ie{constructor(e,t){super(e,Ae),this.name="LoadFileError",pe._setPrototypeOf(this,bt.prototype),t instanceof fe?this.request=t:this.file=t}}class yt extends Ie{constructor(e,t){super(e,Re),this.request=t,this.name="RequestFileError",pe._setPrototypeOf(this,yt.prototype)}}class Mt extends Ie{constructor(e,t){super(e,ve),this.file=t,this.name="ReadFileError",pe._setPrototypeOf(this,Mt.prototype)}}const xt={DefaultRetryStrategy:class{static ExponentialBackoff(e=3,t=500){return(i,s,n)=>0!==s.status||n>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,n)*t}}.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e,CleanUrl:e=>e=e.replace(/#/gm,"%23")},Ot=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&xt.CorsBehavior)if("string"==typeof xt.CorsBehavior||xt.CorsBehavior instanceof String)t.crossOrigin=xt.CorsBehavior;else{const i=xt.CorsBehavior(e);i&&(t.crossOrigin=i)}},Dt=(e,t,i,s,n="",r)=>{const a=M.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!a?._features.forceBitmapOverHTMLImageElement)return i("LoadImage is only supported in web or BabylonNative environments."),null;let o,l=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(o=URL.createObjectURL(new Blob([e],{type:n})),l=!0):o=`data:${n};base64,`+Se(e):e instanceof Blob?(o=URL.createObjectURL(e),l=!0):(o=xt.CleanUrl(e),o=xt.PreprocessUrl(o));const h=t=>{if(i){const s=o||e.toString();i(`Error while trying to load image: ${0===s.indexOf("http")||s.length<=128?s:s.slice(0,128)+"..."}`,t)}};if(a?._features.forceBitmapOverHTMLImageElement)return Nt(o,(s=>{a.createImageBitmap(new Blob([s],{type:n}),{premultiplyAlpha:"none",...r}).then((e=>{t(e),l&&URL.revokeObjectURL(o)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,s||void 0,!0,((e,t)=>{h(t)})),null;const c=new Image;Ot(o,c);const u=[],d=()=>{u.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),u.length=0};u.push({target:c,name:"load",handler:()=>{d(),t(c),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:c,name:"error",handler:e=>{d(),h(e),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==c.src)return;d();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);M.UseFallbackTexture=!1,h(t),l&&c.src&&URL.revokeObjectURL(c.src),c.src=""}}),u.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const _="blob:"===o.substring(0,5),f="data:"===o.substring(0,5),m=()=>{_||f||!fe.IsCustomRequestAvailable?c.src=o:Nt(o,((e,t,i)=>{const s=new Blob([e],{type:!n&&i?i:n}),r=URL.createObjectURL(s);l=!0,c.src=r}),void 0,s||void 0,!0,((e,t)=>{h(t)}))},p=()=>{s&&s.loadImage(o,c)};if(!_&&!f&&s&&s.enableTexturesOffline)s.open(p,m);else{if(-1!==o.indexOf("file:")){const e=decodeURIComponent(o.substring(5).toLowerCase());if(me.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(me.FilesToLoad[e])}catch(i){t=URL.createObjectURL(me.FilesToLoad[e])}c.src=t,l=!0}catch(e){c.src=""}return c}}m()}return c},Pt=(e,t,i,s,n)=>{const r=new FileReader,a={onCompleteObservable:new g,abort:()=>r.abort()};return r.onloadend=()=>a.onCompleteObservable.notifyObservers(a),n&&(r.onerror=()=>{n(new Mt(`Unable to read ${e.name}`,e))}),r.onload=e=>{t(e.target.result)},i&&(r.onprogress=i),s?r.readAsArrayBuffer(e):r.readAsText(e),a},Nt=(e,t,i,s,n,r,a)=>{if(e.name)return Pt(e,t,i,n,r?e=>{r(void 0,e)}:void 0);const o=e;if(-1!==o.indexOf("file:")){let e=decodeURIComponent(o.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const s=me.FilesToLoad[e];if(s)return Pt(s,t,i,n,r?e=>r(void 0,new bt(e.message,e.file)):void 0)}const{match:l,type:h}=Bt(o);if(l){const e={onCompleteObservable:new g,abort:()=>()=>{}};try{const e=n?Ut(o):kt(o);t(e,void 0,h)}catch(e){r?r(void 0,e):ce.Error(e.message||"Failed to parse the Data URL")}return et.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return Lt(o,((e,i)=>{t(e,i?.responseURL,i?.getResponseHeader("content-type"))}),i,s,n,r?e=>{r(e.request,new bt(e.message,e.request))}:void 0,a)},Lt=(e,t,i,s,n,r,a)=>{e=xt.CleanUrl(e),e=xt.PreprocessUrl(e);const o=xt.BaseUrl+e;let l=!1;const h={onCompleteObservable:new g,abort:()=>l=!0},c=()=>{let e,s=new fe,c=null;const u=()=>{s&&(i&&s.removeEventListener("progress",i),e&&s.removeEventListener("readystatechange",e),s.removeEventListener("loadend",d))};let d=()=>{u(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),i=void 0,e=null,d=null,r=void 0,a=void 0,t=void 0};h.abort=()=>{l=!0,d&&d(),s&&s.readyState!==(XMLHttpRequest.DONE||4)&&s.abort(),null!==c&&(clearTimeout(c),c=null),s=null};const _=e=>{const t=e.message||"Unknown error";r&&s?r(new yt(t,s)):ce.Error(t)},f=h=>{if(s){if(s.open("GET",o),a)try{a(s)}catch(e){return void _(e)}n&&(s.responseType="arraybuffer"),i&&s.addEventListener("progress",i),d&&s.addEventListener("loadend",d),e=()=>{if(!l&&s&&s.readyState===(XMLHttpRequest.DONE||4)){if(e&&s.removeEventListener("readystatechange",e),s.status>=200&&s.status<300||0===s.status&&(!ae()||Ft())){try{t&&t(n?s.response:s.responseText,s)}catch(e){_(e)}return}const i=xt.DefaultRetryStrategy;if(i){const e=i(o,s,h);if(-1!==e)return u(),s=new fe,void(c=setTimeout((()=>f(h+1)),e))}const a=new yt("Error status: "+s.status+" "+s.statusText+" - Unable to load "+o,s);r&&r(a)}},s.addEventListener("readystatechange",e),s.send()}};f(0)};if(s&&s.enableSceneOffline){const a=e=>{e&&e.status>400?r&&r(e):c()},o=()=>{s&&s.loadFile(xt.BaseUrl+e,(e=>{!l&&t&&t(e),h.onCompleteObservable.notifyObservers(h)}),i?e=>{!l&&i&&i(e)}:void 0,a,n)};s.open(o,a)}else c();return h},Ft=()=>"undefined"!=typeof location&&"file:"===location.protocol,wt=e=>Ct.test(e),Bt=e=>{const t=Ct.exec(e);if(null===t||0===t.length)return{match:!1,type:""};return{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function Ut(e){return(e=>{const t=Ce(e),i=t.length,s=new Uint8Array(new ArrayBuffer(i));for(let e=0;e<i;e++)s[e]=t.charCodeAt(e);return s.buffer})(e.split(",")[1])}const kt=e=>Ce(e.split(",")[1]);let Gt;St._FileToolsLoadImage=Dt,Fe.loadFile=Nt,Je.loadFile=Nt;((e,t,i,s,n,r,a,o,l,h)=>{Gt={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:s,IsFileURL:n,LoadFile:r,LoadImage:a,ReadFile:o,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(Gt,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(Gt,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(Gt,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(Gt,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})})(Ut,kt,xt,wt,Ft,Nt,Dt,Pt,Lt,Ot);class Vt{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=b(e);if(t)return t;ce.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let e=0,t=i.length;e<t;e++)s=s[i[e]];return"function"!=typeof s?null:s}}function Xt(){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 Ht(e){let t=1;do{t*=2}while(t<e);return t===e}function zt(e,t,i){return e*(1-i)+t*i}function Wt(e){const t=Yt(e),i=Kt(e);return t-e>e-i?i:t}function Yt(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}function Kt(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}function qt(e,t,i=tt.SCALEMODE_NEAREST){let s;switch(i){case tt.SCALEMODE_FLOOR:s=Kt(e);break;case tt.SCALEMODE_NEAREST:s=Wt(e);break;case tt.SCALEMODE_CEILING:default:s=Yt(e)}return Math.min(s,t)}Vt.RegisteredExternalClasses={};class Qt{static get BaseUrl(){return xt.BaseUrl}static set BaseUrl(e){xt.BaseUrl=e}static get CleanUrl(){return xt.CleanUrl}static set CleanUrl(e){xt.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){xt.ScriptBaseUrl=e}static get ScriptBaseUrl(){return xt.ScriptBaseUrl}static set ScriptPreprocessUrl(e){xt.ScriptPreprocessUrl=e}static get ScriptPreprocessUrl(){return xt.ScriptPreprocessUrl}static get DefaultRetryStrategy(){return xt.DefaultRetryStrategy}static set DefaultRetryStrategy(e){xt.DefaultRetryStrategy=e}static get CorsBehavior(){return xt.CorsBehavior}static set CorsBehavior(e){xt.CorsBehavior=e}static get UseFallbackTexture(){return M.UseFallbackTexture}static set UseFallbackTexture(e){M.UseFallbackTexture=e}static get RegisteredExternalClasses(){return Vt.RegisteredExternalClasses}static set RegisteredExternalClasses(e){Vt.RegisteredExternalClasses=e}static get fallbackTexture(){return M.FallbackTexture}static set fallbackTexture(e){M.FallbackTexture=e}static FetchToRef(e,t,i,s,n,r){const a=4*((Math.abs(e)*i%i|0)+(Math.abs(t)*s%s|0)*i);r.r=n[a]/255,r.g=n[a+1]/255,r.b=n[a+2]/255,r.a=n[a+3]/255}static Mix(e,t,i){return 0}static Instantiate(e){return Vt.Instantiate(e)}static SetImmediate(e){et.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 i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)}static ToDegrees(e){return 180*e/Math.PI}static ToRadians(e){return e*Math.PI/180}static SmoothAngleChange(e,t,i=.9){const s=this.ToRadians(e),n=this.ToRadians(t);return this.ToDegrees(Math.atan2((1-i)*Math.sin(n)+i*Math.sin(s),(1-i)*Math.cos(n)+i*Math.cos(s)))}static MakeArray(e,t){return!0===t||void 0!==e&&null!=e?Array.isArray(e)?e:[e]:null}static GetPointerPrefix(e){let t="pointer";return ae()&&!window.PointerEvent&&(t="mouse"),!e._badDesktopOS||e._badOS||document&&"ontouchend"in document||(t="mouse"),t}static SetCorsBehavior(e,t){Ot(e,t)}static SetReferrerPolicyBehavior(e,t){t.referrerPolicy=e}static get PreprocessUrl(){return xt.PreprocessUrl}static set PreprocessUrl(e){xt.PreprocessUrl=e}static LoadImage(e,t,i,s,n,r){return Dt(e,t,i,s,n,r)}static LoadFile(e,t,i,s,n,r){return Nt(e,t,i,s,n,r)}static LoadFileAsync(e,t=!0){return new Promise(((i,s)=>{Nt(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{s(t)}))}))}static GetBabylonScriptURL(e,t){if(!e)return"";if(Qt.ScriptBaseUrl&&e.startsWith(Qt._DefaultCdnUrl)){const t="/"===Qt.ScriptBaseUrl[Qt.ScriptBaseUrl.length-1]?Qt.ScriptBaseUrl.substring(0,Qt.ScriptBaseUrl.length-1):Qt.ScriptBaseUrl;e=e.replace(Qt._DefaultCdnUrl,t)}return e=Qt.ScriptPreprocessUrl(e),t&&(e=Qt.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=Qt.GetBabylonScriptURL(e),Qt.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=Qt.GetBabylonScriptURL(e),Qt.LoadScriptAsync(e)}static LoadScript(e,t,i,s){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){i?.(`Unable to load script '${e}' in worker`,t)}return}if(!ae())return void i?.(`Cannot load script '${e}' outside of a window or a worker`);const n=document.getElementsByTagName("head")[0],r=document.createElement("script");r.setAttribute("type","text/javascript"),r.setAttribute("src",e),s&&(r.id=s),r.onload=()=>{t&&t()},r.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},n.appendChild(r)}static LoadScriptAsync(e,t){return new Promise(((i,s)=>{this.LoadScript(e,(()=>{i()}),((e,t)=>{s(t||new Error(e))}),t)}))}static ReadFileAsDataURL(e,t,i){const s=new FileReader,n={onCompleteObservable:new g,abort:()=>s.abort()};return s.onloadend=()=>{n.onCompleteObservable.notifyObservers(n)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),n}static ReadFile(e,t,i,s,n){return Pt(e,t,i,s,n)}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,i,s){de.DeepCopy(e,t,i,s)}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 i=0;i<t.length;i++){const s=t[i];e.addEventListener(s.name,s.handler,!1);try{window.parent&&window.parent.addEventListener(s.name,s.handler,!1)}catch(e){}}}static UnregisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){const s=t[i];e.removeEventListener(s.name,s.handler);try{e.parent&&e.parent.removeEventListener(s.name,s.handler)}catch(e){}}}static async DumpFramebuffer(e,t,i,s,n="image/png",r,a){throw W("DumpTools")}static DumpData(e,t,i,s,n="image/png",r,a=!1,o=!1,l){throw W("DumpTools")}static DumpDataAsync(e,t,i,s="image/png",n,r=!1,a=!1,o){throw W("DumpTools")}static _IsOffScreenCanvas(e){return void 0!==e.convertToBlob}static ToBlob(e,t,i="image/png",s){Qt._IsOffScreenCanvas(e)||e.toBlob||(e.toBlob=function(e,t,i){setTimeout((()=>{const s=atob(this.toDataURL(t,i).split(",")[1]),n=s.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=s.charCodeAt(e);e(new Blob([r]))}))}),Qt._IsOffScreenCanvas(e)?e.convertToBlob({type:i,quality:s}).then((e=>t(e))):e.toBlob((function(e){t(e)}),i,s)}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"}Qt.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),i=window.open("");if(!i)return;const s=i.document.createElement("img");s.onload=function(){URL.revokeObjectURL(t)},s.src=t,i.document.body.appendChild(s)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,n){if("string"!=typeof s&&t){if(t){if(Qt._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:n}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const s=e.toDataURL(i,n);t(s)}}else this.ToBlob(e,(function(e){e&&Qt.DownloadBlob(e,s),t&&t("")}),i,n)}static Download(e,t){if("undefined"==typeof URL)return;const i=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.style.display="none",s.href=i,s.download=t,s.addEventListener("click",(()=>{s.parentElement&&s.parentElement.removeChild(s)})),s.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,s,n="image/png",r=!1,a){throw W("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",n){throw W("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,n="image/png",r=1,a=!1,o,l=!1,h=!1,c=!0,u){throw W("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",n=1,r=!1,a,o=!1,l=!1,h=!0,c){throw W("ScreenshotTools")}static RandomId(){return Xt()}static IsBase64(e){return wt(e)}static DecodeBase64(e){return Ut(e)}static get errorsCount(){return ce.errorsCount}static Log(e){ce.Log(e)}static Warn(e){ce.Warn(e)}static Error(e){ce.Error(e)}static get LogCache(){return ce.LogCache}static ClearLogCache(){ce.ClearLogCache()}static set LogLevels(e){ce.LogLevels=e}static set PerformanceLogLevel(e){return(e&Qt.PerformanceUserMarkLogLevel)===Qt.PerformanceUserMarkLogLevel?(Qt.StartPerformanceCounter=Qt._StartUserMark,void(Qt.EndPerformanceCounter=Qt._EndUserMark)):(e&Qt.PerformanceConsoleLogLevel)===Qt.PerformanceConsoleLogLevel?(Qt.StartPerformanceCounter=Qt._StartPerformanceConsole,void(Qt.EndPerformanceCounter=Qt._EndPerformanceConsole)):(Qt.StartPerformanceCounter=Qt._StartPerformanceCounterDisabled,void(Qt.EndPerformanceCounter=Qt._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Qt._Performance){if(!ae())return;Qt._Performance=window.performance}t&&Qt._Performance.mark&&Qt._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&Qt._Performance.mark&&(Qt._Performance.mark(e+"-End"),Qt._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Qt._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Qt._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return _e.Now}static GetClassName(e,t=!1){let i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__}i||(i=typeof e)}return i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,s=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const n=t?e:Object.getPrototypeOf(e);i=n.constructor.__bjsclassName__,s=n.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=s?s+".":"")+i:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!oe()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}Qt.UseCustomRequestHeaders=!1,Qt.CustomRequestHeaders=fe.CustomRequestHeaders,Qt.GetDOMTextContent=he,Qt._DefaultCdnUrl="https://cdn.babylonjs.com",Qt.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.")},Qt.NoneLogLevel=ce.NoneLogLevel,Qt.MessageLogLevel=ce.MessageLogLevel,Qt.WarningLogLevel=ce.WarningLogLevel,Qt.ErrorLogLevel=ce.ErrorLogLevel,Qt.AllLogLevel=ce.AllLogLevel,Qt.IsWindowObjectExist=ae,Qt.PerformanceNoneLogLevel=0,Qt.PerformanceUserMarkLogLevel=1,Qt.PerformanceConsoleLogLevel=2,Qt.StartPerformanceCounter=Qt._StartPerformanceCounterDisabled,Qt.EndPerformanceCounter=Qt._EndPerformanceCounterDisabled;class jt{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}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,i,s=0){const n=new jt(e,t,i,s);return n.executeNext(),n}static SyncAsyncForLoop(e,t,i,s,n,r=0){return jt.Run(Math.ceil(e/t),(s=>{n&&n()?s.breakLoop():setTimeout((()=>{for(let r=0;r<t;++r){const a=s.index*t+r;if(a>=e)break;if(i(a),n&&n()){s.breakLoop();break}}s.executeNext()}),r)}),s)}}function Zt(e,t,i){try{const s=e.next();s.done?t(s):s.value?s.value.then((()=>{s.value=void 0,t(s)}),i):t(s)}catch(e){i(e)}}function $t(e,t,i,s,n){const r=()=>{let n;const a=e=>{e.done?i(e.value):void 0===n?n=!0:r()};do{n=void 0,t(e,a,s),void 0===n&&(n=!1)}while(n)};r()}function Jt(e,t){let i;return $t(e,Zt,(e=>i=e),(e=>{throw e})),i}Qt.Mix=zt,Qt.IsExponentOfTwo=Ht,M.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";class ei{constructor(e){this.length=0,this.data=new Array(e),this._id=ei._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)}}ei._GlobalId=0;class ti extends ei{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 i=(e.data||e)[t];this.pushNoDuplicate(i)}}}}class ii{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new ii(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new ii(this.x,this.y,this.width,this.height)}}class si{constructor(e,t,i,s){this.normal=new B(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new si(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=si._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,n=this.normal.y,r=this.normal.z,a=this.d,o=s*i[0]+n*i[1]+r*i[2]+a*i[3],l=s*i[4]+n*i[5]+r*i[6]+a*i[7],h=s*i[8]+n*i[9]+r*i[10]+a*i[11],c=s*i[12]+n*i[13]+r*i[14]+a*i[15];return new si(o,l,h,c)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const s=t.x-e.x,n=t.y-e.y,r=t.z-e.z,a=i.x-e.x,o=i.y-e.y,l=i.z-e.z,h=n*l-r*o,c=r*a-s*l,u=s*o-n*a,d=Math.sqrt(h*h+c*c+u*u);let _;return _=0!==d?1/d:0,this.normal.x=h*_,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 B.Dot(this.normal,e)<=t}signedDistanceTo(e){return B.Dot(e,this.normal)+this.d}static FromArray(e){return new si(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new si(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new si(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return B.Dot(i,t)+s}}si._TmpMatrix=G.Identity();class ni{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new si(0,0,0,0));return ni.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){ni.GetNearPlaneToRef(e,t[0]),ni.GetFarPlaneToRef(e,t[1]),ni.GetLeftPlaneToRef(e,t[2]),ni.GetRightPlaneToRef(e,t[3]),ni.GetTopPlaneToRef(e,t[4]),ni.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}class ri extends re{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 e=0,t=0;if(this.mode===ri.PERSPECTIVE_CAMERA)this.fovMode===ri.FOVMODE_VERTICAL_FIXED?(t=2*this.minZ*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=2*this.minZ*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,s=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??s)-(this.orthoBottom??-s)}return e*t}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}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(e,t,i,s=!0){super(e,i,!1),this._position=B.Zero(),this._upVector=B.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=ri.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new ii(0,0,1,1),this.layerMask=268435455,this.fovMode=ri.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=ri.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new g,this.onProjectionMatrixChangedObservable=new g,this.onAfterCheckInputsObservable=new g,this.onRestoreStateObservable=new g,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new G,this._postProcesses=new Array,this._activeMeshes=new ei(256),this._globalPosition=B.Zero(),this._computedViewMatrix=G.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=G.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=k.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}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 i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].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 B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new B(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(){let e=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ;if(!e)return!1;const t=this.getEngine();return this.mode===ri.PERSPECTIVE_CAMERA?e=this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===t.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:(e=this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===t.getRenderWidth()&&this._cache.renderHeight===t.getRenderHeight(),this.oblique&&(e=e&&this._cache.obliqueAngle===this.oblique.angle&&this._cache.obliqueLength===this.oblique.length&&this._cache.obliqueOffset===this.oblique.offset)),e}attachControl(e,t){}detachControl(e){}update(){this._hasMoved=!1,this._checkInputs(),this.cameraRigMode!==ri.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],i=t._rigPostProcess;if(i){"pass"===i.getEffectName()&&(t.isIntermediate=0===this._postProcesses.length),t._postProcesses=this._postProcesses.slice(0).concat(i),i.markTextureDirty()}else t._postProcesses=this._postProcesses.slice(0)}}attachPostProcess(e,t=null){return!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(ce.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 G.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._computedViewMatrix}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),i=this.getScene(),s=t.useReverseDepthBuffer;if(this.mode===ri.PERSPECTIVE_CAMERA){let e;this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=t.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),e=i.useRightHandedSystem?G.PerspectiveFovRHToRef:G.PerspectiveFovLHToRef,e(this.fov,t.getAspectRatio(this),s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===ri.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{const e=t.getRenderWidth()/2,n=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?G.ObliqueOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-n,this.orthoTop??n,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):G.OrthoOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-n,this.orthoTop??n,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?G.ObliqueOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-n,this.orthoTop??n,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):G.OrthoOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-n,this.orthoTop??n,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.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=t.getRenderWidth(),this._cache.renderHeight=t.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?B.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?ni.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=ni.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw W("Ray")}getForwardRayToRef(e,t=100,i,s){throw W("Ray")}dispose(e,t=!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!==ri.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(e,t)}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(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=Qt.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==ri.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(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return G.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,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=Qt.ToRadians(t/.0637))}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.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===ri.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)}_setupInputs(){}serialize(){const e=se.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&this.parent._serializeAsParent(e),this.inputs&&this.inputs.serialize(e),se.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}clone(e,t=null){const i=se.Clone(ri.GetConstructorFromName(this.getClassName(),e,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this);return i.name=e,i.parent=t,this.onClonedObservable.notifyObservers(i),i}getDirection(e){const t=B.Zero();return this.getDirectionToRef(e,t),t}get absoluteRotation(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation}getDirectionToRef(e,t){B.TransformNormalToRef(e,this.getWorldMatrix(),t)}static GetConstructorFromName(e,t,i,s=0,n=!0){const r=re.Construct(e,t,i,{interaxial_distance:s,isStereoscopicSideBySide:n});return r||(()=>ri._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=ri.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),n=se.Parse(s,e,t);if(void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),n.inputs&&(n.inputs.parse(e),n._setupInputs()),e.upVector&&(n.upVector=B.FromArray(e.upVector)),n.setPosition&&(n.position.copyFromFloats(0,0,0),n.setPosition(B.FromArray(e.position))),e.target&&n.setTarget&&n.setTarget(B.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};n.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t<e.animations.length;t++){const i=e.animations[t],s=b("BABYLON.Animation");s&&n.animations.push(s.Parse(i))}re.ParseAnimationRanges(n,e,t)}return e.autoAnimate&&t.beginAnimation(n,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&n.setEnabled(e.isEnabled),n}_calculateHandednessMultiplier(){let e=this.getScene().useRightHandedSystem?-1:1;return this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(e*=-1),e}}ri._CreateDefaultParsedCamera=(e,t)=>{throw W("UniversalCamera")},ri.PERSPECTIVE_CAMERA=tt.PERSPECTIVE_CAMERA,ri.ORTHOGRAPHIC_CAMERA=tt.ORTHOGRAPHIC_CAMERA,ri.FOVMODE_VERTICAL_FIXED=tt.FOVMODE_VERTICAL_FIXED,ri.FOVMODE_HORIZONTAL_FIXED=tt.FOVMODE_HORIZONTAL_FIXED,ri.RIG_MODE_NONE=tt.RIG_MODE_NONE,ri.RIG_MODE_STEREOSCOPIC_ANAGLYPH=tt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,ri.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=tt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,ri.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=tt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,ri.RIG_MODE_STEREOSCOPIC_OVERUNDER=tt.RIG_MODE_STEREOSCOPIC_OVERUNDER,ri.RIG_MODE_STEREOSCOPIC_INTERLACED=tt.RIG_MODE_STEREOSCOPIC_INTERLACED,ri.RIG_MODE_VR=tt.RIG_MODE_VR,ri.RIG_MODE_CUSTOM=tt.RIG_MODE_CUSTOM,ri.ForceAttachControlToAlwaysPreventDefault=!1,e([c("position")],ri.prototype,"_position",void 0),e([c("upVector")],ri.prototype,"_upVector",void 0),e([a()],ri.prototype,"orthoLeft",null),e([a()],ri.prototype,"orthoRight",null),e([a()],ri.prototype,"orthoBottom",null),e([a()],ri.prototype,"orthoTop",null),e([a()],ri.prototype,"fov",void 0),e([a()],ri.prototype,"projectionPlaneTilt",void 0),e([a()],ri.prototype,"minZ",void 0),e([a()],ri.prototype,"maxZ",void 0),e([a()],ri.prototype,"inertia",void 0),e([a()],ri.prototype,"mode",null),e([a()],ri.prototype,"layerMask",void 0),e([a()],ri.prototype,"fovMode",void 0),e([a()],ri.prototype,"cameraRigMode",void 0),e([a()],ri.prototype,"interaxialDistance",void 0),e([a()],ri.prototype,"isStereoscopicSideBySide",void 0);class ai{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=ai._Counter++}}ai._Counter=0;class oi{get isDisposed(){return this._isDisposed}constructor(e,t,i,s=0,n=!1,r=!1,a=!1,o,l){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=r,this._divisor=o||1,this._label=l,t instanceof ai?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=a?s:s*Float32Array.BYTES_PER_ELEMENT,n||this.create()}createVertexBuffer(e,t,i,s,n,r=!1,a){const o=r?t:t*Float32Array.BYTES_PER_ELEMENT,l=s?r?s:s*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new li(this._engine,this,e,this._updatable,!0,l,void 0===n?this._instanced:n,o,i,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));ce.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,i,s=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,s?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),this._data=0===t&&void 0===i?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 li{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,i,s,n,r,a,o,l,h,c=!1,u=!1,d=1,_=!1){this._isDisposed=!1;let f=!1;if(this.engine=e,"object"==typeof s&&null!==s?(f=s.updatable??!1,n=s.postponeInternalCreation,r=s.stride,a=s.instanced,o=s.offset,l=s.size,h=s.type,c=s.normalized??!1,u=s.useBytes??!1,d=s.divisor??1,_=s.takeBufferOwnership??!1,this._label=s.label):f=!!s,t instanceof oi?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new oi(e,t,f,r,n,a,u,d,this._label),this._ownsBuffer=!0),this.uniqueId=li._Counter++,this._kind=i,void 0===h){const e=this.getData();this.type=e?li.GetDataType(e):li.FLOAT}else this.type=h;const m=li.GetTypeByteLength(this.type);u?(this._size=l||(r?r/m:li.DeduceStride(i)),this.byteStride=r||this._buffer.byteStride||this._size*m,this.byteOffset=o||0):(this._size=l||r||li.DeduceStride(i),this.byteStride=r?r*m:this._buffer.byteStride||this._size*m,this.byteOffset=(o||0)*m),this.normalized=c,this._instanced=void 0!==a&&a,this._instanceDivisor=a?d:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120|0)+((this.normalized?1:0)<<3)+(this._size<<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 i=this.getData();return i?li.GetFloatData(i,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/li.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/li.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*li.GetTypeByteLength(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,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){li.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case li.UVKind:case li.UV2Kind:case li.UV3Kind:case li.UV4Kind:case li.UV5Kind:case li.UV6Kind:return 2;case li.NormalKind:case li.PositionKind:return 3;case li.ColorKind:case li.ColorInstanceKind:case li.MatricesIndicesKind:case li.MatricesIndicesExtraKind:case li.MatricesWeightsKind:case li.MatricesWeightsExtraKind:case li.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?li.BYTE:e instanceof Uint8Array?li.UNSIGNED_BYTE:e instanceof Int16Array?li.SHORT:e instanceof Uint16Array?li.UNSIGNED_SHORT:e instanceof Int32Array?li.INT:e instanceof Uint32Array?li.UNSIGNED_INT:li.FLOAT}static GetTypeByteLength(e){switch(e){case li.BYTE:case li.UNSIGNED_BYTE:return 1;case li.SHORT:case li.UNSIGNED_SHORT:return 2;case li.INT:case li.UNSIGNED_INT:case li.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,s,n,r,a,o){if(e instanceof Array){let n=t/4;const a=i/4;for(let t=0;t<r;t+=s){for(let i=0;i<s;i++)o(e[n+i],t+i);n+=a}}else{const l=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),h=li.GetTypeByteLength(n);for(let e=0;e<r;e+=s){let r=t;for(let t=0;t<s;t++){o(li._GetFloatValue(l,n,r,a),e+t),r+=h}t+=i}}}static _GetFloatValue(e,t,i,s){switch(t){case li.BYTE:{let t=e.getInt8(i);return s&&(t=Math.max(t/127,-1)),t}case li.UNSIGNED_BYTE:{let t=e.getUint8(i);return s&&(t/=255),t}case li.SHORT:{let t=e.getInt16(i,!0);return s&&(t=Math.max(t/32767,-1)),t}case li.UNSIGNED_SHORT:{let t=e.getUint16(i,!0);return s&&(t/=65535),t}case li.INT:return e.getInt32(i,!0);case li.UNSIGNED_INT:return e.getUint32(i,!0);case li.FLOAT:return e.getFloat32(i,!0);default:throw new Error(`Invalid component type ${t}`)}}static GetFloatData(e,t,i,s,n,r,a,o){const l=t*li.GetTypeByteLength(i),h=a*t;if(i!==li.FLOAT||n!==l){const a=new Float32Array(h);return li.ForEach(e,s,n,t,i,h,r,((e,t)=>a[t]=e)),a}if(!(e instanceof Array||e instanceof Float32Array)||0!==s||e.length!==h){if(e instanceof Array){const t=s/4;return e.slice(t,t+h)}if(e instanceof ArrayBuffer)return new Float32Array(e,s,h);{const t=e.byteOffset+s;if(3&t&&(ce.Warn("Float array must be aligned to 4-bytes border"),o=!0),o){const i=new Uint8Array(h*Float32Array.BYTES_PER_ELEMENT),s=new Uint8Array(e.buffer,t,i.length);return i.set(s),new Float32Array(i.buffer)}return new Float32Array(e.buffer,t,h)}}return o?e.slice():e}}li._Counter=0,li.BYTE=tt.BYTE,li.UNSIGNED_BYTE=tt.UNSIGNED_BYTE,li.SHORT=tt.SHORT,li.UNSIGNED_SHORT=tt.UNSIGNED_SHORT,li.INT=tt.INT,li.UNSIGNED_INT=tt.UNSIGNED_INT,li.FLOAT=tt.FLOAT,li.PositionKind=tt.PositionKind,li.NormalKind=tt.NormalKind,li.TangentKind=tt.TangentKind,li.UVKind=tt.UVKind,li.UV2Kind=tt.UV2Kind,li.UV3Kind=tt.UV3Kind,li.UV4Kind=tt.UV4Kind,li.UV5Kind=tt.UV5Kind,li.UV6Kind=tt.UV6Kind,li.ColorKind=tt.ColorKind,li.ColorInstanceKind=tt.ColorInstanceKind,li.MatricesIndicesKind=tt.MatricesIndicesKind,li.MatricesWeightsKind=tt.MatricesWeightsKind,li.MatricesIndicesExtraKind=tt.MatricesIndicesExtraKind,li.MatricesWeightsExtraKind=tt.MatricesWeightsExtraKind;class hi{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class ci{constructor(e,t,i){this.vectors=R.BuildArray(8,B.Zero),this.center=B.Zero(),this.centerWorld=B.Zero(),this.extendSize=B.Zero(),this.extendSizeWorld=B.Zero(),this.directions=R.BuildArray(3,B.Zero),this.vectorsWorld=R.BuildArray(8,B.Zero),this.minimumWorld=B.Zero(),this.maximumWorld=B.Zero(),this.minimum=B.Zero(),this.maximum=B.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,n=e.y,r=e.z,a=t.x,o=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(s,n,r),this.maximum.copyFromFloats(a,o,l),h[0].copyFromFloats(s,n,r),h[1].copyFromFloats(a,o,l),h[2].copyFromFloats(a,n,r),h[3].copyFromFloats(s,o,r),h[4].copyFromFloats(s,n,l),h[5].copyFromFloats(a,o,r),h[6].copyFromFloats(s,o,l),h[7].copyFromFloats(a,n,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||G.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=ci._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const n=s*e,r=i.scaleInPlace(.5*n),a=this.center.subtractToRef(r,t[1]),o=this.center.addToRef(r,t[2]);return this.reConstruct(a,o,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,n=this.vectorsWorld,r=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)n[e].copyFrom(r[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let s=0;s<8;++s){const a=n[s];B.TransformCoordinatesToRef(r[s],e,a),t.minimizeInPlace(a),i.maximizeInPlace(a)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}B.FromArrayToRef(e.m,0,s[0]),B.FromArrayToRef(e.m,4,s[1]),B.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return ci.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return ci.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,n=t.y,r=t.z,a=i.x,o=i.y,l=i.z,h=e.x,c=e.y,u=e.z,d=-A;return!(a-h<d||d>h-s)&&(!(o-c<d||d>c-n)&&!(l-u<d||d>u-r))}intersectsSphere(e){return ci.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,n=i.x,r=i.y,a=i.z,o=s.x,l=s.y,h=s.z,c=e.x,u=e.y,d=e.z,_=t.x,f=t.y,m=t.z;return!(o<c||n>_)&&(!(l<u||r>f)&&!(h<d||a>m))}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const n=ci._TmpVector3[0];B.ClampToRef(i,e,t,n);return B.DistanceSquared(i,n)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const n=t[i];for(let t=0;t<8;++t)if(n.dotCoordinate(e[t])>=0){s=!1;break}if(s)return!1}return!0}}ci._TmpVector3=R.BuildArray(3,B.Zero);class ui{constructor(e,t,i){this.center=B.Zero(),this.centerWorld=B.Zero(),this.minimum=B.Zero(),this.maximum=B.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=B.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*s,this._update(i||G.IdentityReadOnly)}scale(e){const t=this.radius*e,i=ui._TmpVector3,s=i[0].setAll(t),n=this.center.subtractToRef(s,i[1]),r=this.center.addToRef(s,i[2]);return this.reConstruct(n,r,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{B.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=ui._TmpVector3[0];B.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,i=this.radiusWorld;for(let s=0;s<6;s++)if(e[s].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=B.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld<t)}static Intersects(e,t){const i=B.DistanceSquared(e.centerWorld,t.centerWorld),s=e.radiusWorld+t.radiusWorld;return!(s*s<i)}static CreateFromCenterAndRadius(e,t,i){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 s=new ui(this._TmpVector3[0],this._TmpVector3[2]);return s._worldMatrix=i||G.Identity(),s}}ui._TmpVector3=R.BuildArray(3,B.Zero);const di={min:0,max:0},_i={min:0,max:0},fi=(e,t,i)=>{const s=B.Dot(t.centerWorld,e),n=Math.abs(B.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(B.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(B.Dot(t.directions[2],e))*t.extendSize.z;i.min=s-n,i.max=s+n},mi=(e,t,i)=>(fi(e,t,di),fi(e,i,_i),!(di.min>_i.max||_i.min>di.max));class pi{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new ci(e,t,i),this.boundingSphere=new ui(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}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 i=pi._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=pi._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=B.Minimize(this.minimum,e),i=B.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=X.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=X.Vector3[0];return B.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),B.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=tt.MESHES_CULLINGSTRATEGY_STANDARD){if((t===tt.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION||t===tt.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY)&&this.boundingSphere.isCenterInFrustum(e))return!0;if(!this.boundingSphere.isInFrustum(e))return!1;return!(t!==tt.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY&&t!==tt.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY)||this.boundingBox.isInFrustum(e)}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,pi._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(!ui.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!ci.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!!mi(i.directions[0],i,s)&&(!!mi(i.directions[1],i,s)&&(!!mi(i.directions[2],i,s)&&(!!mi(s.directions[0],i,s)&&(!!mi(s.directions[1],i,s)&&(!!mi(s.directions[2],i,s)&&(!!mi(B.Cross(i.directions[0],s.directions[0]),i,s)&&(!!mi(B.Cross(i.directions[0],s.directions[1]),i,s)&&(!!mi(B.Cross(i.directions[0],s.directions[2]),i,s)&&(!!mi(B.Cross(i.directions[1],s.directions[0]),i,s)&&(!!mi(B.Cross(i.directions[1],s.directions[1]),i,s)&&(!!mi(B.Cross(i.directions[1],s.directions[2]),i,s)&&(!!mi(B.Cross(i.directions[2],s.directions[0]),i,s)&&(!!mi(B.Cross(i.directions[2],s.directions[1]),i,s)&&!!mi(B.Cross(i.directions[2],s.directions[2]),i,s))))))))))))))}}pi._TmpVector3=R.BuildArray(2,B.Zero);class gi{static extractMinAndMaxIndexed(e,t,i,s,n,r){for(let a=i;a<i+s;a++){const i=3*t[a],s=e[i],o=e[i+1],l=e[i+2];n.minimizeInPlaceFromFloats(s,o,l),r.maximizeInPlaceFromFloats(s,o,l)}}static extractMinAndMax(e,t,i,s,n,r){for(let a=t,o=t*s;a<t+i;a++,o+=s){const t=e[o],i=e[o+1],s=e[o+2];n.minimizeInPlaceFromFloats(t,i,s),r.maximizeInPlaceFromFloats(t,i,s)}}}function Ei(e,t,i,s=null,n){const r=new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new B(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return n||(n=3),gi.extractMinAndMax(e,t,i,n,r,a),s&&(r.x-=r.x*s.x+s.y,r.y-=r.y*s.x+s.y,r.z-=r.z*s.x+s.y,a.x+=a.x*s.x+s.y,a.y+=a.y*s.x+s.y,a.z+=a.z*s.x+s.y),{minimum:r,maximum:a}}e([f.filter(((...[e,t])=>!Array.isArray(e)&&!Array.isArray(t)))],gi,"extractMinAndMaxIndexed",null),e([f.filter(((...[e])=>!Array.isArray(e)))],gi,"extractMinAndMax",null);class Ti{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,i=!0){this.effect=e,void 0!==t&&(this.defines=t),i&&this.drawContext?.reset()}dispose(){this.drawContext?.dispose()}}class Ai{get materialDefines(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:this._getDrawWrapper()?.defines}set materialDefines(e){(this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new Ti(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){t&&this._drawWrappers[e]?.dispose(),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,i,s=!0){const n=this._drawWrapper;n.setEffect(e,t,s),void 0!==i&&(n.materialContext=i),e||(n.defines=null,n.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)e?.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,s,n,r,a,o=!0){return new Ai(e,t,i,s,n,r,a,o)}constructor(e,t,i,s,n,r,a,o=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=n,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=r,this._renderingMesh=a||r,l&&r.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=r.subMeshes.length-1,o&&(this.refreshBoundingInfo(),r.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().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(li.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();i={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else i=function(e,t,i,s,n=null){const r=new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new B(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return gi.extractMinAndMaxIndexed(e,t,i,s,r,a),n&&(r.x-=r.x*n.x+n.y,r.y-=r.y*n.x+n.y,r.z-=r.z*n.x+n.y,a.x+=a.x*n.x+n.y,a.y+=a.y*n.x+n.y,a.z+=a.z*n.x+n.y),{minimum:r,maximum:a}}(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new pi(i.minimum,i.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 i=[];for(let t=this.indexStart;t<this.indexStart+this.indexCount;t+=3)i.push(e[t],e[t+1],e[t+1],e[t+2],e[t+2],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,i,s,n){const r=this.getMaterial();if(!r)return null;let a=3,o=!1;switch(r.fillMode){case tt.MATERIAL_PointListDrawMode:case tt.MATERIAL_LineLoopDrawMode:case tt.MATERIAL_LineStripDrawMode:case tt.MATERIAL_TriangleFanDrawMode:return null;case tt.MATERIAL_TriangleStripDrawMode:a=1,o=!0}return r.fillMode===tt.MATERIAL_LineListDrawMode?i.length?this._intersectLines(e,t,i,this._mesh.intersectionThreshold,s):this._intersectUnIndexedLines(e,t,i,this._mesh.intersectionThreshold,s):!i.length&&this._mesh._unIndexed?this._intersectUnIndexedTriangles(e,t,i,s,n):this._intersectTriangles(e,t,i,a,o,s,n)}_intersectLines(e,t,i,s,n){let r=null;for(let a=this.indexStart;a<this.indexStart+this.indexCount;a+=2){const o=t[i[a]],l=t[i[a+1]],h=e.intersectionSegment(o,l,s);if(!(h<0)&&((n||!r||h<r.distance)&&(r=new hi(null,null,h),r.faceId=a/2,n)))break}return r}_intersectUnIndexedLines(e,t,i,s,n){let r=null;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=2){const a=t[i],o=t[i+1],l=e.intersectionSegment(a,o,s);if(!(l<0)&&((n||!r||l<r.distance)&&(r=new hi(null,null,l),r.faceId=i/2,n)))break}return r}_intersectTriangles(e,t,i,s,n,r,a){let o=null,l=-1;for(let h=this.indexStart;h<this.indexStart+this.indexCount-(3-s);h+=s){l++;const s=i[h],c=i[h+1],u=i[h+2];if(n&&4294967295===u){h+=2;continue}const d=t[s],_=t[c],f=t[u];if(!d||!_||!f)continue;if(a&&!a(d,_,f,e,s,c,u))continue;const m=e.intersectsTriangle(d,_,f);if(m){if(m.distance<0)continue;if((r||!o||m.distance<o.distance)&&(o=m,o.faceId=l,r))break}}return o}_intersectUnIndexedTriangles(e,t,i,s,n){let r=null;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=3){const a=t[i],o=t[i+1],l=t[i+2];if(n&&!n(a,o,l,e,-1,-1,-1))continue;const h=e.intersectsTriangle(a,o,l);if(h){if(h.distance<0)continue;if((s||!r||h.distance<r.distance)&&(r=h,r.faceId=i/3,s))break}}return r}_rebuild(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)}clone(e,t){const i=new Ai(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,e,t,!1);if(!this.IsGlobal){const e=this.getBoundingInfo();if(!e)return i;i._boundingInfo=new pi(e.minimum,e.maximum)}return i}dispose(){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);const e=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(e,1),this.resetDrawCache()}getClassName(){return"SubMesh"}static CreateFromIndices(e,t,i,s,n,r=!0){let a=Number.MAX_VALUE,o=-Number.MAX_VALUE;const l=(n||s).getIndices();for(let e=t;e<t+i;e++){const t=l[e];t<a&&(a=t),t>o&&(o=t)}return new Ai(e,a,o-a+1,t,i,s,n,r)}}class Ri{}class vi{constructor(){var e;this.uniqueId=0,this.metadata={},this._applyTo=(e=this._applyToCoroutine.bind(this),(...t)=>Jt(e(...t))),this.uniqueId=vi._UniqueIDGenerator,vi._UniqueIDGenerator++}set(e,t){switch(e.length||ce.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case li.PositionKind:this.positions=e;break;case li.NormalKind:this.normals=e;break;case li.TangentKind:this.tangents=e;break;case li.UVKind:this.uvs=e;break;case li.UV2Kind:this.uvs2=e;break;case li.UV3Kind:this.uvs3=e;break;case li.UV4Kind:this.uvs4=e;break;case li.UV5Kind:this.uvs5=e;break;case li.UV6Kind:this.uvs6=e;break;case li.ColorKind:this.colors=e;break;case li.MatricesIndicesKind:this.matricesIndices=e;break;case li.MatricesWeightsKind:this.matricesWeights=e;break;case li.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case li.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,i){if(this.positions&&(e.setVerticesData(li.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(li.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(li.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(li.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(li.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(li.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(li.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(li.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(li.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(li.ColorKind,this.colors,t),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(li.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(li.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(li.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(li.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const t=e;t.subMeshes=[];for(const e of this.materialInfos)new Ai(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,t)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(li.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(li.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(li.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(li.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(li.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(li.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(li.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(li.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(li.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(li.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(li.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(li.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(li.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(li.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const n=X.Vector3[0],r=X.Vector3[1];for(let a=i;a<i+s;a+=3)B.FromArrayToRef(e,a,n),B.TransformCoordinatesToRef(n,t,r),e[a]=r.x,e[a+1]=r.y,e[a+2]=r.z}static _TransformVector3Normals(e,t,i=0,s=e.length){const n=X.Vector3[0],r=X.Vector3[1];for(let a=i;a<i+s;a+=3)B.FromArrayToRef(e,a,n),B.TransformNormalToRef(n,t,r),e[a]=r.x,e[a+1]=r.y,e[a+2]=r.z}static _TransformVector4Normals(e,t,i=0,s=e.length){const n=X.Vector4[0],r=X.Vector4[1];for(let a=i;a<i+s;a+=4)U.FromArrayToRef(e,a,n),U.TransformNormalToRef(n,t,r),e[a]=r.x,e[a+1]=r.y,e[a+2]=r.z,e[a+3]=r.w}static _FlipFaces(e,t=0,i=e.length){for(let s=t;s<t+i;s+=3){const t=e[s+1];e[s+1]=e[s+2],e[s+2]=t}}transform(e){const t=e.determinant()<0;return this.positions&&vi._TransformVector3Coordinates(this.positions,e),this.normals&&vi._TransformVector3Normals(this.normals,e),this.tangents&&vi._TransformVector4Normals(this.tangents,e),t&&this.indices&&vi._FlipFaces(this.indices),this}splitBasedOnMaterialID(){if(!this.materialInfos||this.materialInfos.length<2)return[this];const e=[];for(const t of this.materialInfos){const i=new vi;if(this.positions&&(i.positions=this.positions.slice(3*t.verticesStart,3*(t.verticesCount+t.verticesStart))),this.normals&&(i.normals=this.normals.slice(3*t.verticesStart,3*(t.verticesCount+t.verticesStart))),this.tangents&&(i.tangents=this.tangents.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.colors&&(i.colors=this.colors.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.uvs&&(i.uvs=this.uvs.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs2&&(i.uvs2=this.uvs2.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs3&&(i.uvs3=this.uvs3.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs4&&(i.uvs4=this.uvs4.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs5&&(i.uvs5=this.uvs5.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs6&&(i.uvs6=this.uvs6.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.matricesIndices&&(i.matricesIndices=this.matricesIndices.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.matricesIndicesExtra&&(i.matricesIndicesExtra=this.matricesIndicesExtra.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.matricesWeights&&(i.matricesWeights=this.matricesWeights.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.matricesWeightsExtra&&(i.matricesWeightsExtra=this.matricesWeightsExtra.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.indices){i.indices=[];for(let e=t.indexStart;e<t.indexStart+t.indexCount;e++)i.indices.push(this.indices[e]-t.verticesStart)}const s=new Ri;s.indexStart=0,s.indexCount=i.indices?i.indices.length:0,s.materialIndex=t.materialIndex,s.verticesStart=0,s.verticesCount=(i.positions?i.positions.length:0)/3,i.materialInfos=[s],e.push(i)}return e}merge(e,t=!1,i=!1,s=!1,n=!1){const r=Array.isArray(e)?e.map((e=>({vertexData:e}))):[{vertexData:e}];return Jt(this._mergeCoroutine(void 0,r,t,!1,i,s,n))}*_mergeCoroutine(e,t,i=!1,s,n,r=!1,a=!1){this._validate();let o=t.map((e=>e.vertexData)),l=this;if(a)for(const e of o)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 o)if(e)if(a)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(r){let i=0,s=0,n=0;const r=[];let a=null;const h=[];for(const t of this.splitBasedOnMaterialID())h.push({vertexData:t,transform:e});for(const e of t)if(e.vertexData)for(const t of e.vertexData.splitBasedOnMaterialID())h.push({vertexData:t,transform:e.transform});h.sort(((e,t)=>{const i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,s=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>s?1:i===s?0:-1}));for(const e of h){const t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,a&&a.materialIndex===i)a.indexCount+=t.indices.length,a.verticesCount+=t.positions.length/3;else{const e=new Ri;e.materialIndex=i,e.indexStart=s,e.indexCount=t.indices.length,e.verticesStart=n,e.verticesCount=t.positions.length/3,r.push(e),a=e}s+=t.indices.length,n+=t.positions.length/3}const c=h.splice(0,1)[0];l=c.vertexData,e=c.transform,o=h.map((e=>e.vertexData)),t=h,this.materialInfos=r}const h=o.reduce(((e,t)=>e+(t.indices?.length??0)),l.indices?.length??0);let c=n||o.some((e=>e.indices===l.indices))?l.indices?.slice():l.indices;if(h>0){let n=c?.length??0;if(c||(c=new Array(h)),c.length!==h){if(Array.isArray(c))c.length=h;else{const e=i||c instanceof Uint32Array?new Uint32Array(h):new Uint16Array(h);e.set(c),c=e}e&&e.determinant()<0&&vi._FlipFaces(c,0,n)}let r=l.positions?l.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t<e.indices.length;t++)c[n+t]=e.indices[t]+r;i&&i.determinant()<0&&vi._FlipFaces(c,n,e.indices.length),r+=e.positions.length/3,n+=e.indices.length,s&&(yield)}}return this.indices=c,this.positions=vi._MergeElement(li.PositionKind,l.positions,e,t.map((e=>[e.vertexData.positions,e.transform]))),s&&(yield),l.normals&&(this.normals=vi._MergeElement(li.NormalKind,l.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),s&&(yield)),l.tangents&&(this.tangents=vi._MergeElement(li.TangentKind,l.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),s&&(yield)),l.uvs&&(this.uvs=vi._MergeElement(li.UVKind,l.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),s&&(yield)),l.uvs2&&(this.uvs2=vi._MergeElement(li.UV2Kind,l.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),s&&(yield)),l.uvs3&&(this.uvs3=vi._MergeElement(li.UV3Kind,l.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),s&&(yield)),l.uvs4&&(this.uvs4=vi._MergeElement(li.UV4Kind,l.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),s&&(yield)),l.uvs5&&(this.uvs5=vi._MergeElement(li.UV5Kind,l.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),s&&(yield)),l.uvs6&&(this.uvs6=vi._MergeElement(li.UV6Kind,l.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),s&&(yield)),l.colors&&(this.colors=vi._MergeElement(li.ColorKind,l.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),(void 0!==l.hasVertexAlpha||t.some((e=>void 0!==e.vertexData.hasVertexAlpha)))&&(this.hasVertexAlpha=l.hasVertexAlpha||t.some((e=>e.vertexData.hasVertexAlpha))),s&&(yield)),l.matricesIndices&&(this.matricesIndices=vi._MergeElement(li.MatricesIndicesKind,l.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),s&&(yield)),l.matricesWeights&&(this.matricesWeights=vi._MergeElement(li.MatricesWeightsKind,l.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),s&&(yield)),l.matricesIndicesExtra&&(this.matricesIndicesExtra=vi._MergeElement(li.MatricesIndicesExtraKind,l.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),s&&(yield)),l.matricesWeightsExtra&&(this.matricesWeightsExtra=vi._MergeElement(li.MatricesWeightsExtraKind,l.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform])))),this}static _MergeElement(e,t,i,s){const n=s.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==n.length)return t;if(!t)return this._MergeElement(e,n[0][0],n[0][1],n.slice(1));const r=n.reduce(((e,t)=>e+t[0].length),t.length),a=e===li.PositionKind?vi._TransformVector3Coordinates:e===li.NormalKind?vi._TransformVector3Normals:e===li.TangentKind?vi._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(r);e.set(t),i&&a(e,i,0,t.length);let s=t.length;for(const[t,i]of n)e.set(t,s),i&&a(e,i,s,t.length),s+=t.length;return e}{const e=new Array(r);for(let i=0;i<t.length;i++)e[i]=t[i];i&&a(e,i,0,t.length);let s=t.length;for(const[t,i]of n){for(let i=0;i<t.length;i++)e[s+i]=t[i];i&&a(e,i,s,t.length),s+=t.length}return e}}_validate(){if(!this.positions)throw new Ie("Positions are required",ge);const e=(e,t)=>{const i=li.DeduceStride(e);if(t.length%i!=0)throw new Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(li.PositionKind,this.positions),i=(i,s)=>{const n=e(i,s);if(n!==t)throw new Error("The "+i+"s element count ("+n+") does not match the positions count ("+t+")")};this.normals&&i(li.NormalKind,this.normals),this.tangents&&i(li.TangentKind,this.tangents),this.uvs&&i(li.UVKind,this.uvs),this.uvs2&&i(li.UV2Kind,this.uvs2),this.uvs3&&i(li.UV3Kind,this.uvs3),this.uvs4&&i(li.UV4Kind,this.uvs4),this.uvs5&&i(li.UV5Kind,this.uvs5),this.uvs6&&i(li.UV6Kind,this.uvs6),this.colors&&i(li.ColorKind,this.colors),this.matricesIndices&&i(li.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(li.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(li.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(li.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return vi.Parse(e)}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.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return vi._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return vi._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new vi;if(e.isVerticesDataPresent(li.PositionKind)&&(s.positions=e.getVerticesData(li.PositionKind,t,i)),e.isVerticesDataPresent(li.NormalKind)&&(s.normals=e.getVerticesData(li.NormalKind,t,i)),e.isVerticesDataPresent(li.TangentKind)&&(s.tangents=e.getVerticesData(li.TangentKind,t,i)),e.isVerticesDataPresent(li.UVKind)&&(s.uvs=e.getVerticesData(li.UVKind,t,i)),e.isVerticesDataPresent(li.UV2Kind)&&(s.uvs2=e.getVerticesData(li.UV2Kind,t,i)),e.isVerticesDataPresent(li.UV3Kind)&&(s.uvs3=e.getVerticesData(li.UV3Kind,t,i)),e.isVerticesDataPresent(li.UV4Kind)&&(s.uvs4=e.getVerticesData(li.UV4Kind,t,i)),e.isVerticesDataPresent(li.UV5Kind)&&(s.uvs5=e.getVerticesData(li.UV5Kind,t,i)),e.isVerticesDataPresent(li.UV6Kind)&&(s.uvs6=e.getVerticesData(li.UV6Kind,t,i)),e.isVerticesDataPresent(li.ColorKind)){const n=e.geometry||e,r=n.getVertexBuffer(li.ColorKind),a=n.getVerticesData(li.ColorKind,t,i);if(3===r.getSize()){const e=new Float32Array(4*a.length/3);for(let t=0,i=0;t<a.length;t+=3,i+=4)e[i]=a[t],e[i+1]=a[t+1],e[i+2]=a[t+2],e[i+3]=1;s.colors=e}else{if(4!==r.getSize())throw new Error(`Unexpected number of color components: ${r.getSize()}`);s.colors=a}}return e.isVerticesDataPresent(li.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(li.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(li.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(li.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(li.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(li.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(li.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(li.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw W("ribbonBuilder")}static CreateBox(e){throw W("boxBuilder")}static CreateTiledBox(e){throw W("tiledBoxBuilder")}static CreateTiledPlane(e){throw W("tiledPlaneBuilder")}static CreateSphere(e){throw W("sphereBuilder")}static CreateCylinder(e){throw W("cylinderBuilder")}static CreateTorus(e){throw W("torusBuilder")}static CreateLineSystem(e){throw W("linesBuilder")}static CreateDashedLines(e){throw W("linesBuilder")}static CreateGround(e){throw W("groundBuilder")}static CreateTiledGround(e){throw W("groundBuilder")}static CreateGroundFromHeightMap(e){throw W("groundBuilder")}static CreatePlane(e){throw W("planeBuilder")}static CreateDisc(e){throw W("discBuilder")}static CreatePolygon(e,t,i,s,n,r,a){throw W("polygonBuilder")}static CreateIcoSphere(e){throw W("icoSphereBuilder")}static CreatePolyhedron(e){throw W("polyhedronBuilder")}static CreateCapsule(e={orientation:B.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw W("capsuleBuilder")}static CreateTorusKnot(e){throw W("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let n=0,r=0,a=0,o=0,l=0,h=0,c=0,u=0,d=0,_=0,f=0,m=0,p=0,g=0,E=0,T=0,A=0,R=0,v=0,I=0,S=!1,C=!1,b=!1,y=!1,M=1,x=0,O=null;s&&(S=!!s.facetNormals,C=!!s.facetPositions,b=!!s.facetPartitioning,M=!0===s.useRightHandedSystem?-1:1,x=s.ratio||0,y=!!s.depthSort,O=s.distanceTo,y&&void 0===O&&(O=B.Zero()));let D=0,P=0,N=0,L=0;for(b&&s&&s.bbSize&&(D=s.subDiv.X*x/s.bbSize.x,P=s.subDiv.Y*x/s.bbSize.y,N=s.subDiv.Z*x/s.bbSize.z,L=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),n=0;n<e.length;n++)i[n]=0;const F=t.length/3|0;for(n=0;n<F;n++){if(m=3*t[3*n],p=m+1,g=m+2,E=3*t[3*n+1],T=E+1,A=E+2,R=3*t[3*n+2],v=R+1,I=R+2,r=e[m]-e[E],a=e[p]-e[T],o=e[g]-e[A],l=e[R]-e[E],h=e[v]-e[T],c=e[I]-e[A],u=M*(a*c-o*h),d=M*(o*l-r*c),_=M*(r*h-a*l),f=Math.sqrt(u*u+d*d+_*_),f=0===f?1:f,u/=f,d/=f,_/=f,S&&s&&(s.facetNormals[n].x=u,s.facetNormals[n].y=d,s.facetNormals[n].z=_),C&&s&&(s.facetPositions[n].x=(e[m]+e[E]+e[R])/3,s.facetPositions[n].y=(e[p]+e[T]+e[v])/3,s.facetPositions[n].z=(e[g]+e[A]+e[I])/3),b&&s){const t=Math.floor((s.facetPositions[n].x-s.bInfo.minimum.x*x)*D),i=Math.floor((s.facetPositions[n].y-s.bInfo.minimum.y*x)*P),r=Math.floor((s.facetPositions[n].z-s.bInfo.minimum.z*x)*N),a=Math.floor((e[m]-s.bInfo.minimum.x*x)*D),o=Math.floor((e[p]-s.bInfo.minimum.y*x)*P),l=Math.floor((e[g]-s.bInfo.minimum.z*x)*N),h=Math.floor((e[E]-s.bInfo.minimum.x*x)*D),c=Math.floor((e[T]-s.bInfo.minimum.y*x)*P),u=Math.floor((e[A]-s.bInfo.minimum.z*x)*N),d=Math.floor((e[R]-s.bInfo.minimum.x*x)*D),_=Math.floor((e[v]-s.bInfo.minimum.y*x)*P),f=Math.floor((e[I]-s.bInfo.minimum.z*x)*N),S=a+s.subDiv.max*o+L*l,C=h+s.subDiv.max*c+L*u,b=d+s.subDiv.max*_+L*f,y=t+s.subDiv.max*i+L*r;s.facetPartitioning[y]=s.facetPartitioning[y]?s.facetPartitioning[y]:new Array,s.facetPartitioning[S]=s.facetPartitioning[S]?s.facetPartitioning[S]:new Array,s.facetPartitioning[C]=s.facetPartitioning[C]?s.facetPartitioning[C]:new Array,s.facetPartitioning[b]=s.facetPartitioning[b]?s.facetPartitioning[b]:new Array,s.facetPartitioning[S].push(n),C!=S&&s.facetPartitioning[C].push(n),b!=C&&b!=S&&s.facetPartitioning[b].push(n),y!=S&&y!=C&&y!=b&&s.facetPartitioning[y].push(n)}if(y&&s&&s.facetPositions){const e=s.depthSortedFacets[n];e.ind=3*n,e.sqDistance=B.DistanceSquared(s.facetPositions[n],O)}i[m]+=u,i[p]+=d,i[g]+=_,i[E]+=u,i[T]+=d,i[A]+=_,i[R]+=u,i[v]+=d,i[I]+=_}for(n=0;n<i.length/3;n++)u=i[3*n],d=i[3*n+1],_=i[3*n+2],f=Math.sqrt(u*u+d*d+_*_),f=0===f?1:f,u/=f,d/=f,_/=f,i[3*n]=u,i[3*n+1]=d,i[3*n+2]=_}static _ComputeSides(e,t,i,s,n,r,a){const o=i.length,l=s.length;let h,c;switch(e=e||vi.DEFAULTSIDE){case vi.FRONTSIDE:break;case vi.BACKSIDE:for(h=0;h<o;h+=3){const e=i[h];i[h]=i[h+2],i[h+2]=e}for(c=0;c<l;c++)s[c]=-s[c];break;case vi.DOUBLESIDE:{const e=t.length,u=e/3;for(let i=0;i<e;i++)t[e+i]=t[i];for(h=0;h<o;h+=3)i[h+o]=i[h+2]+u,i[h+1+o]=i[h+1]+u,i[h+2+o]=i[h]+u;for(c=0;c<l;c++)s[l+c]=-s[c];const d=n.length;let _=0;for(_=0;_<d;_++)n[_+d]=n[_];for(r=r||new U(0,0,1,1),a=a||new U(0,0,1,1),_=0,h=0;h<d/2;h++)n[_]=r.x+(r.z-r.x)*n[_],n[_+1]=r.y+(r.w-r.y)*n[_+1],n[_+d]=a.x+(a.z-a.x)*n[_+d],n[_+d+1]=a.y+(a.w-a.y)*n[_+d+1],_+=2;break}}}static Parse(e){const t=new vi,i=e.positions;i&&t.set(i,li.PositionKind);const s=e.normals;s&&t.set(s,li.NormalKind);const n=e.tangents;n&&t.set(n,li.TangentKind);const r=e.uvs;r&&t.set(r,li.UVKind);const a=e.uvs2;a&&t.set(a,li.UV2Kind);const o=e.uvs3;o&&t.set(o,li.UV3Kind);const l=e.uvs4;l&&t.set(l,li.UV4Kind);const h=e.uvs5;h&&t.set(h,li.UV5Kind);const c=e.uvs6;c&&t.set(c,li.UV6Kind);const u=e.colors;u&&(t.set(ee.CheckColors4(u,i.length/3),li.ColorKind),void 0!==e.hasVertexAlpha&&(t.hasVertexAlpha=e.hasVertexAlpha));const d=e.matricesIndices;d&&t.set(d,li.MatricesIndicesKind);const _=e.matricesWeights;_&&t.set(_,li.MatricesWeightsKind);const f=e.indices;f&&(t.indices=f);const m=e.materialInfos;if(m){t.materialInfos=[];for(const e of m){const i=new Ri;i.indexCount=e.indexCount,i.indexStart=e.indexStart,i.verticesCount=e.verticesCount,i.verticesStart=e.verticesStart,i.materialIndex=e.materialIndex,t.materialInfos.push(i)}}return t}static ImportVertexData(e,t){const i=vi.Parse(e);t.setAllVerticesData(i,e.updatable)}}vi.FRONTSIDE=0,vi.BACKSIDE=1,vi.DOUBLESIDE=2,vi.DEFAULTSIDE=0,vi._UniqueIDGenerator=0,e([f.filter(((...[e])=>!Array.isArray(e)))],vi,"_TransformVector3Coordinates",null),e([f.filter(((...[e])=>!Array.isArray(e)))],vi,"_TransformVector3Normals",null),e([f.filter(((...[e])=>!Array.isArray(e)))],vi,"_TransformVector4Normals",null),e([f.filter(((...[e])=>!Array.isArray(e)))],vi,"_FlipFaces",null);class Ii{static get ForceFullSceneLoadingForIncremental(){return Ii._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Ii._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Ii._ShowLoadingScreen}static set ShowLoadingScreen(e){Ii._ShowLoadingScreen=e}static get loggingLevel(){return Ii._LoggingLevel}static set loggingLevel(e){Ii._LoggingLevel=e}static get CleanBoneMatrixWeights(){return Ii._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Ii._CleanBoneMatrixWeights=e}}Ii._ForceFullSceneLoadingForIncremental=!1,Ii._ShowLoadingScreen=!0,Ii._CleanBoneMatrixWeights=!1,Ii._LoggingLevel=tt.SCENELOADER_NO_LOGGING;class Si{}Si.UseOpenGLOrientationForUV=!1;class Ci{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 Ci(Ci.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,n=null){this.delayLoadState=tt.DELAYLOADSTATE_NONE,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||M.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=s,i?this.setAllVerticesData(i,s):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),n&&(this.applyToMesh(n),n.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return this.delayLoadState===tt.DELAYLOADSTATE_LOADED||this.delayLoadState===tt.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,i=!1,s){i&&Array.isArray(t)&&(t=new Float32Array(t));const n=new li(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:s,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(n)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const s=e.getKind();this._vertexBuffers[s]&&i&&this._vertexBuffers[s].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[s]=e;const n=this._meshes,r=n.length;if(s===li.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const i=this._extend&&this._extend.minimum||new B(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=this._extend&&this._extend.maximum||new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e<r;e++){const t=n[e];t.buildBoundingInfo(i,s),t._createGlobalSubMesh(t.isUnIndexed),t.computeWorldMatrix(!0),t.synchronizeInstances()}}this._notifyUpdate(s)}updateVerticesDataDirectly(e,t,i,s=!1){const n=this.getVertexBuffer(e);n&&(n.updateDirectly(t,i,s),this._notifyUpdate(e))}updateVerticesData(e,t,i=!1){const s=this.getVertexBuffer(e);s&&(s.update(t),e===li.PositionKind&&this._updateBoundingInfo(i,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,i,s){if(!e)return;void 0===t&&(t=this._indexBuffer);const n=this.getVertexBuffers();if(!n)return;if(t!=this._indexBuffer||!this._vertexArrayObjects&&!s)return void this._engine.bindBuffers(n,t,e,i);const r=s||this._vertexArrayObjects,a=this._engine;r[e.key]||(r[e.key]=a.recordVertexArrayObject(n,t,e,i)),a.bindVertexArrayObject(r[e.key],t)}getTotalVertices(){return this.isReady()?this._totalVertices:0}getVerticesData(e,t,i){const s=this.getVertexBuffer(e);return s?s.getFloatData(this._totalVertices,i||t&&1!==this._meshes.length):null}copyVerticesData(e,t){const i=this.getVertexBuffer(e);if(!i)return;t[e]||=new Float32Array(this._totalVertices*i.getSize());const s=i.getData();s&&function(e,t,i,s,n,r,a,o){const l=t*li.GetTypeByteLength(i),h=a*t;if(o.length!==h)throw new Error("Output length is not valid");if(i===li.FLOAT&&n===l)if(e instanceof Array){const t=s/4;o.set(e,t)}else if(e instanceof ArrayBuffer){const t=new Float32Array(e,s,h);o.set(t)}else{const t=e.byteOffset+s;if(t%4)return ce.Warn("CopyFloatData: copied misaligned data."),void o.set(new Float32Array(e.buffer.slice(t,t+4*h)));const i=new Float32Array(e.buffer,t,h);o.set(i)}else li.ForEach(e,s,n,t,i,h,r,((e,t)=>o[t]=e))}(s,i.getSize(),i.type,i.byteOffset,i.byteStride,i.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,i=!1){if(this._indexBuffer)if(this._indexBufferIsUpdatable){const s=e.length!==this._indices.length;if(i||(this._indices=e.slice()),this._engine.updateDynamicIndexBuffer(this._indexBuffer,e,t),s)for(const e of this._meshes)e._createGlobalSubMesh(!0)}else this.setIndices(e,null,!0)}setIndexBuffer(e,t,i){this._indices=[],this._indexBufferIsUpdatable=!1,this._indexBuffer=e,this._totalVertices=t,this._totalIndices=i,e.is32Bits||=this._totalIndices>65535;for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),null!=t&&(this._totalVertices=t);for(const e of this._meshes)e._createGlobalSubMesh(!0),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 i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}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 i=this._meshes,s=i.indexOf(e);-1!==s&&(i.splice(s,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.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(li.PositionKind)))return;this._extend=Ei(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===li.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&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!==tt.DELAYLOADSTATE_LOADING&&(this.isReady()?t&&t():(this.delayLoadState=tt.DELAYLOADSTATE_LOADING,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=tt.DELAYLOADSTATE_LOADED,this._delayInfo=[],e.removePendingData(this);const s=this._meshes,n=s.length;for(let e=0;e<n;e++)this._applyToMesh(s[e]);t&&t()}),void 0,!0))}toLeftHanded(){const e=this.getIndices(!1);if(null!=e&&e.length>0){for(let t=0;t<e.length;t+=3){const i=e[t+0];e[t+0]=e[t+2],e[t+2]=i}this.setIndices(e)}const t=this.getVerticesData(li.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(li.PositionKind,t,!1)}const i=this.getVerticesData(li.NormalKind,!1);if(null!=i&&i.length>0){for(let e=0;e<i.length;e+=3)i[e+2]=-i[e+2];this.setVerticesData(li.NormalKind,i,!1)}}_resetPointsArrayCache(){this._positions=null}_generatePointsArray(){if(this._positions)return!0;const e=this.getVerticesData(li.PositionKind);if(!e||0===e.length)return!1;for(let t=3*this._positionsCache.length,i=this._positionsCache.length;t<e.length;t+=3,++i)this._positionsCache[i]=B.FromArray(e,t);for(let t=0,i=0;t<e.length;t+=3,++i)this._positionsCache[i].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 i=0;i<t;i++)e[i]._invalidateInstanceVertexArrayObject()}}dispose(){const e=this._meshes,t=e.length;let i;for(i=0;i<t;i++)this.releaseForMesh(e[i]);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=tt.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 vi;t.indices=[];const i=this.getIndices();if(i)for(let e=0;e<i.length;e++)t.indices.push(i[e]);let s,n=!1,r=!1;for(s in this._vertexBuffers){const e=this.getVerticesData(s);if(e&&(e instanceof Float32Array?t.set(new Float32Array(e),s):t.set(e.slice(0),s),!r)){const e=this.getVertexBuffer(s);e&&(n=e.isUpdatable(),r=!n)}}const a=new Ci(e,this._scene,t,n);for(s in a.delayLoadState=this.delayLoadState,a.delayLoadingFile=this.delayLoadingFile,a._delayLoadingFunction=this._delayLoadingFunction,this._delayInfo)a._delayInfo=a._delayInfo||[],a._delayInfo.push(s);return a._boundingInfo=new pi(this._extend.minimum,this._extend.maximum),a}serialize(){const e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,K&&K.HasTags(this)&&(e.tags=K.GetTags(this)),e}_toNumberArray(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)}clearCachedData(){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(li.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(li.PositionKind)),this.isVertexBufferUpdatable(li.PositionKind)&&(e.positions._updatable=!0)),this.isVerticesDataPresent(li.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(li.NormalKind)),this.isVertexBufferUpdatable(li.NormalKind)&&(e.normals._updatable=!0)),this.isVerticesDataPresent(li.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(li.TangentKind)),this.isVertexBufferUpdatable(li.TangentKind)&&(e.tangents._updatable=!0)),this.isVerticesDataPresent(li.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(li.UVKind)),this.isVertexBufferUpdatable(li.UVKind)&&(e.uvs._updatable=!0)),this.isVerticesDataPresent(li.UV2Kind)&&(e.uvs2=this._toNumberArray(this.getVerticesData(li.UV2Kind)),this.isVertexBufferUpdatable(li.UV2Kind)&&(e.uvs2._updatable=!0)),this.isVerticesDataPresent(li.UV3Kind)&&(e.uvs3=this._toNumberArray(this.getVerticesData(li.UV3Kind)),this.isVertexBufferUpdatable(li.UV3Kind)&&(e.uvs3._updatable=!0)),this.isVerticesDataPresent(li.UV4Kind)&&(e.uvs4=this._toNumberArray(this.getVerticesData(li.UV4Kind)),this.isVertexBufferUpdatable(li.UV4Kind)&&(e.uvs4._updatable=!0)),this.isVerticesDataPresent(li.UV5Kind)&&(e.uvs5=this._toNumberArray(this.getVerticesData(li.UV5Kind)),this.isVertexBufferUpdatable(li.UV5Kind)&&(e.uvs5._updatable=!0)),this.isVerticesDataPresent(li.UV6Kind)&&(e.uvs6=this._toNumberArray(this.getVerticesData(li.UV6Kind)),this.isVertexBufferUpdatable(li.UV6Kind)&&(e.uvs6._updatable=!0)),this.isVerticesDataPresent(li.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(li.ColorKind)),this.isVertexBufferUpdatable(li.ColorKind)&&(e.colors._updatable=!0)),this.isVerticesDataPresent(li.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(li.MatricesIndicesKind)),e.matricesIndices._isExpanded=!0,this.isVertexBufferUpdatable(li.MatricesIndicesKind)&&(e.matricesIndices._updatable=!0)),this.isVerticesDataPresent(li.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(li.MatricesWeightsKind)),this.isVertexBufferUpdatable(li.MatricesWeightsKind)&&(e.matricesWeights._updatable=!0)),e.indices=this._toNumberArray(this.getIndices()),e}static ExtractFromMesh(e,t){const i=e._geometry;return i?i.copy(t):null}static RandomId(){return Qt.RandomId()}static _GetGeometryByLoadedUniqueId(e,t){for(let i=0;i<t.geometries.length;i++)if(t.geometries[i]._loadedUniqueId===e)return t.geometries[i];return null}static _ImportGeometry(e,t){const i=t.getScene(),s=e.geometryUniqueId,n=e.geometryId;if(s||n){const e=s?this._GetGeometryByLoadedUniqueId(s,i):i.getGeometryById(n);e&&e.applyToMesh(t)}else if(e instanceof ArrayBuffer){const i=t._binaryInfo;if(i.positionsAttrDesc&&i.positionsAttrDesc.count>0){const s=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(li.PositionKind,s,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const s=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(li.NormalKind,s,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const s=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(li.TangentKind,s,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const s=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(Si.UseOpenGLOrientationForUV)for(let e=1;e<s.length;e+=2)s[e]=1-s[e];t.setVerticesData(li.UVKind,s,!1)}if(i.uvs2AttrDesc&&i.uvs2AttrDesc.count>0){const s=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(Si.UseOpenGLOrientationForUV)for(let e=1;e<s.length;e+=2)s[e]=1-s[e];t.setVerticesData(li.UV2Kind,s,!1)}if(i.uvs3AttrDesc&&i.uvs3AttrDesc.count>0){const s=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(Si.UseOpenGLOrientationForUV)for(let e=1;e<s.length;e+=2)s[e]=1-s[e];t.setVerticesData(li.UV3Kind,s,!1)}if(i.uvs4AttrDesc&&i.uvs4AttrDesc.count>0){const s=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(Si.UseOpenGLOrientationForUV)for(let e=1;e<s.length;e+=2)s[e]=1-s[e];t.setVerticesData(li.UV4Kind,s,!1)}if(i.uvs5AttrDesc&&i.uvs5AttrDesc.count>0){const s=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(Si.UseOpenGLOrientationForUV)for(let e=1;e<s.length;e+=2)s[e]=1-s[e];t.setVerticesData(li.UV5Kind,s,!1)}if(i.uvs6AttrDesc&&i.uvs6AttrDesc.count>0){const s=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(Si.UseOpenGLOrientationForUV)for(let e=1;e<s.length;e+=2)s[e]=1-s[e];t.setVerticesData(li.UV6Kind,s,!1)}if(i.colorsAttrDesc&&i.colorsAttrDesc.count>0){const s=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(li.ColorKind,s,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),n=[];for(let e=0;e<s.length;e++){const t=s[e];n.push(255&t),n.push((65280&t)>>8),n.push((16711680&t)>>16),n.push(t>>24&255)}t.setVerticesData(li.MatricesIndicesKind,n,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),n=[];for(let e=0;e<s.length;e++){const t=s[e];n.push(255&t),n.push((65280&t)>>8),n.push((16711680&t)>>16),n.push(t>>24&255)}t.setVerticesData(li.MatricesIndicesExtraKind,n,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const s=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(li.MatricesWeightsKind,s,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){const s=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(s,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){const s=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e<i.subMeshesAttrDesc.count;e++){const i=s[5*e+0],n=s[5*e+1],r=s[5*e+2],a=s[5*e+3],o=s[5*e+4];Ai.AddToMesh(i,n,r,a,o,t)}}}else if(e.positions&&e.normals&&e.indices){if(t.setVerticesData(li.PositionKind,e.positions,e.positions._updatable),t.setVerticesData(li.NormalKind,e.normals,e.normals._updatable),e.tangents&&t.setVerticesData(li.TangentKind,e.tangents,e.tangents._updatable),e.uvs&&t.setVerticesData(li.UVKind,e.uvs,e.uvs._updatable),e.uvs2&&t.setVerticesData(li.UV2Kind,e.uvs2,e.uvs2._updatable),e.uvs3&&t.setVerticesData(li.UV3Kind,e.uvs3,e.uvs3._updatable),e.uvs4&&t.setVerticesData(li.UV4Kind,e.uvs4,e.uvs4._updatable),e.uvs5&&t.setVerticesData(li.UV5Kind,e.uvs5,e.uvs5._updatable),e.uvs6&&t.setVerticesData(li.UV6Kind,e.uvs6,e.uvs6._updatable),e.colors&&t.setVerticesData(li.ColorKind,ee.CheckColors4(e.colors,e.positions.length/3),e.colors._updatable),e.matricesIndices)if(e.matricesIndices._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(li.MatricesIndicesKind,e.matricesIndices,e.matricesIndices._updatable);else{const i=[];for(let t=0;t<e.matricesIndices.length;t++){const s=e.matricesIndices[t];i.push(255&s),i.push((65280&s)>>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(li.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(li.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t<e.matricesIndicesExtra.length;t++){const s=e.matricesIndicesExtra[t];i.push(255&s),i.push((65280&s)>>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(li.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(Ci._CleanMatricesWeights(e,t),t.setVerticesData(li.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(li.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i<e.subMeshes.length;i++){const s=e.subMeshes[i];Ai.AddToMesh(s.materialIndex,s.verticesStart,s.verticesCount,s.indexStart,s.indexCount,t)}}t._shouldGenerateFlatShading&&(t.convertToFlatShadedMesh(),t._shouldGenerateFlatShading=!1),t.computeWorldMatrix(!0),i.onMeshImportedObservable.notifyObservers(t)}static _CleanMatricesWeights(e,t){const i=.001;if(!Ii.CleanBoneMatrixWeights)return;let s=0;if(!(e.skeletonId>-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;s=i.bones.length}const n=t.getVerticesData(li.MatricesIndicesKind),r=t.getVerticesData(li.MatricesIndicesExtraKind),a=e.matricesWeights,o=e.matricesWeightsExtra,l=e.numBoneInfluencer,h=a.length;for(let e=0;e<h;e+=4){let t=0,h=-1;for(let s=0;s<4;s++){const n=a[e+s];t+=n,n<i&&h<0&&(h=s)}if(o)for(let s=0;s<4;s++){const n=o[e+s];t+=n,n<i&&h<0&&(h=s+4)}if((h<0||h>l-1)&&(h=l-1),t>i){const i=1/t;for(let t=0;t<4;t++)a[e+t]*=i;if(o)for(let t=0;t<4;t++)o[e+t]*=i}else h>=4?(o[e+h-4]=1-t,r[e+h-4]=s):(a[e+h]=1-t,n[e+h]=s)}t.setVerticesData(li.MatricesIndicesKind,n),e.matricesWeightsExtra&&t.setVerticesData(li.MatricesIndicesExtraKind,r)}static Parse(e,t,i){const s=new Ci(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,K&&K.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=tt.DELAYLOADSTATE_NOTLOADED,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new pi(B.FromArray(e.boundingBoxMinimum),B.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(li.UVKind),e.hasUVs2&&s._delayInfo.push(li.UV2Kind),e.hasUVs3&&s._delayInfo.push(li.UV3Kind),e.hasUVs4&&s._delayInfo.push(li.UV4Kind),e.hasUVs5&&s._delayInfo.push(li.UV5Kind),e.hasUVs6&&s._delayInfo.push(li.UV6Kind),e.hasColors&&s._delayInfo.push(li.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(li.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(li.MatricesWeightsKind),s._delayLoadingFunction=vi.ImportVertexData):vi.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class bi{constructor(){this.shaderLanguage=0}postProcessor(e,t,i,s,n){if(n.drawBuffersExtensionDisabled){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}const yi=/(flat\s)?\s*varying\s*.*/;class Mi{constructor(){this.shaderLanguage=0}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return yi.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=-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("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);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,(s||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else{if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}return e}}class xi extends ai{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()}}class Di{}class Pi extends St{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return mt.ShadersRepository}static set ShadersRepository(e){mt.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,i,s){if(i=i||{},super(t??i.antialias,i,s),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 n=null;if(e.getContext){if(n=e,this._renderingCanvas=n,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of Pi.ExceptionList){const s=t.key,n=t.targets;if(new RegExp(s).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,s=t.captureConstraint,n=new RegExp(i).exec(e);if(n&&n.length>0){if(parseInt(n[n.length-1])>=s)continue}}for(const e of n)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,ce.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost((()=>this._initGLContext()))},n.addEventListener("webglcontextlost",this._onContextLost,!1),n.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=n.getContext("webgl2",i)||n.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!n)throw new Error("The provided canvas is null or undefined.");try{this._gl=n.getContext("webgl",i)||n.getContext("experimental-webgl",i)}catch(e){throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";const t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e<this._caps.maxVertexAttribs;e++)this._currentBufferPointers[e]=new Di;this._shaderProcessor=this.webGLVersion>1?new Mi:new bi;const r=`Babylon.js v${Pi.Version}`;ce.Log(r+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",r);const a=at(this._gl);a.validateShaderPrograms=this.validateShaderPrograms,a.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),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")),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},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");if(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.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_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);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),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);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}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})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!(!this._creationOptions||!this._creationOptions.forceSRGBBufferSupportState)}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,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,_collectUbosUpdatedInFrame:!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,i,s=!1){const n=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=n;let r=0;if(t&&e){let t=!0;if(this._currentRenderTarget){const i=this._currentRenderTarget.texture?.format;if(i===tt.TEXTUREFORMAT_RED_INTEGER||i===tt.TEXTUREFORMAT_RG_INTEGER||i===tt.TEXTUREFORMAT_RGB_INTEGER||i===tt.TEXTUREFORMAT_RGBA_INTEGER){const i=this._currentRenderTarget.texture?.type;i===tt.TEXTURETYPE_UNSIGNED_INTEGER||i===tt.TEXTURETYPE_UNSIGNED_SHORT?(Pi._TempClearColorUint32[0]=255*e.r,Pi._TempClearColorUint32[1]=255*e.g,Pi._TempClearColorUint32[2]=255*e.b,Pi._TempClearColorUint32[3]=255*e.a,this._gl.clearBufferuiv(this._gl.COLOR,0,Pi._TempClearColorUint32),t=!1):(Pi._TempClearColorInt32[0]=255*e.r,Pi._TempClearColorInt32[1]=255*e.g,Pi._TempClearColorInt32[2]=255*e.b,Pi._TempClearColorInt32[3]=255*e.a,this._gl.clearBufferiv(this._gl.COLOR,0,Pi._TempClearColorInt32),t=!1)}}t&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),r|=this._gl.COLOR_BUFFER_BIT)}i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),r|=this._gl.DEPTH_BUFFER_BIT),s&&(this._gl.clearStencil(0),r|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(r)}_viewport(e,t,i,s){e===this._viewportCached.x&&t===this._viewportCached.y&&i===this._viewportCached.z&&s===this._viewportCached.w||(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=s,this._gl.viewport(e,t,i,s))}endFrame(){super.endFrame(),this._badOS&&this.flushFramebuffer()}get performanceMonitor(){throw new Error("Not Supported by ThinEngine")}bindFramebuffer(e,t=0,i,s,n,r=0,a=0){const o=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(o._MSAAFramebuffer?o._MSAAFramebuffer:o._framebuffer);const l=this._gl;e.isMulti||(e.is2DArray||e.is3D?l.framebufferTextureLayer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,e.texture._hardwareTexture?.underlyingResource,r,a):e.isCube?l.framebufferTexture2D(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_CUBE_MAP_POSITIVE_X+t,e.texture._hardwareTexture?.underlyingResource,r):o._currentLOD!==r&&(l.framebufferTexture2D(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_2D,e.texture._hardwareTexture?.underlyingResource,r),o._currentLOD=r));const h=e._depthStencilTexture;if(h){e.is3D&&(e.texture.width===h.width&&e.texture.height===h.height&&e.texture.depth===h.depth||ce.Warn("Depth/Stencil attachment for 3D target must have same dimensions as color attachment"));const i=e._depthStencilTextureWithStencil?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT;e.is2DArray||e.is3D?l.framebufferTextureLayer(l.FRAMEBUFFER,i,h._hardwareTexture?.underlyingResource,r,a):e.isCube?l.framebufferTexture2D(l.FRAMEBUFFER,i,l.TEXTURE_CUBE_MAP_POSITIVE_X+t,h._hardwareTexture?.underlyingResource,r):l.framebufferTexture2D(l.FRAMEBUFFER,i,l.TEXTURE_2D,h._hardwareTexture?.underlyingResource,r)}this._cachedViewport&&!n?this.setViewport(this._cachedViewport,i,s):(i||(i=e.width,r&&(i/=Math.pow(2,r))),s||(s=e.height,r&&(s/=Math.pow(2,r))),this._viewport(0,0,i,s)),this.wipeCaches()}setState(e,t=0,i,s=!1,n,r,a=0){(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const o=this.cullBackFaces??n??1?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==o||i)&&(this._depthCullingState.cullFace=o),this.setZOffset(t),this.setZOffsetUnits(a);const l=s?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==l||i)&&(this._depthCullingState.frontFace=l),this._stencilStateComposer.stencilMaterial=r}_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=!1,i){const s=e;this._currentRenderTarget=null;const n=this._gl;if(s._MSAAFramebuffer){if(e.isMulti)return void this.unBindMultiColorAttachmentFramebuffer(e,t,i);n.bindFramebuffer(n.READ_FRAMEBUFFER,s._MSAAFramebuffer),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,s._framebuffer),n.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,n.COLOR_BUFFER_BIT,n.NEAREST)}!e.texture?.generateMipMaps||t||e.isCube||this.generateMipmaps(e.texture),i&&(s._MSAAFramebuffer&&this._bindUnboundFramebuffer(s._framebuffer),i()),this._bindUnboundFramebuffer(null)}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,i){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create vertex buffer");const s=new xi(i);return this.bindArrayBuffer(s),"number"!=typeof e?e instanceof Array?(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t),s.capacity=4*e.length):(this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),s.capacity=e.byteLength):(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Uint8Array(e),t),s.capacity=e),this._resetVertexBufferBinding(),s.references=1,s}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,i){const s=this._gl.createBuffer(),n=new xi(s);if(!s)throw new Error("Unable to create index buffer");this.bindIndexBuffer(n);const r=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),n.references=1,n.is32Bits=4===r.BYTES_PER_ELEMENT,n}_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,i){const s=e.program,n=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,n,i)}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,i,s,n,r,a){const o=this._currentBufferPointers[t];if(!o)return;let l=!1;o.active?(o.buffer!==e&&(o.buffer=e,l=!0),o.size!==i&&(o.size=i,l=!0),o.type!==s&&(o.type=s,l=!0),o.normalized!==n&&(o.normalized=n,l=!0),o.stride!==r&&(o.stride=r,l=!0),o.offset!==a&&(o.offset=a,l=!0)):(l=!0,o.active=!0,o.index=t,o.size=i,o.type=s,o.normalized=n,o.stride=r,o.offset=a,o.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,r,a):this._gl.vertexAttribPointer(t,i,s,n,r,a))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const s=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let n=0;n<s.length;n++){const r=t.getAttributeLocation(n);if(r>=0){const t=s[n];let a=null;if(i&&(a=i[t]),a||(a=e[t]),!a)continue;this._gl.enableVertexAttribArray(r),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[r]=!0);const o=a.getBuffer();o&&(this._vertexAttribPointer(o,r,a.getSize(),a.type,a.normalized,a.byteStride,a.byteOffset),a.getIsInstanced()&&(this._gl.vertexAttribDivisor(r,a.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(r),this._currentInstanceBuffers.push(o))))}}}recordVertexArrayObject(e,t,i,s){const n=this._gl.createVertexArray();if(!n)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(n),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),n}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,i,s,n){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==n){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=n;const t=n.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let r=0;for(let a=0;a<t;a++)if(a<i.length){const t=n.getAttributeLocation(a);t>=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[a],this._gl.FLOAT,!1,s,r)),r+=4*i[a]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,s){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,s)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t<i;t++){const i=this._currentInstanceBuffers[t];e!=i&&i.references&&(e=i,this.bindArrayBuffer(i));const s=this._currentInstanceLocations[t];this._gl.vertexAttribDivisor(s,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,i){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),void 0!==i[0].index)this.bindInstancesBuffer(e,i,!0);else for(let t=0;t<4;t++){const s=i[t];this._vertexAttribArraysEnabled[s]||(this._gl.enableVertexAttribArray(s),this._vertexAttribArraysEnabled[s]=!0),this._vertexAttribPointer(e,s,4,this._gl.FLOAT,!1,64,16*t),this._gl.vertexAttribDivisor(s,1),this._currentInstanceLocations.push(s),this._currentInstanceBuffers.push(e)}}bindInstancesBuffer(e,t,i=!0){this.bindArrayBuffer(e);let s=0;if(i)for(let e=0;e<t.length;e++){s+=4*t[e].attributeSize}for(let i=0;i<t.length;i++){const n=t[i];void 0===n.index&&(n.index=this._currentEffect.getAttributeLocationByName(n.attributeName)),n.index<0||(this._vertexAttribArraysEnabled[n.index]||(this._gl.enableVertexAttribArray(n.index),this._vertexAttribArraysEnabled[n.index]=!0),this._vertexAttribPointer(e,n.index,n.attributeSize,n.attributeType||this._gl.FLOAT,n.normalized||!1,s,n.offset),this._gl.vertexAttribDivisor(n.index,void 0===n.divisor?1:n.divisor),this._currentInstanceLocations.push(n.index),this._currentInstanceBuffers.push(e))}}disableInstanceAttributeByName(e){if(!this._currentEffect)return;const t=this._currentEffect.getAttributeLocationByName(e);this.disableInstanceAttribute(t)}disableInstanceAttribute(e){let t,i=!1;for(;-1!==(t=this._currentInstanceLocations.indexOf(e));)this._currentInstanceLocations.splice(t,1),this._currentInstanceBuffers.splice(t,1),i=!0,t=this._currentInstanceLocations.indexOf(e);i&&(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,i,s){this.drawElementsType(e?tt.MATERIAL_TriangleFillMode:tt.MATERIAL_WireFrameFillMode,t,i,s)}drawPointClouds(e,t,i){this.drawArraysType(tt.MATERIAL_PointFillMode,e,t,i)}drawUnIndexed(e,t,i,s){this.drawArraysType(e?tt.MATERIAL_TriangleFillMode:tt.MATERIAL_WireFrameFillMode,t,i,s)}drawElementsType(e,t,i,s){this.applyStates(),this._reportDrawCall();const n=this._drawMode(e),r=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,a=this._uintIndicesCurrentlySet?4:2;s?this._gl.drawElementsInstanced(n,i,r,t*a,s):this._gl.drawElements(n,i,r,t*a)}drawArraysType(e,t,i,s){this.applyStates(),this._reportDrawCall();const n=this._drawMode(e);s?this._gl.drawArraysInstanced(n,t,i,s):this._gl.drawArrays(n,t,i)}_drawMode(e){switch(e){case tt.MATERIAL_TriangleFillMode:return this._gl.TRIANGLES;case tt.MATERIAL_PointFillMode:return this._gl.POINTS;case tt.MATERIAL_WireFrameFillMode:return this._gl.LINES;case tt.MATERIAL_PointListDrawMode:return this._gl.POINTS;case tt.MATERIAL_LineListDrawMode:return this._gl.LINES;case tt.MATERIAL_LineLoopDrawMode:return this._gl.LINE_LOOP;case tt.MATERIAL_LineStripDrawMode:return this._gl.LINE_STRIP;case tt.MATERIAL_TriangleStripDrawMode:return this._gl.TRIANGLE_STRIP;case tt.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,_t(t),this._gl.deleteProgram(t.program))}_getGlobalDefines(e){return Ue(e,this.isNDCHalfZRange,this.useReverseDepthBuffer,this.useExactSrgbConversions)}createEffect(e,t,i,s,n,r,a,o,l,h=0){const c="string"==typeof e?e:e.vertexToken||e.vertexSource||e.vertexElement||e.vertex,u="string"==typeof e?e:e.fragmentToken||e.fragmentSource||e.fragmentElement||e.fragment,d=this._getGlobalDefines();let _=n??t.defines??"";d&&(_+=d);const f=c+"+"+u+"@"+_;if(this._compiledEffects[f]){const e=this._compiledEffects[f];return a&&e.isReady()&&a(e),e}this._gl&&at(this._gl);const m=new mt(e,t,i,s,this,n,r,a,o,l,f,t.shaderLanguage??h);return this._compiledEffects[f]=m,m}_getShaderSource(e){return this._gl.getShaderSource(e)}createRawShaderProgram(e,t,i,s,n=null){const r=at(this._gl);return r._contextWasLost=this._contextWasLost,r.validateShaderPrograms=this.validateShaderPrograms,ot(e,t,i,s||this._gl,n)}createShaderProgram(e,t,i,s,n,r=null){const a=at(this._gl);return a._contextWasLost=this._contextWasLost,a.validateShaderPrograms=this.validateShaderPrograms,lt(e,t,i,s,n||this._gl,r)}inlineShaderCode(e){return e}createPipelineContext(e){if(this._gl){at(this._gl).parallelShaderCompile=this._caps.parallelShaderCompile}const t=function(e){const t=new st,i=at(e);return i.parallelShaderCompile&&(t.isParallelCompiled=!0),t.context=i._context,t}(this._gl);return t.engine=this,t}createMaterialContext(){}createDrawContext(){}_finalizePipelineContext(e){return ct(e,this._gl,this.validateShaderPrograms)}_preparePipelineContext(e,t,i,s,n,r,a,o,l,h){const c=at(this._gl);return c._contextWasLost=this._contextWasLost,c.validateShaderPrograms=this.validateShaderPrograms,c._createShaderProgramInjection=this._createShaderProgram.bind(this),c.createRawShaderProgramInjection=this.createRawShaderProgram.bind(this),c.createShaderProgramInjection=this.createShaderProgram.bind(this),c.loadFileInjection=this._loadFile.bind(this),function(e,t,i,s,n,r,a,o,l,h="",c,u){const d=at(e.context);c||(c=d.createRawShaderProgramInjection??ot),u||(u=d.createShaderProgramInjection??lt);const _=e;_.program=s?c(_,t,i,_.context,l):u(_,t,i,o,_.context,l),_.program.__SPECTOR_rebuildProgram=a}(e,t,i,s,0,0,a,o,l,h)}_createShaderProgram(e,t,i,s,n=null){return ht(e,t,i,s,n)}_isRenderingStateCompiled(e){const t=e;return!this._isDisposed&&!t._isDisposed&&(!!this._gl.getProgramParameter(t.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(t),!0))}_executeWhenRenderingStateIsCompiled(e,t){!function(e,t){const i=e;if(!i.isParallelCompiled)return void t(e);const s=i.onCompiled;i.onCompiled=()=>{s?.(),t(e)}}(e,t)}getUniforms(e,t){const i=new Array,s=e;for(let e=0;e<t.length;e++)i.push(this._gl.getUniformLocation(s.program,t[e]));return i}getAttributes(e,t){const i=[],s=e;for(let e=0;e<t.length;e++)try{i.push(this._gl.getAttribLocation(s.program,t[e]))}catch(e){i.push(-1)}return i}enableEffect(e){(e=null!==e&&function(e){return void 0===e.getPipelineContext}(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,i){return!!e&&(this._gl.uniform2i(e,t,i),!0)}setInt3(e,t,i,s){return!!e&&(this._gl.uniform3i(e,t,i,s),!0)}setInt4(e,t,i,s,n){return!!e&&(this._gl.uniform4i(e,t,i,s,n),!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,i){return!!e&&(this._gl.uniform2ui(e,t,i),!0)}setUInt3(e,t,i,s){return!!e&&(this._gl.uniform3ui(e,t,i,s),!0)}setUInt4(e,t,i,s,n){return!!e&&(this._gl.uniform4ui(e,t,i,s,n),!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,i){return!!e&&(this._gl.uniform2f(e,t,i),!0)}setFloat3(e,t,i,s){return!!e&&(this._gl.uniform3f(e,t,i,s),!0)}setFloat4(e,t,i,s,n){return!!e&&(this._gl.uniform4f(e,t,i,s,n),!0)}applyStates(){if(this._depthCullingState.apply(this._gl),this._stencilStateComposer.apply(this._gl),this._alphaState.apply(this._gl),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._alphaMode=tt.ALPHA_ADD,this._alphaEquation=tt.ALPHA_DISABLE,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 i=this._gl;let s=i.NEAREST,n=i.NEAREST;switch(e){case tt.TEXTURE_LINEAR_LINEAR_MIPNEAREST:s=i.LINEAR,n=t?i.LINEAR_MIPMAP_NEAREST:i.LINEAR;break;case tt.TEXTURE_LINEAR_LINEAR_MIPLINEAR:s=i.LINEAR,n=t?i.LINEAR_MIPMAP_LINEAR:i.LINEAR;break;case tt.TEXTURE_NEAREST_NEAREST_MIPLINEAR:s=i.NEAREST,n=t?i.NEAREST_MIPMAP_LINEAR:i.NEAREST;break;case tt.TEXTURE_NEAREST_NEAREST_MIPNEAREST:s=i.NEAREST,n=t?i.NEAREST_MIPMAP_NEAREST:i.NEAREST;break;case tt.TEXTURE_NEAREST_LINEAR_MIPNEAREST:s=i.NEAREST,n=t?i.LINEAR_MIPMAP_NEAREST:i.LINEAR;break;case tt.TEXTURE_NEAREST_LINEAR_MIPLINEAR:s=i.NEAREST,n=t?i.LINEAR_MIPMAP_LINEAR:i.LINEAR;break;case tt.TEXTURE_NEAREST_LINEAR:s=i.NEAREST,n=i.LINEAR;break;case tt.TEXTURE_NEAREST_NEAREST:s=i.NEAREST,n=i.NEAREST;break;case tt.TEXTURE_LINEAR_NEAREST_MIPNEAREST:s=i.LINEAR,n=t?i.NEAREST_MIPMAP_NEAREST:i.NEAREST;break;case tt.TEXTURE_LINEAR_NEAREST_MIPLINEAR:s=i.LINEAR,n=t?i.NEAREST_MIPMAP_LINEAR:i.NEAREST;break;case tt.TEXTURE_LINEAR_LINEAR:s=i.LINEAR,n=i.LINEAR;break;case tt.TEXTURE_LINEAR_NEAREST:s=i.LINEAR,n=i.NEAREST}return{min:n,mag:s}}_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,i=!0,s=0){let n,r=!1,a=tt.TEXTURETYPE_UNSIGNED_INT,o=tt.TEXTURE_TRILINEAR_SAMPLINGMODE,l=tt.TEXTUREFORMAT_RGBA,h=!1,c=1;void 0!==t&&"object"==typeof t?(r=!!t.generateMipMaps,a=void 0===t.type?tt.TEXTURETYPE_UNSIGNED_INT:t.type,o=void 0===t.samplingMode?tt.TEXTURE_TRILINEAR_SAMPLINGMODE:t.samplingMode,l=void 0===t.format?tt.TEXTUREFORMAT_RGBA:t.format,h=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,c=t.samples??1,n=t.label):r=!!t,h&&=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU),(a!==tt.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(a!==tt.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(o=tt.TEXTURE_NEAREST_SAMPLINGMODE),a!==tt.TEXTURETYPE_FLOAT||this._caps.textureFloat||(a=tt.TEXTURETYPE_UNSIGNED_INT,ce.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=this._gl,d=new vt(this,s),_=e.width||e,f=e.height||e,m=e.depth||0,p=e.layers||0,g=this._getSamplingParameters(o,r),E=0!==p?u.TEXTURE_2D_ARRAY:0!==m?u.TEXTURE_3D:u.TEXTURE_2D,T=this._getRGBABufferInternalSizedFormat(a,l,h),A=this._getInternalFormat(l),R=this._getWebGLTextureType(a);return this._bindTextureDirectly(E,d),0!==p?(d.is2DArray=!0,u.texImage3D(E,0,T,_,f,p,0,A,R,null)):0!==m?(d.is3D=!0,u.texImage3D(E,0,T,_,f,m,0,A,R,null)):u.texImage2D(E,0,T,_,f,0,A,R,null),u.texParameteri(E,u.TEXTURE_MAG_FILTER,g.mag),u.texParameteri(E,u.TEXTURE_MIN_FILTER,g.min),u.texParameteri(E,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(E,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),r&&this._gl.generateMipmap(E),this._bindTextureDirectly(E,null),d._useSRGBBuffer=h,d.baseWidth=_,d.baseHeight=f,d.width=_,d.height=f,d.depth=p,d.isReady=!0,d.samples=c,d.generateMipMaps=r,d.samplingMode=o,d.type=a,d.format=l,d.label=n,this._internalTexturesCache.push(d),d}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,s,n=tt.TEXTURE_TRILINEAR_SAMPLINGMODE,r=null,a=null,o=null,l=null,h=null,c=null,u,d,_,f){return this._createTextureBase(e,t,i,s,n,r,a,((...e)=>this._prepareWebGLTexture(...e,h)),((e,t,i,n,r,a)=>{const o=this._gl,l=i.width===e&&i.height===t;r._creationFlags=_??0;const h=this._getTexImageParametersForCreateTexture(r.format,r._useSRGBBuffer);if(l)return o.texImage2D(o.TEXTURE_2D,0,h.internalFormat,h.format,h.type,i),!1;const c=this._caps.maxTextureSize;if(i.width>c||i.height>c||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!(!this._workingCanvas||!this._workingContext)&&(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),o.texImage2D(o.TEXTURE_2D,0,h.internalFormat,h.format,h.type,this._workingCanvas),r.width=e,r.height=t,!1);{const e=new vt(this,2);this._bindTextureDirectly(o.TEXTURE_2D,e,!0),o.texImage2D(o.TEXTURE_2D,0,h.internalFormat,h.format,h.type,i),this._rescaleTexture(e,r,s,h.format,(()=>{this._releaseTexture(e),this._bindTextureDirectly(o.TEXTURE_2D,r,!0),a()}))}return!0}),o,l,h,c,u,d,f)}_getTexImageParametersForCreateTexture(e,t){let i,s;return 1===this.webGLVersion?(i=this._getInternalFormat(e,t),s=i):(i=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(tt.TEXTURETYPE_UNSIGNED_BYTE,e,t)),{internalFormat:s,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,s,n){}_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,i=!1){const s=this._getTextureTarget(t),n=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,n.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,n.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const n=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(n,null)}_uploadCompressedDataToTextureDirectly(e,t,i,s,n,r=0,a=0){const o=this._gl;let l=o.TEXTURE_2D;if(e.isCube&&(l=o.TEXTURE_CUBE_MAP_POSITIVE_X+r),e._useSRGBBuffer)switch(t){case tt.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2:case tt.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL:this._caps.etc2?t=o.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case tt.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC:this._caps.etc2?t=o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case tt.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM:t=o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case tt.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case tt.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case tt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case tt.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}this._gl.compressedTexImage2D(l,a,t,i,s,0,n)}_uploadDataToTextureDirectly(e,t,i=0,s=0,n,r=!1){const a=this._gl,o=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===n?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(n,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=a.TEXTURE_2D;e.isCube&&(c=a.TEXTURE_CUBE_MAP_POSITIVE_X+i);const u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),_=r?e.width:Math.pow(2,Math.max(u-s,0)),f=r?e.height:Math.pow(2,Math.max(d-s,0));a.texImage2D(c,s,h,_,f,0,l,o,t)}updateTextureData(e,t,i,s,n,r,a=0,o=0,l=!1){const h=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,_=h.TEXTURE_2D;e.isCube&&(_=h.TEXTURE_CUBE_MAP_POSITIVE_X+a,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(_,o,i,s,n,r,u,c,t),l&&this._gl.generateMipmap(_),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const n=this._gl,r=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(r,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(r,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,n){const r=this._gl;if(!r)return;const a=this._getSamplingParameters(n,!i);r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,a.mag),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,a.min),i||s||r.generateMipmap(r.TEXTURE_2D),this._bindTextureDirectly(r.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,n,r,a,o,l,h){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?qt(s.width,c):s.width),d=Math.min(c,this.needPOTTextures?qt(s.height,c):s.height),_=this._gl;_&&(e._hardwareTexture?(this._bindTextureDirectly(_.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===n||!!n),e.baseWidth=s.width,e.baseHeight=s.height,e.width=u,e.height=d,e.isReady=!0,e.type=-1!==e.type?e.type:tt.TEXTURETYPE_UNSIGNED_BYTE,e.format=-1!==e.format?e.format:h??(".jpg"!==t||e._useSRGBBuffer?tt.TEXTUREFORMAT_RGBA:tt.TEXTUREFORMAT_RGB),o(u,d,s,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,r,a,l)}))||this._prepareWebGLTextureContinuation(e,i,r,a,l)):i&&i.removePendingData(e))}_setupFramebufferDepthAttachments(e,t,i,s,n=1){const r=this._gl;if(e&&t)return this._createRenderBuffer(i,s,n,r.DEPTH_STENCIL,r.DEPTH24_STENCIL8,r.DEPTH_STENCIL_ATTACHMENT);if(t){let e=r.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=r.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,n,e,e,r.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,n,r.STENCIL_INDEX8,r.STENCIL_INDEX8,r.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,n,r,a=!0){const o=this._gl.createRenderbuffer();return this._updateRenderBuffer(o,e,t,i,s,n,r,a)}_updateRenderBuffer(e,t,i,s,n,r,a,o=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),s>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,s,r,t,i):l.renderbufferStorage(l.RENDERBUFFER,n,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,a,l.RENDERBUFFER,e),o&&l.bindRenderbuffer(l.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 i=e.getSamplers();for(let t=0;t<i.length;t++){const s=e.getUniform(i[t]);s&&(this._boundUniforms[t]=s)}this._currentEffect=null}_activateCurrentTexture(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)}_bindTextureDirectly(e,t,i=!1,s=!1){let n=!1;const r=t&&t._associatedChannel>-1;i&&r&&(this._activeChannel=t._associatedChannel);if(this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw ce.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 i&&(n=!0,this._activateCurrentTexture());return r&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),n}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;const s=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(s,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,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case tt.TEXTURE_WRAP_ADDRESSMODE:return this._gl.REPEAT;case tt.TEXTURE_CLAMP_ADDRESSMODE:return this._gl.CLAMP_TO_EDGE;case tt.TEXTURE_MIRROR_ADDRESSMODE:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,s=!1,n=""){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 i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(t.delayLoadState===tt.DELAYLOADSTATE_NOTLOADED)return t.delayLoad(),!1;let r;r=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&r&&(r._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===r&&(i||this._bindSamplerUniformToChannel(r._associatedChannel,e),a=!1),this._activeChannel=e;const o=this._getTextureTarget(r);if(a&&this._bindTextureDirectly(o,r,i),r&&!r.isMultiview){if(r.isCube&&r._cachedCoordinatesMode!==t.coordinatesMode){r._cachedCoordinatesMode=t.coordinatesMode;const e=t.coordinatesMode!==tt.TEXTURE_CUBIC_MODE&&t.coordinatesMode!==tt.TEXTURE_SKYBOX_MODE?tt.TEXTURE_WRAP_ADDRESSMODE:tt.TEXTURE_CLAMP_ADDRESSMODE;t.wrapU=e,t.wrapV=e}r._cachedWrapU!==t.wrapU&&(r._cachedWrapU=t.wrapU,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),r)),r._cachedWrapV!==t.wrapV&&(r._cachedWrapV=t.wrapV,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),r)),r.is3D&&r._cachedWrapR!==t.wrapR&&(r._cachedWrapR=t.wrapR,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),r)),this._setAnisotropicLevel(o,r,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t<i.length;t++){const s=i[t].getInternalTexture();s?(this._textureUnits[t]=e+t,s._associatedChannel=e+t):this._textureUnits[t]=-1}this._gl.uniform1iv(t,this._textureUnits);for(let e=0;e<i.length;e++)this._setTexture(this._textureUnits[e],i[e],!0)}}_setAnisotropicLevel(e,t,i){const s=this._caps.textureAnisotropicFilterExtension;t.samplingMode!==tt.TEXTURE_LINEAR_LINEAR_MIPNEAREST&&t.samplingMode!==tt.TEXTURE_LINEAR_LINEAR_MIPLINEAR&&t.samplingMode!==tt.TEXTURE_LINEAR_LINEAR&&(i=1),s&&t._cachedAnisotropicFilteringLevel!==i&&(this._setTextureParameterFloat(e,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(i,this._caps.maxAnisotropy),t),t._cachedAnisotropicFilteringLevel=i)}_setTextureParameterFloat(e,t,i,s){this._bindTextureDirectly(e,s,!0,!0),this._gl.texParameterf(e,t,i)}_setTextureParameterInteger(e,t,i,s){s&&this._bindTextureDirectly(e,s,!0,!0),this._gl.texParameteri(e,t,i)}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(){const e=Object.keys(this._compiledEffects);for(const t of e){this._compiledEffects[t].dispose()}this._compiledEffects={}}dispose(){var e;ae()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),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(),e=this._gl,nt.delete(e)}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(tt.TEXTURETYPE_FLOAT)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(tt.TEXTURETYPE_HALF_FLOAT)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const s=t.createTexture();t.bindTexture(t.TEXTURE_2D,s),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 n=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const r=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&r===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);const e=t.RGBA,s=t.UNSIGNED_BYTE,n=new Uint8Array(4);t.readPixels(0,0,1,1,e,s,n),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(n),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case tt.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case tt.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT_OES;case tt.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case tt.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case tt.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case tt.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case tt.TEXTURETYPE_BYTE:return this._gl.BYTE;case tt.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case tt.TEXTURETYPE_SHORT:return this._gl.SHORT;case tt.TEXTURETYPE_UNSIGNED_SHORT:return this._gl.UNSIGNED_SHORT;case tt.TEXTURETYPE_INT:return this._gl.INT;case tt.TEXTURETYPE_UNSIGNED_INTEGER:return this._gl.UNSIGNED_INT;case tt.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case tt.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT;case tt.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case tt.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case tt.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5;case tt.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case tt.TEXTURETYPE_UNSIGNED_INT_24_8:return this._gl.UNSIGNED_INT_24_8;case tt.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case tt.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case tt.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 i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case tt.TEXTUREFORMAT_ALPHA:i=this._gl.ALPHA;break;case tt.TEXTUREFORMAT_LUMINANCE:i=this._gl.LUMINANCE;break;case tt.TEXTUREFORMAT_LUMINANCE_ALPHA:i=this._gl.LUMINANCE_ALPHA;break;case tt.TEXTUREFORMAT_RED:i=this._gl.RED;break;case tt.TEXTUREFORMAT_RG:i=this._gl.RG;break;case tt.TEXTUREFORMAT_RGB:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case tt.TEXTUREFORMAT_RGBA:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case tt.TEXTUREFORMAT_RED_INTEGER:i=this._gl.RED_INTEGER;break;case tt.TEXTUREFORMAT_RG_INTEGER:i=this._gl.RG_INTEGER;break;case tt.TEXTUREFORMAT_RGB_INTEGER:i=this._gl.RGB_INTEGER;break;case tt.TEXTUREFORMAT_RGBA_INTEGER:i=this._gl.RGBA_INTEGER}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case tt.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case tt.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case tt.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;case tt.TEXTUREFORMAT_RGB:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case tt.TEXTURETYPE_BYTE:switch(t){case tt.TEXTUREFORMAT_RED:return this._gl.R8_SNORM;case tt.TEXTUREFORMAT_RG:return this._gl.RG8_SNORM;case tt.TEXTUREFORMAT_RGB:return this._gl.RGB8_SNORM;case tt.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8I;case tt.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8I;case tt.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8I;case tt.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case tt.TEXTURETYPE_UNSIGNED_BYTE:switch(t){case tt.TEXTUREFORMAT_RED:return this._gl.R8;case tt.TEXTUREFORMAT_RG:return this._gl.RG8;case tt.TEXTUREFORMAT_RGB:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case tt.TEXTUREFORMAT_RGBA:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case tt.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8UI;case tt.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8UI;case tt.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8UI;case tt.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8UI;case tt.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case tt.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case tt.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case tt.TEXTURETYPE_SHORT:switch(t){case tt.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16I;case tt.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16I;case tt.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16I;case tt.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16I}case tt.TEXTURETYPE_UNSIGNED_SHORT:switch(t){case tt.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16UI;case tt.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16UI;case tt.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16UI;case tt.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16UI}case tt.TEXTURETYPE_INT:switch(t){case tt.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32I;case tt.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32I;case tt.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32I;case tt.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32I}case tt.TEXTURETYPE_UNSIGNED_INTEGER:switch(t){case tt.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32UI;case tt.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32UI;case tt.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32UI;case tt.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32UI}case tt.TEXTURETYPE_FLOAT:switch(t){case tt.TEXTUREFORMAT_RED:return this._gl.R32F;case tt.TEXTUREFORMAT_RG:return this._gl.RG32F;case tt.TEXTUREFORMAT_RGB:return this._gl.RGB32F;case tt.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA32F}case tt.TEXTURETYPE_HALF_FLOAT:switch(t){case tt.TEXTUREFORMAT_RED:return this._gl.R16F;case tt.TEXTUREFORMAT_RG:return this._gl.RG16F;case tt.TEXTUREFORMAT_RGB:return this._gl.RGB16F;case tt.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA16F}case tt.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.RGB565;case tt.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.R11F_G11F_B10F;case tt.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.RGB9_E5;case tt.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.RGBA4;case tt.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.RGB5_A1;case tt.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:switch(t){case tt.TEXTUREFORMAT_RGBA:return this._gl.RGB10_A2;case tt.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,s,n=!0,r=!0){const a=n?4:3,o=n?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(s*i*a);return r&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,o,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}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=St._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{const e=St._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}}Pi._TempClearColorUint32=new Uint32Array(4),Pi._TempClearColorInt32=new Int32Array(4),Pi.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"]}],Pi.CollisionsEpsilon=.001,Pi._ConcatenateShader=we,Pi._IsSupported=null,Pi._HasMajorPerformanceCaveat=null,Pi.CeilingPOT=Yt,Pi.FloorPOT=Kt,Pi.NearestPOT=Wt,Pi.GetExponentOfTwo=qt,Pi.QueueNewFrame=It;class Ni{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new Li(e)}sampleFrame(e=_e.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 Li{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 Fi(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}Pi.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){case tt.ALPHA_DISABLE:this._alphaState.alphaBlend=!1;break;case tt.ALPHA_PREMULTIPLIED:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_PREMULTIPLIED_PORTERDUFF:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_COMBINE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_ADD:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_SUBTRACT:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_MULTIPLY:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_MAXIMIZED:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_INTERPOLATE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_SCREENMODE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_ONEONE_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_ALPHATOCOLOR:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_REVERSEONEMINUS:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_SRC_DSTONEMINUSSRCALPHA:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_ONEONE_ONEZERO:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_EXCLUSION:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case tt.ALPHA_LAYER_ACCUMULATE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0}t||(this.depthCullingState.depthMask=e===tt.ALPHA_DISABLE),this._alphaMode=e}else if(!t){const t=e===tt.ALPHA_DISABLE;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}},Pi.prototype._readTexturePixelsSync=function(e,t,i,s=-1,n=0,r=null,a=!0,o=!1,l=0,h=0){const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=c.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),s>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+s,e._hardwareTexture?.underlyingResource,n):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,e._hardwareTexture?.underlyingResource,n);let u=void 0!==e.type?this._getWebGLTextureType(e.type):c.UNSIGNED_BYTE;if(o)r||(r=function(e,t,i=!1){switch(e){case tt.TEXTURETYPE_BYTE:return ArrayBuffer,new Int8Array(t);case tt.TEXTURETYPE_UNSIGNED_BYTE:return ArrayBuffer,new Uint8Array(t);case tt.TEXTURETYPE_SHORT:return t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);case tt.TEXTURETYPE_UNSIGNED_SHORT:case tt.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:case tt.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:case tt.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:case tt.TEXTURETYPE_HALF_FLOAT:return t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);case tt.TEXTURETYPE_INT:return t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);case tt.TEXTURETYPE_UNSIGNED_INTEGER:case tt.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:case tt.TEXTURETYPE_UNSIGNED_INT_24_8:case tt.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:case tt.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:case tt.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:return t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);case tt.TEXTURETYPE_FLOAT:return t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t)}return ArrayBuffer,new Uint8Array(t)}(e.type,4*t*i));else if(u===c.UNSIGNED_BYTE)r||(r=new Uint8Array(4*t*i)),u=c.UNSIGNED_BYTE;else r||(r=new Float32Array(4*t*i)),u=c.FLOAT;return a&&this.flushFramebuffer(),c.readPixels(l,h,t,i,c.RGBA,u,r),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),r},Pi.prototype._readTexturePixels=function(e,t,i,s=-1,n=0,r=null,a=!0,o=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,s,n,r,a,o,l,h))},Pi.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let s;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),s=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,s,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},Pi.prototype.updateDynamicVertexBuffer=function(e,t,i,s){this.bindArrayBuffer(e),void 0===i&&(i=0);const n=t.byteLength||t.length;void 0===s||s>=n&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+s)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,s):new Uint8Array(t.buffer,t.byteOffset+i,s),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()},St.prototype.displayLoadingUI=function(){if(!ae())return;const e=this.loadingScreen;e&&e.displayLoadingUI()},St.prototype.hideLoadingUI=function(){if(!ae())return;const e=this._loadingScreen;e&&e.hideLoadingUI()},Object.defineProperty(St.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=St.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(St.prototype,"loadingUIText",{set:function(e){this.loadingScreen.loadingUIText=e},enumerable:!0,configurable:!0}),Object.defineProperty(St.prototype,"loadingUIBackgroundColor",{set:function(e){this.loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),St.prototype.getInputElement=function(){return this._renderingCanvas},St.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},St.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},St.prototype.getAspectRatio=function(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},St.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},St.prototype._verifyPointerLock=function(){this._onPointerLockChange?.()},St.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case tt.ALPHA_EQUATION_ADD:this._alphaState.setAlphaEquationParameters(tt.GL_ALPHA_EQUATION_ADD,tt.GL_ALPHA_EQUATION_ADD);break;case tt.ALPHA_EQUATION_SUBSTRACT:this._alphaState.setAlphaEquationParameters(tt.GL_ALPHA_EQUATION_SUBTRACT,tt.GL_ALPHA_EQUATION_SUBTRACT);break;case tt.ALPHA_EQUATION_REVERSE_SUBTRACT:this._alphaState.setAlphaEquationParameters(tt.GL_ALPHA_EQUATION_REVERSE_SUBTRACT,tt.GL_ALPHA_EQUATION_REVERSE_SUBTRACT);break;case tt.ALPHA_EQUATION_MAX:this._alphaState.setAlphaEquationParameters(tt.GL_ALPHA_EQUATION_MAX,tt.GL_ALPHA_EQUATION_MAX);break;case tt.ALPHA_EQUATION_MIN:this._alphaState.setAlphaEquationParameters(tt.GL_ALPHA_EQUATION_MIN,tt.GL_ALPHA_EQUATION_MIN);break;case tt.ALPHA_EQUATION_DARKEN:this._alphaState.setAlphaEquationParameters(tt.GL_ALPHA_EQUATION_MIN,tt.GL_ALPHA_EQUATION_ADD)}this._alphaEquation=e}},St.prototype.getInputElement=function(){return this._renderingCanvas},St.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},St.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},St.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(tt.GREATER)},St.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(tt.GEQUAL)},St.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(tt.LESS)},St.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(tt.LEQUAL)},St.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},St.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},St.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},St.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},St.prototype.getStencilMask=function(){return this._stencilState.stencilMask},St.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},St.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},St.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},St.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},St.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},St.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},St.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},St.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},St.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},St.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},St.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},St.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},St.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},St.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()},St.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)},St.prototype.setAlphaConstants=function(e,t,i,s){this._alphaState.setAlphaBlendConstants(e,t,i,s)},St.prototype.getAlphaMode=function(){return this._alphaMode},St.prototype.getAlphaEquation=function(){return this._alphaEquation},St.prototype.getRenderPassNames=function(){return this._renderPassNames},St.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]},St.prototype.createRenderPassId=function(e){const t=++St._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t},St.prototype.releaseRenderPassId=function(e){this._renderPassNames[e]=void 0;for(let t=0;t<this.scenes.length;++t){const i=this.scenes[t];for(let t=0;t<i.meshes.length;++t){const s=i.meshes[t];if(s.subMeshes)for(let t=0;t<s.subMeshes.length;++t){s.subMeshes[t]._removeDrawWrapper(e)}}}},St.prototype.createDepthStencilTexture=function(e,t,i){if(t.isCube){const i=e.width||e;return this._createDepthStencilCubeTexture(i,t)}return this._createDepthStencilTexture(e,t,i)};class wi{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._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._lastSecValueCount++}addCount(e,t){wi.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){wi.Enabled&&(this._startMonitoringTime=_e.Now)}endMonitoring(e=!0){if(!wi.Enabled)return;e&&this.fetchNewFrame();const t=_e.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;const e=_e.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}wi.Enabled=!0,St.AudioEngineFactory=(e,t,i)=>new Bi(e,t,i);class Bi{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new g,this.onAudioLockedObservable=new g,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!ae())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);const s=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{s&&s.canPlayType&&(s.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||s.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{s&&s.canPlayType&&s.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){if("running"===this._audioContext?.state)return this._hideMuteButton(),void(this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)));this._tryToRun?this._audioContext?.suspend().then((()=>{this._tryToRun=!1,this._triggerRunningState()})):this._triggerRunningState()}_resumeAudioContextOnStateChange(){this._audioContext?.addEventListener("statechange",(()=>{this.unlocked&&"running"!==this._audioContext?.state&&this._resumeAudioContext()}),{once:!0,passive:!0,signal:AbortSignal.timeout(3e3)})}_resumeAudioContext(){return this._audioContext?.resume?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,ce.Error("Web Audio: "+e.message)}}_triggerRunningState(){this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then((()=>{this._tryToRun=!1,this._muteButton&&this._hideMuteButton(),this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)})).catch((()=>{this._tryToRun=!1,this.unlocked=!1})))}_triggerSuspendedState(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()}_displayMuteButton(){if(this.useCustomUnlockedButton||this._muteButton)return;this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";const e=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",(()=>{this._triggerRunningState()}),!0),this._muteButton.addEventListener("click",(()=>{this.unlock()}),!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}}class Ui extends Pi{static get NpmPackage(){return St.NpmPackage}static get Version(){return St.Version}static get Instances(){return M.Instances}static get LastCreatedEngine(){return M.LastCreatedEngine}static get LastCreatedScene(){return M.LastCreatedScene}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i<Ui.Instances.length;i++){const s=Ui.Instances[i];for(let i=0;i<s.scenes.length;i++)s.scenes[i].markAllMaterialsAsDirty(e,t)}}static DefaultLoadingScreenFactory(e){return St.DefaultLoadingScreenFactory(e)}get _supportsHardwareTextureRescaling(){return!!Ui._RescalePostProcessFactory}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}get performanceMonitor(){return this._performanceMonitor}constructor(e,t,i,s=!1){if(super(e,t,i,s),this.customAnimationFrameRequester=null,this._performanceMonitor=new Ni,this._drawCalls=new wi,e&&(this._features.supportRenderPasses=!0,i=this._creationOptions,e.getContext)){const t=e;this._sharedInit(t)}}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),function(e,t,i){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=i=>{document.elementFromPoint(i.clientX,i.clientY)!==t&&e.onCanvasPointerOutObservable.notifyObservers(i)};const s=e.getHostWindow();s&&"function"==typeof s.addEventListener&&(s.addEventListener("blur",e._onBlur),s.addEventListener("focus",e._onFocus)),t.addEventListener("pointerout",e._onCanvasPointerOut),i.doNotHandleTouchAction||function(e){e&&e.setAttribute&&(e.setAttribute("touch-action","none"),e.style.touchAction="none",e.style.webkitTapHighlightColor="transparent")}(t),!St.audioEngine&&i.audioEngine&&St.AudioEngineFactory&&(St.audioEngine=St.AudioEngineFactory(e.getRenderingCanvas(),e.getAudioContext(),e.getAudioDestination())),le()&&(e._onFullscreenChange=()=>{e.isFullscreen=!!document.fullscreenElement,e.isFullscreen&&e._pointerLockRequested&&t&&Fi(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!==St.OfflineProviderFactory,e._deterministicLockstep=!!i.deterministicLockstep,e._lockstepMaxSteps=i.lockstepMaxSteps||0,e._timeStep=i.timeStep||1/60}(this,e,this._creationOptions)}resizeImageBitmap(e,t,i){return function(e,t,i,s){const n=e.createCanvas(i,s).getContext("2d");if(!n)throw new Error("Unable to get 2d context for resizeImageBitmap");return n.drawImage(t,0,0),n.getImageData(0,0,i,s).data}(this,e,t,i)}_createImageBitmapFromSource(e,t){return function(e,t,i){return new Promise(((s,n)=>{const r=new Image;r.onload=()=>{r.decode().then((()=>{e.createImageBitmap(r,i).then((e=>{s(e)}))}))},r.onerror=()=>{n(`Error loading image ${r.src}`)},r.src=t}))}(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&function(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&function(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}()}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,i,s){const n=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,s),n}scissorClear(e,t,i,s,n){this.enableScissor(e,t,i,s),this.clear(n,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,s){const n=this._gl;n.enable(n.SCISSOR_TEST),n.scissor(e,t,i,s)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_loadFileAsync(e,t,i){return new Promise(((s,n)=>{this._loadFile(e,(e=>{s(e)}),void 0,t,i,((e,t)=>{n(t)}))}))}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 function(e){const t=document.createElement("span");t.textContent="Hg",t.style.font=e;const i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";const s=document.createElement("div");s.style.whiteSpace="nowrap",s.appendChild(t),s.appendChild(i),document.body.appendChild(s);let n=0,r=0;try{r=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",n=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(s)}return{ascent:n,height:r,descent:r-n}}(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(0!==this._frameHandler){this._frameHandler=0;const{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(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()))}enterPointerlock(){this._renderingCanvas&&Fi(this._renderingCanvas)}exitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}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,i,s,n,r=null){n=n||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const a=super.createShaderProgram(e,t,i,s,n,r);return this.onAfterShaderCompilationObservable.notifyObservers(this),a}_createShaderProgram(e,t,i,s,n=null){const r=s.createProgram();if(e.program=r,!r)throw new Error("Unable to create program");if(s.attachShader(r,t),s.attachShader(r,i),this.webGLVersion>1&&n){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(r,n),e.transformFeedback=t}return s.linkProgram(r),this.webGLVersion>1&&n&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),r}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach((t=>{t.postProcesses.forEach((t=>{t._outputTexture===e&&(t._outputTexture=null)})),t.cameras.forEach((t=>{t._postProcesses.forEach((t=>{t&&t._outputTexture===e&&(t._outputTexture=null)}))}))}))}_rescaleTexture(e,t,i,s,n){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 r=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:tt.TEXTURETYPE_UNSIGNED_INT,samplingMode:tt.TEXTURE_BILINEAR_SAMPLINGMODE,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&Ui._RescalePostProcessFactory&&(this._rescalePostProcess=Ui._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled((()=>{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let a=i;a||(a=this.scenes[this.scenes.length-1]),a.postProcessManager.directRender([this._rescalePostProcess],r,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(r),r.dispose(),n&&n()})))}wrapWebGLTexture(e,t=!1,i=tt.TEXTURE_TRILINEAR_SAMPLINGMODE,s=0,n=0){const r=new Oi(e,this._gl),a=new vt(this,0,!0);return a._hardwareTexture=r,a.baseWidth=s,a.baseHeight=n,a.width=s,a.height=n,a.isReady=!0,a.useMipMaps=t,this.updateTextureSamplingMode(i,a),a}_uploadImageToTexture(e,t,i=0,s=0){const n=this._gl,r=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,a),l=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=n.TEXTURE_2D;e.isCube&&(h=n.TEXTURE_CUBE_MAP_POSITIVE_X+i),n.texImage2D(h,s,o,a,r,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void ce.Error("WebGL 1 does not support texture comparison.");const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,tt.LEQUAL),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,tt.LEQUAL),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.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 i=new xi(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const s=this._gl;return new Promise(((n,r)=>{const a=()=>{const o=s.clientWaitSync(e,t,0);o!=s.WAIT_FAILED?o!=s.TIMEOUT_EXPIRED?n():setTimeout(a,i):r()};a()}))}_readPixelsAsync(e,t,i,s,n,r,a){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const o=this._gl,l=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.bufferData(o.PIXEL_PACK_BUFFER,a.byteLength,o.STREAM_READ),o.readPixels(e,t,i,s,n,r,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);const h=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(o.flush(),this._clientWaitAsync(h,0,10).then((()=>(o.deleteSync(h),o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,a),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(l),a)))):null}dispose(){this.hideLoadingUI(),this._rescalePostProcess&&this._rescalePostProcess.dispose(),function(e,t){1===M.Instances.length&&St.audioEngine&&(St.audioEngine.dispose(),St.audioEngine=null);const i=e.getHostWindow();i&&"function"==typeof i.removeEventListener&&(i.removeEventListener("blur",e._onBlur),i.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)),le()&&(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))}(this,this._renderingCanvas),super.dispose()}}Ui.ALPHA_DISABLE=tt.ALPHA_DISABLE,Ui.ALPHA_ADD=tt.ALPHA_ADD,Ui.ALPHA_COMBINE=tt.ALPHA_COMBINE,Ui.ALPHA_SUBTRACT=tt.ALPHA_SUBTRACT,Ui.ALPHA_MULTIPLY=tt.ALPHA_MULTIPLY,Ui.ALPHA_MAXIMIZED=tt.ALPHA_MAXIMIZED,Ui.ALPHA_ONEONE=tt.ALPHA_ONEONE,Ui.ALPHA_PREMULTIPLIED=tt.ALPHA_PREMULTIPLIED,Ui.ALPHA_PREMULTIPLIED_PORTERDUFF=tt.ALPHA_PREMULTIPLIED_PORTERDUFF,Ui.ALPHA_INTERPOLATE=tt.ALPHA_INTERPOLATE,Ui.ALPHA_SCREENMODE=tt.ALPHA_SCREENMODE,Ui.DELAYLOADSTATE_NONE=tt.DELAYLOADSTATE_NONE,Ui.DELAYLOADSTATE_LOADED=tt.DELAYLOADSTATE_LOADED,Ui.DELAYLOADSTATE_LOADING=tt.DELAYLOADSTATE_LOADING,Ui.DELAYLOADSTATE_NOTLOADED=tt.DELAYLOADSTATE_NOTLOADED,Ui.NEVER=tt.NEVER,Ui.ALWAYS=tt.ALWAYS,Ui.LESS=tt.LESS,Ui.EQUAL=tt.EQUAL,Ui.LEQUAL=tt.LEQUAL,Ui.GREATER=tt.GREATER,Ui.GEQUAL=tt.GEQUAL,Ui.NOTEQUAL=tt.NOTEQUAL,Ui.KEEP=tt.KEEP,Ui.REPLACE=tt.REPLACE,Ui.INCR=tt.INCR,Ui.DECR=tt.DECR,Ui.INVERT=tt.INVERT,Ui.INCR_WRAP=tt.INCR_WRAP,Ui.DECR_WRAP=tt.DECR_WRAP,Ui.TEXTURE_CLAMP_ADDRESSMODE=tt.TEXTURE_CLAMP_ADDRESSMODE,Ui.TEXTURE_WRAP_ADDRESSMODE=tt.TEXTURE_WRAP_ADDRESSMODE,Ui.TEXTURE_MIRROR_ADDRESSMODE=tt.TEXTURE_MIRROR_ADDRESSMODE,Ui.TEXTUREFORMAT_ALPHA=tt.TEXTUREFORMAT_ALPHA,Ui.TEXTUREFORMAT_LUMINANCE=tt.TEXTUREFORMAT_LUMINANCE,Ui.TEXTUREFORMAT_LUMINANCE_ALPHA=tt.TEXTUREFORMAT_LUMINANCE_ALPHA,Ui.TEXTUREFORMAT_RGB=tt.TEXTUREFORMAT_RGB,Ui.TEXTUREFORMAT_RGBA=tt.TEXTUREFORMAT_RGBA,Ui.TEXTUREFORMAT_RED=tt.TEXTUREFORMAT_RED,Ui.TEXTUREFORMAT_R=tt.TEXTUREFORMAT_R,Ui.TEXTUREFORMAT_RG=tt.TEXTUREFORMAT_RG,Ui.TEXTUREFORMAT_RED_INTEGER=tt.TEXTUREFORMAT_RED_INTEGER,Ui.TEXTUREFORMAT_R_INTEGER=tt.TEXTUREFORMAT_R_INTEGER,Ui.TEXTUREFORMAT_RG_INTEGER=tt.TEXTUREFORMAT_RG_INTEGER,Ui.TEXTUREFORMAT_RGB_INTEGER=tt.TEXTUREFORMAT_RGB_INTEGER,Ui.TEXTUREFORMAT_RGBA_INTEGER=tt.TEXTUREFORMAT_RGBA_INTEGER,Ui.TEXTURETYPE_UNSIGNED_BYTE=tt.TEXTURETYPE_UNSIGNED_BYTE,Ui.TEXTURETYPE_UNSIGNED_INT=tt.TEXTURETYPE_UNSIGNED_INT,Ui.TEXTURETYPE_FLOAT=tt.TEXTURETYPE_FLOAT,Ui.TEXTURETYPE_HALF_FLOAT=tt.TEXTURETYPE_HALF_FLOAT,Ui.TEXTURETYPE_BYTE=tt.TEXTURETYPE_BYTE,Ui.TEXTURETYPE_SHORT=tt.TEXTURETYPE_SHORT,Ui.TEXTURETYPE_UNSIGNED_SHORT=tt.TEXTURETYPE_UNSIGNED_SHORT,Ui.TEXTURETYPE_INT=tt.TEXTURETYPE_INT,Ui.TEXTURETYPE_UNSIGNED_INTEGER=tt.TEXTURETYPE_UNSIGNED_INTEGER,Ui.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=tt.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4,Ui.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=tt.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1,Ui.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=tt.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,Ui.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=tt.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV,Ui.TEXTURETYPE_UNSIGNED_INT_24_8=tt.TEXTURETYPE_UNSIGNED_INT_24_8,Ui.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=tt.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV,Ui.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=tt.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV,Ui.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=tt.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV,Ui.TEXTURE_NEAREST_SAMPLINGMODE=tt.TEXTURE_NEAREST_SAMPLINGMODE,Ui.TEXTURE_BILINEAR_SAMPLINGMODE=tt.TEXTURE_BILINEAR_SAMPLINGMODE,Ui.TEXTURE_TRILINEAR_SAMPLINGMODE=tt.TEXTURE_TRILINEAR_SAMPLINGMODE,Ui.TEXTURE_NEAREST_NEAREST_MIPLINEAR=tt.TEXTURE_NEAREST_NEAREST_MIPLINEAR,Ui.TEXTURE_LINEAR_LINEAR_MIPNEAREST=tt.TEXTURE_LINEAR_LINEAR_MIPNEAREST,Ui.TEXTURE_LINEAR_LINEAR_MIPLINEAR=tt.TEXTURE_LINEAR_LINEAR_MIPLINEAR,Ui.TEXTURE_NEAREST_NEAREST_MIPNEAREST=tt.TEXTURE_NEAREST_NEAREST_MIPNEAREST,Ui.TEXTURE_NEAREST_LINEAR_MIPNEAREST=tt.TEXTURE_NEAREST_LINEAR_MIPNEAREST,Ui.TEXTURE_NEAREST_LINEAR_MIPLINEAR=tt.TEXTURE_NEAREST_LINEAR_MIPLINEAR,Ui.TEXTURE_NEAREST_LINEAR=tt.TEXTURE_NEAREST_LINEAR,Ui.TEXTURE_NEAREST_NEAREST=tt.TEXTURE_NEAREST_NEAREST,Ui.TEXTURE_LINEAR_NEAREST_MIPNEAREST=tt.TEXTURE_LINEAR_NEAREST_MIPNEAREST,Ui.TEXTURE_LINEAR_NEAREST_MIPLINEAR=tt.TEXTURE_LINEAR_NEAREST_MIPLINEAR,Ui.TEXTURE_LINEAR_LINEAR=tt.TEXTURE_LINEAR_LINEAR,Ui.TEXTURE_LINEAR_NEAREST=tt.TEXTURE_LINEAR_NEAREST,Ui.TEXTURE_EXPLICIT_MODE=tt.TEXTURE_EXPLICIT_MODE,Ui.TEXTURE_SPHERICAL_MODE=tt.TEXTURE_SPHERICAL_MODE,Ui.TEXTURE_PLANAR_MODE=tt.TEXTURE_PLANAR_MODE,Ui.TEXTURE_CUBIC_MODE=tt.TEXTURE_CUBIC_MODE,Ui.TEXTURE_PROJECTION_MODE=tt.TEXTURE_PROJECTION_MODE,Ui.TEXTURE_SKYBOX_MODE=tt.TEXTURE_SKYBOX_MODE,Ui.TEXTURE_INVCUBIC_MODE=tt.TEXTURE_INVCUBIC_MODE,Ui.TEXTURE_EQUIRECTANGULAR_MODE=tt.TEXTURE_EQUIRECTANGULAR_MODE,Ui.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=tt.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,Ui.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=tt.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,Ui.SCALEMODE_FLOOR=tt.SCALEMODE_FLOOR,Ui.SCALEMODE_NEAREST=tt.SCALEMODE_NEAREST,Ui.SCALEMODE_CEILING=tt.SCALEMODE_CEILING;const ki=G.Compose(B.One(),k.FromEulerAngles(0,Math.PI,0),B.Zero());class Gi extends re{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=!!(this._billboardMode&Gi.BILLBOARDMODE_USE_POSITION),this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==Gi.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t,!1),this._forward=new B(0,0,1),this._up=new B(0,1,0),this._right=new B(1,0,0),this._position=B.Zero(),this._rotation=B.Zero(),this._rotationQuaternion=null,this._scaling=B.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=Gi.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=G.Zero(),this._usePivotMatrix=!1,this._absolutePosition=B.Zero(),this._absoluteScaling=B.Zero(),this._absoluteRotationQuaternion=k.Identity(),this._pivotMatrix=G.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new g,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return B.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return B.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return B.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=G.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return this._billboardMode===e.billboardMode&&this._billboardMode===Gi.BILLBOARDMODE_NONE&&(!e.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,e.useBillboardPath=!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=G.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const s=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);s&&i&&i(this,s);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||k.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,i,s;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],s=arguments[2]}else t=e.x,i=e.y,s=e.z;if(this.parent){const e=X.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),B.TransformCoordinatesFromFloatsToRef(t,i,s,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=s;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=B.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=X.Matrix[0];return this._localMatrix.invertToRef(e),B.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=B.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,n=0){const r=Gi._LookAtVectorCache,a=0===n?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,r),this.setDirection(r,t,i,s),1===n&&this.parent)if(this.rotationQuaternion){const e=X.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=X.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=X.Quaternion[0];k.FromEulerVectorToRef(this.rotation,e);const t=X.Matrix[0];e.toRotationMatrix(t);const i=X.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=B.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return B.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const n=-Math.atan2(e.z,e.x)+Math.PI/2,r=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,r);return this.rotationQuaternion?k.RotationYawPitchRollToRef(n+t,a+i,s,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=n+t,this.rotation.z=s),this}setPivotPoint(e,t=0){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(1==t){const t=X.Matrix[0];i.invertToRef(t),e=B.TransformCoordinates(e,t)}return this.setPivotMatrix(G.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=B.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=B.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),B.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(e,t=!1,i=!1){if(!e&&!this.parent)return this;const s=X.Quaternion[0],n=X.Vector3[0],r=X.Vector3[1],a=X.Matrix[1];G.IdentityToRef(a);const o=X.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=Gi._TmpRotation,k.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),G.ComposeToRef(this.scaling,l,this.position,o),this.parent&&o.multiplyToRef(this.parent.computeWorldMatrix(!0),o),e&&(e.computeWorldMatrix(!0).invertToRef(a),o.multiplyToRef(a,o)),o.decompose(r,s,n,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(r),this.position.copyFrom(n),this.parent=e,i&&this.setPivotMatrix(G.Identity()),this}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return 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(e,t,i){let s;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&0!==i){if(this.parent){const i=this.parent.getWorldMatrix(),s=X.Matrix[0];i.invertToRef(s),e=B.TransformNormal(e,s),i.determinant()<0&&(t*=-1)}s=k.RotationAxisToRef(e,t,Gi._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else s=k.RotationAxisToRef(e,t,Gi._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=k.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=X.Vector3[0],n=X.Vector3[1],r=X.Vector3[2],a=X.Quaternion[0],o=X.Matrix[0],l=X.Matrix[1],h=X.Matrix[2],c=X.Matrix[3];return e.subtractToRef(this.position,s),G.TranslationToRef(s.x,s.y,s.z,o),G.TranslationToRef(-s.x,-s.y,-s.z,l),G.RotationAxisToRef(t,i,h),l.multiplyToRef(h,c),c.multiplyToRef(o,c),c.decompose(n,a,r),this.position.addInPlace(r),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(i&&0!==i)this.setAbsolutePosition(this.getAbsolutePosition().add(s));else{const e=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=X.Quaternion[1],k.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const n=X.Quaternion[0];return k.RotationYawPitchRollToRef(t,e,i,n),s.multiplyInPlace(n),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==Gi.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.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(),r=Gi._TmpScaling;let a,o=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new B(e.m[12],e.m[13],e.m[14]);o=Gi._TmpTranslation,o.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(r.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion){if(this._rotationQuaternion._isDirty=!1,a=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion){this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(k.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))}}else a=Gi._TmpRotation,k.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,a);if(this._usePivotMatrix){const e=X.Matrix[1];G.ScalingToRef(r.x,r.y,r.z,e);const t=X.Matrix[0];a.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,X.Matrix[4]),X.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else G.ComposeToRef(r,a,o,this._localMatrix);if(n&&n.getWorldMatrix){if(e&&n.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),X.Matrix[7])}else X.Matrix[7].copyFrom(n.getWorldMatrix());const e=X.Vector3[5],t=X.Vector3[6],i=X.Quaternion[0];X.Matrix[7].decompose(t,i,e),G.ScalingToRef(t.x,t.y,t.z,X.Matrix[7]),X.Matrix[7].setTranslation(e),Gi.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(X.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),X.Matrix[6]),X.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.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const e=X.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),X.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&X.Matrix[1].multiplyToRef(ki,X.Matrix[1]),X.Matrix[1].setTranslationFromFloats(0,0,0),X.Matrix[1].invertToRef(X.Matrix[0]),(this.billboardMode&Gi.BILLBOARDMODE_ALL)!==Gi.BILLBOARDMODE_ALL){X.Matrix[0].decompose(void 0,X.Quaternion[0],void 0);const e=X.Vector3[1];X.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Gi.BILLBOARDMODE_X)!==Gi.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Gi.BILLBOARDMODE_Y)!==Gi.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Gi.BILLBOARDMODE_Z)!==Gi.BILLBOARDMODE_Z&&(e.z=0),G.RotationYawPitchRollToRef(e.y,e.x,e.z,X.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(X.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(X.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const e=X.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(X.Matrix[1]);const s=X.Vector3[1];B.TransformCoordinatesToRef(i,X.Matrix[1],s),s.normalize();const n=-Math.atan2(s.z,s.x)+Math.PI/2,r=Math.sqrt(s.x*s.x+s.z*s.z),a=-Math.atan2(s.y,r);if(k.RotationYawPitchRollToRef(n,a,0,X.Quaternion[0]),(this.billboardMode&Gi.BILLBOARDMODE_ALL)!==Gi.BILLBOARDMODE_ALL){const e=X.Vector3[1];X.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Gi.BILLBOARDMODE_X)!==Gi.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Gi.BILLBOARDMODE_Y)!==Gi.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Gi.BILLBOARDMODE_Z)!==Gi.BILLBOARDMODE_Z&&(e.z=0),G.RotationYawPitchRollToRef(e.y,e.x,e.z,X.Matrix[0])}else G.FromQuaternionToRef(X.Quaternion[0],X.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(X.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(X.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=G.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 i=e[t];if(i){i.computeWorldMatrix();const e=X.Matrix[0];i._localMatrix.multiplyToRef(this._localMatrix,e);const t=X.Quaternion[0];e.decompose(i.scaling,t,i.position),i.rotationQuaternion?i.rotationQuaternion.copyFrom(t):t.toEulerAnglesToRef(i.rotation)}}}this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=k.Identity()),this._worldMatrix=G.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),B.TransformCoordinates(this.getAbsolutePosition(),e.getViewMatrix())}getDistanceToCamera(e=null){return e||(e=this.getScene().activeCamera),this.getAbsolutePosition().subtract(e.globalPosition).length()}clone(e,t,i){const s=se.Clone((()=>new Gi(e,this.getScene())),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i<t.length;i++){const n=t[i];n.clone&&n.clone(e+"."+n.name,s)}}return s}serialize(e){const t=se.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(),se.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t}static Parse(e,t,i){const s=se.Parse((()=>new Gi(e.name,t)),e,t,i);if(e.localMatrix?s.setPreTransformMatrix(G.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(G.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let t=0;t<e.animations.length;t++){const i=e.animations[t],n=b("BABYLON.Animation");n&&s.animations.push(n.Parse(i))}re.ParseAnimationRanges(s,e,t)}return e.autoAnimate&&t.beginAnimation(s,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),s}getChildTransformNodes(e,t){const i=[];return this._getDescendants(i,e,(e=>(!t||t(e))&&e instanceof Gi)),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,i){let s=null,n=null;t&&(this.rotationQuaternion?(n=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const r=this.getHierarchyBoundingVectors(e,i),a=r.max.subtract(r.min),o=Math.max(a.x,a.y,a.z);if(0===o)return this;const l=1/o;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&n?this.rotationQuaternion.copyFrom(n):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}var Vi,Xi,Hi;Gi.BILLBOARDMODE_NONE=0,Gi.BILLBOARDMODE_X=1,Gi.BILLBOARDMODE_Y=2,Gi.BILLBOARDMODE_Z=4,Gi.BILLBOARDMODE_ALL=7,Gi.BILLBOARDMODE_USE_POSITION=128,Gi.BillboardUseParentOrientation=!1,Gi._TmpRotation=k.Zero(),Gi._TmpScaling=B.Zero(),Gi._TmpTranslation=B.Zero(),Gi._LookAtVectorCache=new B(0,0,0),Gi._RotationAxisCache=new k,e([c("position")],Gi.prototype,"_position",void 0),e([c("rotation")],Gi.prototype,"_rotation",void 0),e([(Vi="rotationQuaternion",n(10,Vi))],Gi.prototype,"_rotationQuaternion",void 0),e([c("scaling")],Gi.prototype,"_scaling",void 0),e([a("billboardMode")],Gi.prototype,"_billboardMode",void 0),e([a()],Gi.prototype,"scalingDeterminant",void 0),e([a("infiniteDistance")],Gi.prototype,"_infiniteDistance",void 0),e([a()],Gi.prototype,"ignoreNonUniformScaling",void 0),e([a()],Gi.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class zi{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(li.NormalKind))return null;let i,s=this.pickedMesh.getIndices();0===s?.length&&(s=null);const n=X.Vector3[0],r=X.Vector3[1],a=X.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(li.NormalKind);let t=s?B.FromArrayToRef(e,3*s[3*this.faceId],n):n.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),o=s?B.FromArrayToRef(e,3*s[3*this.faceId+1],r):r.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=s?B.FromArrayToRef(e,3*s[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),l=l.scale(1-this.bu-this.bv),i=new B(t.x+o.x+l.x,t.y+o.y+l.y,t.z+o.z+l.z)}else{const e=this.pickedMesh.getVerticesData(li.PositionKind),t=s?B.FromArrayToRef(e,3*s[3*this.faceId],n):n.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),o=s?B.FromArrayToRef(e,3*s[3*this.faceId+1],r):r.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=s?B.FromArrayToRef(e,3*s[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]),h=t.subtract(o),c=l.subtract(o);i=B.Cross(h,c)}const o=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(X.Matrix[0].copyFrom(i),i=X.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(X.Matrix[1]),i=X.Matrix[1]),B.TransformNormalToRef(t,i,t)};if(e&&o(this.pickedMesh,i),this.ray){const t=X.Vector3[0].copyFrom(i);e||o(this.pickedMesh,t),B.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=li.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let s=w.FromArray(i,2*t[3*this.faceId]),n=w.FromArray(i,2*t[3*this.faceId+1]),r=w.FromArray(i,2*t[3*this.faceId+2]);return s=s.scale(this.bu),n=n.scale(this.bv),r=r.scale(1-this.bu-this.bv),new w(s.x+n.x+r.x,s.y+n.y+r.y)}}Pi.prototype.createUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create uniform buffer");const s=new xi(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},Pi.prototype.createDynamicUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create dynamic uniform buffer");const s=new xi(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},Pi.prototype.updateUniformBuffer=function(e,t,i,s){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===s?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+s)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+s)),this.bindUniformBuffer(null)},Pi.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},Pi.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},Pi.prototype.bindUniformBlock=function(e,t,i){const s=e.program,n=this._gl.getUniformBlockIndex(s,t);4294967295!==n&&this._gl.uniformBlockBinding(s,n,i)};class Wi{constructor(e,t,i,s,n=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||n,this._dynamic=i,this._name=s??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=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 void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_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 i=this._uniformLocationPointer-e;for(let e=0;e<i;e++)this._data.push(0)}}addUniform(e,t,i=0){if(this._noUBO)return;if(void 0!==this._uniformLocations[e])return;let s;if(i>0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t)t*=i;else{t=t*i+(4-t)*i}s=[];for(let e=0;e<t;e++)s.push(0)}else{if(t instanceof Array)s=t,t=s.length;else{s=[];for(let e=0;e<t;e++)s.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(s[e]);this._needSync=!0}addMatrix(e,t){this.addUniform(e,Array.prototype.slice.call(t.asArray()))}addFloat2(e,t,i){const s=[t,i];this.addUniform(e,s)}addFloat3(e,t,i,s){const n=[t,i,s];this.addUniform(e,n)}addColor3(e,t){const i=[t.r,t.g,t.b];this.addUniform(e,i)}addColor4(e,t,i){const s=[t.r,t.g,t.b,i];this.addUniform(e,s)}addVector3(e,t){const i=[t.x,t.y,t.z];this.addUniform(e,i)}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)}_getNames(){const e=[];let t=0;for(const i in this._uniformLocations)if(e.push(i),10==++t)break;return e.join(",")}_rebuild(){!this._noUBO&&this._bufferData&&(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNames()):this._buffer=this._engine.createUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNames()),this._engine._features.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._engine._features.trackUbosInFrame&&(this._buffers=[],this._currentFrameId=0),this._rebuild()}get _numBuffers(){return this._buffers.length}get _indexBuffer(){return this._bufferIndex}get name(){return this._name}get currentEffect(){return this._currentEffect}_buffersEqual(e,t){for(let i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0}_copyBuffer(e,t){for(let i=0;i<e.length;++i)t[i]=e[i]}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._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(Wi._UpdatedUbosInFrame[this._name]||(Wi._UpdatedUbosInFrame[this._name]=0),Wi._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.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._engine._features.trackUbosInFrame&&this._currentFrameId!==this._engine.frameId&&(this._currentFrameId=this._engine.frameId,this._createBufferOnWrite=!1,this._buffers&&this._buffers.length>0?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let s=this._uniformLocations[e];if(void 0===s){if(this._buffer)return void ce.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e<i;e++)this._bufferData[s+e]=t[e];else{let e=!1;for(let n=0;n<i;n++)(16===i&&!this._engine._features.uniformBufferHardCheckMatrix||this._bufferData[s+n]!==Math.fround(t[n]))&&(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[s+n]=t[n]);this._needSync=this._needSync||e}}updateUniformArray(e,t,i){this._checkNewFrame();const s=this._uniformLocations[e];if(void 0===s)return void ce.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 n=this._uniformArraySizes[e];if(this._dynamic)for(let e=0;e<i;e++)this._bufferData[s+e]=t[e];else{let e=!1,r=0,a=0;for(let o=0;o<i;o++)if(this._bufferData[s+4*a+r]!==Qt.FloatRound(t[o])&&(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[s+4*a+r]=t[o]),r++,r===n.strideSize){for(;r<4;r++)this._bufferData[s+4*a+r]=0;r=0,a++}this._needSync=this._needSync||e}}_cacheMatrix(e,t){this._checkNewFrame();const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_updateMatrix3x3ForUniform(e,t){for(let e=0;e<3;e++)Wi._TempBuffer[4*e]=t[3*e],Wi._TempBuffer[4*e+1]=t[3*e+1],Wi._TempBuffer[4*e+2]=t[3*e+2],Wi._TempBuffer[4*e+3]=0;this.updateUniform(e,Wi._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++)Wi._TempBuffer[4*e]=t[2*e],Wi._TempBuffer[4*e+1]=t[2*e+1],Wi._TempBuffer[4*e+2]=0,Wi._TempBuffer[4*e+3]=0;this.updateUniform(e,Wi._TempBuffer,8)}_updateFloatForEffect(e,t){this._currentEffect.setFloat(e,t)}_updateFloatForUniform(e,t){Wi._TempBuffer[0]=t,this.updateUniform(e,Wi._TempBuffer,1)}_updateFloat2ForEffect(e,t,i,s=""){this._currentEffect.setFloat2(e+s,t,i)}_updateFloat2ForUniform(e,t,i){Wi._TempBuffer[0]=t,Wi._TempBuffer[1]=i,this.updateUniform(e,Wi._TempBuffer,2)}_updateFloat3ForEffect(e,t,i,s,n=""){this._currentEffect.setFloat3(e+n,t,i,s)}_updateFloat3ForUniform(e,t,i,s){Wi._TempBuffer[0]=t,Wi._TempBuffer[1]=i,Wi._TempBuffer[2]=s,this.updateUniform(e,Wi._TempBuffer,3)}_updateFloat4ForEffect(e,t,i,s,n,r=""){this._currentEffect.setFloat4(e+r,t,i,s,n)}_updateFloat4ForUniform(e,t,i,s,n){Wi._TempBuffer[0]=t,Wi._TempBuffer[1]=i,Wi._TempBuffer[2]=s,Wi._TempBuffer[3]=n,this.updateUniform(e,Wi._TempBuffer,4)}_updateFloatArrayForEffect(e,t){this._currentEffect.setFloatArray(e,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){Wi._TempBufferInt32View.set(t),this.updateUniformArray(e,Wi._TempBuffer,t.length)}_updateUIntArrayForEffect(e,t){this._currentEffect.setUIntArray(e,t)}_updateUIntArrayForUniform(e,t){Wi._TempBufferUInt32View.set(t),this.updateUniformArray(e,Wi._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){Wi._TempBuffer[0]=t.x,Wi._TempBuffer[1]=t.y,Wi._TempBuffer[2]=t.z,this.updateUniform(e,Wi._TempBuffer,3)}_updateVector4ForEffect(e,t){this._currentEffect.setVector4(e,t)}_updateVector4ForUniform(e,t){Wi._TempBuffer[0]=t.x,Wi._TempBuffer[1]=t.y,Wi._TempBuffer[2]=t.z,Wi._TempBuffer[3]=t.w,this.updateUniform(e,Wi._TempBuffer,4)}_updateColor3ForEffect(e,t,i=""){this._currentEffect.setColor3(e+i,t)}_updateColor3ForUniform(e,t){Wi._TempBuffer[0]=t.r,Wi._TempBuffer[1]=t.g,Wi._TempBuffer[2]=t.b,this.updateUniform(e,Wi._TempBuffer,3)}_updateColor4ForEffect(e,t,i,s=""){this._currentEffect.setColor4(e+s,t,i)}_updateDirectColor4ForEffect(e,t,i=""){this._currentEffect.setDirectColor4(e+i,t)}_updateColor4ForUniform(e,t,i){Wi._TempBuffer[0]=t.r,Wi._TempBuffer[1]=t.g,Wi._TempBuffer[2]=t.b,Wi._TempBuffer[3]=i,this.updateUniform(e,Wi._TempBuffer,4)}_updateDirectColor4ForUniform(e,t){Wi._TempBuffer[0]=t.r,Wi._TempBuffer[1]=t.g,Wi._TempBuffer[2]=t.b,Wi._TempBuffer[3]=t.a,this.updateUniform(e,Wi._TempBuffer,4)}_updateIntForEffect(e,t,i=""){this._currentEffect.setInt(e+i,t)}_updateIntForUniform(e,t){Wi._TempBufferInt32View[0]=t,this.updateUniform(e,Wi._TempBuffer,1)}_updateInt2ForEffect(e,t,i,s=""){this._currentEffect.setInt2(e+s,t,i)}_updateInt2ForUniform(e,t,i){Wi._TempBufferInt32View[0]=t,Wi._TempBufferInt32View[1]=i,this.updateUniform(e,Wi._TempBuffer,2)}_updateInt3ForEffect(e,t,i,s,n=""){this._currentEffect.setInt3(e+n,t,i,s)}_updateInt3ForUniform(e,t,i,s){Wi._TempBufferInt32View[0]=t,Wi._TempBufferInt32View[1]=i,Wi._TempBufferInt32View[2]=s,this.updateUniform(e,Wi._TempBuffer,3)}_updateInt4ForEffect(e,t,i,s,n,r=""){this._currentEffect.setInt4(e+r,t,i,s,n)}_updateInt4ForUniform(e,t,i,s,n){Wi._TempBufferInt32View[0]=t,Wi._TempBufferInt32View[1]=i,Wi._TempBufferInt32View[2]=s,Wi._TempBufferInt32View[3]=n,this.updateUniform(e,Wi._TempBuffer,4)}_updateUIntForEffect(e,t,i=""){this._currentEffect.setUInt(e+i,t)}_updateUIntForUniform(e,t){Wi._TempBufferUInt32View[0]=t,this.updateUniform(e,Wi._TempBuffer,1)}_updateUInt2ForEffect(e,t,i,s=""){this._currentEffect.setUInt2(e+s,t,i)}_updateUInt2ForUniform(e,t,i){Wi._TempBufferUInt32View[0]=t,Wi._TempBufferUInt32View[1]=i,this.updateUniform(e,Wi._TempBuffer,2)}_updateUInt3ForEffect(e,t,i,s,n=""){this._currentEffect.setUInt3(e+n,t,i,s)}_updateUInt3ForUniform(e,t,i,s){Wi._TempBufferUInt32View[0]=t,Wi._TempBufferUInt32View[1]=i,Wi._TempBufferUInt32View[2]=s,this.updateUniform(e,Wi._TempBuffer,3)}_updateUInt4ForEffect(e,t,i,s,n,r=""){this._currentEffect.setUInt4(e+r,t,i,s,n)}_updateUInt4ForUniform(e,t,i,s,n){Wi._TempBufferUInt32View[0]=t,Wi._TempBufferUInt32View[1]=i,Wi._TempBufferUInt32View[2]=s,Wi._TempBufferUInt32View[3]=n,this.updateUniform(e,Wi._TempBuffer,4)}setTexture(e,t){this._currentEffect.setTexture(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,!0}return!1}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._engine._features.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)}}Wi._UpdatedUbosInFrame={},Wi._MAX_UNIFORM_SIZE=256,Wi._TempBuffer=new Float32Array(Wi._MAX_UNIFORM_SIZE),Wi._TempBufferInt32View=new Int32Array(Wi._TempBuffer.buffer),Wi._TempBufferUInt32View=new Uint32Array(Wi._TempBuffer.buffer);class Yi{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new B(0,0,0),this._diffPositionForCollisions=new B(0,0,0),this._collisionResponse=!0}}!function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(Xi||(Xi={}));class Ki{}Ki.X=new B(1,0,0),Ki.Y=new B(0,1,0),Ki.Z=new B(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Hi||(Hi={}));class qi{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=B.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class Qi{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new qi,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=null,this._currentLODIsUpToDate=!1,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new Yi,this._enableDistantPicking=!1,this._rawBoundingInfo=null,this._sideOrientationHint=!1,this._inheritVisibility=!1}}class ji extends Gi{static get BILLBOARDMODE_NONE(){return Gi.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Gi.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Gi.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Gi.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Gi.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Gi.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 inheritVisibility(){return this._internalAbstractMeshDataInfo._inheritVisibility}set inheritVisibility(e){this._internalAbstractMeshDataInfo._inheritVisibility=e}get isVisible(){if(!this._isVisible||!this.inheritVisibility||!this._parentNode)return this._isVisible;if(this._isVisible){let e=this._parentNode;for(;e;){const t=e.isVisible;if(void 0!==t)return t;e=e.parent}}return this._isVisible}set isVisible(e){this._isVisible=e}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(),this._unBindEffect()))}getMaterialForRenderPass(e){return this._internalAbstractMeshDataInfo._materialForRenderPass?.[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}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(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new Qi,this._waitingMaterialId=null,this.cullingStrategy=ji.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new g,this.onCollisionPositionChangeObservable=new g,this.onMaterialChangedObservable=new g,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this._isVisible=!0,this.isPickable=!0,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=J.Red(),this.outlineWidth=.02,this.overlayColor=J.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 B(.5,1,.5),this.ellipsoidOffset=new B(0,0,0),this.edgesWidth=1,this.edgesColor=new ee(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 g,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Ui.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new Wi(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.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 i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.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!==Gi.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}_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),i=this._lightSources.indexOf(e);let s=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;s=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(s)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;i<t._drawWrappers.length;++i){const s=t._drawWrappers[i];s&&s.defines&&s.defines.markAllAsDirty&&e(s.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,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,s){return this}updateVerticesData(e,t,i,s){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,i){return this._boundingInfo=new pi(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(li.MatricesIndicesKind)&&this.isVerticesDataPresent(li.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===Gi.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,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const s=new G;(this.rotationQuaternion?this.rotationQuaternion:k.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const n=B.Zero(),r=this.definedFacingForward?-1:1;return B.TransformCoordinatesFromFloatsToRef(e*r,t,i*r,s,n),n}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const s=this.definedFacingForward?1:-1;return new B(e*s,t,i*s)}_refreshBoundingInfo(e,t){if(e){const i=Ei(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new pi(i.minimum,i.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 pi(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,i,s,n,r,a){!function(e,t,i,s,n,r,a){const o=X.Vector3[0],l=X.Matrix[0],h=X.Matrix[1],c=t===li.NormalKind?B.TransformNormalFromFloatsToRef:B.TransformCoordinatesFromFloatsToRef;for(let t=0,u=0;t<e.length;t+=3,u+=4){let d,_;for(l.reset(),d=0;d<4;d++)_=n[u+d],_>0&&(G.FromFloat32ArrayToRefScaled(i,Math.floor(16*s[u+d]),_,h),l.addToSelf(h));if(r&&a)for(d=0;d<4;d++)_=a[u+d],_>0&&(G.FromFloat32ArrayToRefScaled(i,Math.floor(16*r[u+d]),_,h),l.addToSelf(h));c(e[t],e[t+1],e[t+2],l,o),o.toArray(e,t)}}(e,t,i,s,n,r,a)}_getData(e,t,i=li.PositionKind){const s=e.cache,n=e=>{if(s){const t=s._vertexData||={};return t[e]||this.copyVerticesData(e,t),t[e]}return this.getVerticesData(e)};if(t||=n(i),!t)return null;if(s?(s._outputData?s._outputData.set(t):s._outputData=new Float32Array(t),t=s._outputData):(e.applyMorph&&this.morphTargetManager||e.applySkeleton&&this.skeleton)&&(t=t.slice()),e.applyMorph&&this.morphTargetManager&&function(e,t,i){let s=null;switch(t){case li.PositionKind:s=e=>e.getPositions();break;case li.NormalKind:s=e=>e.getNormals();break;case li.TangentKind:s=e=>e.getTangents();break;case li.UVKind:s=e=>e.getUVs();break;default:return}for(let t=0;t<e.length;t++){let n=e[t];for(let r=0;r<i.numTargets;r++){const a=i.getTarget(r),o=a.influence;if(0!==o){const i=s(a);i&&(n+=(i[t]-e[t])*o)}}e[t]=n}}(t,i,this.morphTargetManager),e.applySkeleton&&this.skeleton){const e=n(li.MatricesIndicesKind),s=n(li.MatricesWeightsKind);if(s&&e){const r=this.numBoneInfluencers>4,a=r?n(li.MatricesIndicesExtraKind):null,o=r?n(li.MatricesWeightsExtraKind):null,l=this.skeleton.getTransformMatrices(this);ji._ApplySkeleton(t,i,l,e,s,a,o)}}if(!1!==e.updatePositionsArray&&i===li.PositionKind){const e=this._internalAbstractMeshDataInfo._positions||[],i=e.length;if(e.length=t.length/3,i<e.length)for(let t=i;t<e.length;t++)e[t]=new B;for(let i=0,s=0;i<e.length;i++,s+=3)e[i].copyFromFloats(t[s],t[s+1],t[s+2]);this._internalAbstractMeshDataInfo._positions=e}return t}getNormalsData(e=!1,t=!1){return this._getData({applySkeleton:e,applyMorph:t,updatePositionsArray:!1},null,li.NormalKind)}getPositionData(e=!1,t=!1,i=null){return this._getData({applySkeleton:e,applyMorph:t,updatePositionsArray:!1},i,li.PositionKind)}_updateBoundingInfo(){return this._boundingInfo?this._boundingInfo.update(this.worldMatrixFromCache):this._boundingInfo=new pi(B.Zero(),B.Zero(),this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}_updateSubMeshesBoundingInfo(e){if(!this.subMeshes)return this;const t=this.subMeshes.length;for(let i=0;i<t;i++){const s=this.subMeshes[i];(t>1||!s.IsGlobal)&&s.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,i){const s=this.getBoundingInfo(),n=e.getBoundingInfo();if(s.intersects(n,t))return!0;if(i)for(const i of this.getChildMeshes())if(i.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){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const t=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=t.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const i=e.verticesStart,s=e.verticesStart+e.verticesCount;for(let n=i;n<s;n++)e._lastColliderWorldVertices.push(B.TransformCoordinates(this._positions[n],t))}return i._collide(e._trianglePlanes,e._lastColliderWorldVertices,this.getIndices(),e.indexStart,e.indexStart+e.indexCount,e.verticesStart,!!e.getMaterial(),this,this._shouldConvertRHS(),e.getMaterial()?.fillMode===tt.MATERIAL_TriangleStripDrawMode),this}_processCollisionsForSubMeshes(e,t){const i=this._scene.getCollidingSubMeshCandidates(this,e),s=i.length;for(let n=0;n<s;n++){const r=i.data[n];s>1&&!r._checkCollision(e)||this._collideForSubMesh(r,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=X.Matrix[0],i=X.Matrix[1];return G.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,s=!1,n,r=!1){const a=new zi,o=this.getClassName(),l="InstancedLinesMesh"===o||"LinesMesh"===o||"GreasedLineMesh"===o?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes)return a;if(!(r||e.intersectsSphere(h.boundingSphere,l)&&e.intersectsBox(h.boundingBox,l)))return a;if(s)return a.hit=!r,a.pickedMesh=r?null:this,a.distance=r?0:B.Distance(e.origin,h.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==tt.MATERIAL_TriangleStripDrawMode||t.fillMode==tt.MATERIAL_TriangleFillMode||t.fillMode==tt.MATERIAL_WireFrameFillMode||t.fillMode==tt.MATERIAL_PointFillMode||t.fillMode==tt.MATERIAL_LineListDrawMode)){_=!0;break}}if(!_)return a.hit=!0,a.pickedMesh=this,a.distance=B.Distance(e.origin,h.boundingSphere.center),a.subMeshId=-1,a;for(let s=0;s<d;s++){const n=u.data[s];if(d>1&&!r&&!n.canIntersects(e))continue;const a=n.intersects(e,this._positions,this.getIndices(),t,i);if(a&&(t||!c||a.distance<c.distance)&&(c=a,c.subMeshId=s,t))break}if(c){const t=n??this.getWorldMatrix(),i=X.Vector3[0],s=X.Vector3[1];B.TransformCoordinatesToRef(e.origin,t,i),e.direction.scaleToRef(c.distance,s);const r=B.TransformNormal(s,t).addInPlace(i);return a.hit=!0,a.distance=B.Distance(i,r),a.pickedPoint=r,a.pickedMesh=this,a.bu=c.bu||0,a.bv=c.bv||0,a.subMeshFaceId=c.faceId,a.faceId=c.faceId+u.data[c.subMeshId].indexStart/(-1!==this.getClassName().indexOf("LinesMesh")?2:3),a.subMeshId=c.subMeshId,a}return a}clone(e,t,i){return null}releaseSubMeshes(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=[];return this}dispose(e,t=!1){let i;const s=this.getScene();for(this._scene.useMaterialMeshMap&&this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),s.freeActiveMeshes(),s.freeRenderingGroups(),s.renderingManager.maintainStateBetweenFrames&&s.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),i=0;i<this._intersectionsInProgress.length;i++){const e=this._intersectionsInProgress[i],t=e._intersectionsInProgress.indexOf(this);e._intersectionsInProgress.splice(t,1)}this._intersectionsInProgress.length=0;s.lights.forEach((e=>{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 i=e.getShadowGenerators();if(i){const e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){const e=i.value.getShadowMap();e&&e.renderList&&(t=e.renderList.indexOf(this),-1!==t&&e.renderList.splice(t,1))}}})),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();const n=s.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,n.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),n.wipeCaches(),s.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(i=0;i<s.particleSystems.length;i++)s.particleSystems[i].emitter===this&&(s.particleSystems[i].dispose(),i--);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]=B.Zero(),e.facetPositions[t]=B.Zero();return e.facetDataEnabled=!0,this}updateFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();const t=this.getVerticesData(li.PositionKind),i=this.getIndices(),s=this.getVerticesData(li.NormalKind),n=this.getBoundingInfo();if(e.facetDepthSort&&!e.facetDepthSortEnabled){if(e.facetDepthSortEnabled=!0,i instanceof Uint16Array)e.depthSortedIndices=new Uint16Array(i);else if(i instanceof Uint32Array)e.depthSortedIndices=new Uint32Array(i);else{let t=!1;for(let e=0;e<i.length;e++)if(i[e]>65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:B.Zero()}e.depthSortedFacets=[];for(let t=0;t<e.facetNb;t++){const i={ind:3*t,sqDistance:0};e.depthSortedFacets.push(i)}e.invertedMatrix=G.Identity(),e.facetDepthSortOrigin=B.Zero()}e.bbSize.x=n.maximum.x-n.minimum.x>A?n.maximum.x-n.minimum.x:A,e.bbSize.y=n.maximum.y-n.minimum.y>A?n.maximum.y-n.minimum.y:A,e.bbSize.z=n.maximum.z-n.minimum.z>A?n.maximum.z-n.minimum.z:A;let r=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(r=r>e.bbSize.z?r:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/r),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/r),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/r),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=n,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),B.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&vi.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let s=0;s<t;s++){const t=e.depthSortedFacets[s].ind;e.depthSortedIndices[3*s]=i[t],e.depthSortedIndices[3*s+1]=i[t+1],e.depthSortedIndices[3*s+2]=i[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=B.Zero();return this.getFacetPositionToRef(e,t),t}getFacetPositionToRef(e,t){const i=this.getFacetLocalPositions()[e],s=this.getWorldMatrix();return B.TransformCoordinatesToRef(i,s,t),this}getFacetNormal(e){const t=B.Zero();return this.getFacetNormalToRef(e,t),t}getFacetNormalToRef(e,t){const i=this.getFacetLocalNormals()[e];return B.TransformNormalToRef(i,this.getWorldMatrix(),t),this}getFacetsAtLocalCoordinates(e,t,i){const s=this.getBoundingInfo(),n=this._internalAbstractMeshDataInfo._facetData,r=Math.floor((e-s.minimum.x*n.partitioningBBoxRatio)*n.subDiv.X*n.partitioningBBoxRatio/n.bbSize.x),a=Math.floor((t-s.minimum.y*n.partitioningBBoxRatio)*n.subDiv.Y*n.partitioningBBoxRatio/n.bbSize.y),o=Math.floor((i-s.minimum.z*n.partitioningBBoxRatio)*n.subDiv.Z*n.partitioningBBoxRatio/n.bbSize.z);return r<0||r>n.subDiv.max||a<0||a>n.subDiv.max||o<0||o>n.subDiv.max?null:n.facetPartitioning[r+n.subDiv.max*a+n.subDiv.max*n.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,i,s,n=!1,r=!0){const a=this.getWorldMatrix(),o=X.Matrix[5];a.invertToRef(o);const l=X.Vector3[8];B.TransformCoordinatesFromFloatsToRef(e,t,i,o,l);const h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,s,n,r);return s&&B.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,a,s),h}getClosestFacetAtLocalCoordinates(e,t,i,s,n=!1,r=!0){let a=null,o=0,l=0,h=0,c=0,u=0,d=0,_=0,f=0;const m=this.getFacetLocalPositions(),p=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let E,T,A,R=Number.MAX_VALUE,v=R;for(let I=0;I<g.length;I++)E=g[I],T=p[E],A=m[E],c=(e-A.x)*T.x+(t-A.y)*T.y+(i-A.z)*T.z,(!n||n&&r&&c>=0||n&&!r&&c<=0)&&(c=T.x*A.x+T.y*A.y+T.z*A.z,u=-(T.x*e+T.y*t+T.z*i-c)/(T.x*T.x+T.y*T.y+T.z*T.z),d=e+T.x*u,_=t+T.y*u,f=i+T.z*u,o=d-e,l=_-t,h=f-i,v=o*o+l*l+h*h,v<R&&(R=v,a=E,s&&(s.x=d,s.y=_,s.z=f)));return a}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=null,e.depthSortedIndices=new Uint32Array(0)),this}updateIndices(e,t,i=!1){return this}createNormals(e){const t=this.getVerticesData(li.PositionKind),i=this.getIndices();let s;return s=this.isVerticesDataPresent(li.NormalKind)?this.getVerticesData(li.NormalKind):[],vi.ComputeNormals(t,i,s,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(li.NormalKind,s,e),this}alignWithNormal(e,t){t||(t=Ki.Y);const i=X.Vector3[0],s=X.Vector3[1];return B.CrossToRef(t,e,s),B.CrossToRef(e,s,i),this.rotationQuaternion?k.RotationQuaternionFromAxisToRef(i,e,s,this.rotationQuaternion):B.RotationFromAxisToRef(i,e,s,this.rotation),this}_checkOcclusionQuery(){return!1}disableEdgesRendering(){throw W("EdgesRenderer")}enableEdgesRendering(e,t,i){throw W("EdgesRenderer")}getConnectedParticleSystems(){return this._scene.particleSystems.filter((e=>e.emitter===this))}}ji.OCCLUSION_TYPE_NONE=0,ji.OCCLUSION_TYPE_OPTIMISTIC=1,ji.OCCLUSION_TYPE_STRICT=2,ji.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,ji.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,ji.CULLINGSTRATEGY_STANDARD=tt.MESHES_CULLINGSTRATEGY_STANDARD,ji.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=tt.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,ji.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=tt.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION,ji.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=tt.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY,e([f.filter(((...[e,t,i,s,n])=>!(Array.isArray(e)||Array.isArray(t)||Array.isArray(i)||Array.isArray(s)||Array.isArray(n))))],ji,"_ApplySkeleton",null),C("BABYLON.AbstractMesh",ji);class Zi{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=tt.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=tt.KEEP,this.opDepthFail=tt.KEEP,this.opStencilDepthPass=tt.REPLACE}get func(){return this._func}set func(e){this._func=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 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){se.Clone((()=>e),this)}serialize(){return se.Serialize(this)}parse(e,t,i){se.Parse((()=>this),e,t,i)}}e([a()],Zi.prototype,"func",null),e([a()],Zi.prototype,"funcRef",null),e([a()],Zi.prototype,"funcMask",null),e([a()],Zi.prototype,"opStencilFail",null),e([a()],Zi.prototype,"opDepthFail",null),e([a()],Zi.prototype,"opStencilDepthPass",null),e([a()],Zi.prototype,"mask",null),e([a()],Zi.prototype,"enabled",null);class $i{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}function Ji(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}$i.FALLOFF_DEFAULT=0,$i.FALLOFF_PHYSICAL=1,$i.FALLOFF_GLTF=2,$i.FALLOFF_STANDARD=3,$i.LIGHTMAP_DEFAULT=0,$i.LIGHTMAP_SPECULAR=1,$i.LIGHTMAP_SHADOWSONLY=2,$i.INTENSITYMODE_AUTOMATIC=0,$i.INTENSITYMODE_LUMINOUSPOWER=1,$i.INTENSITYMODE_LUMINOUSINTENSITY=2,$i.INTENSITYMODE_ILLUMINANCE=3,$i.INTENSITYMODE_LUMINANCE=4,$i.LIGHTTYPEID_POINTLIGHT=0,$i.LIGHTTYPEID_DIRECTIONALLIGHT=1,$i.LIGHTTYPEID_SPOTLIGHT=2,$i.LIGHTTYPEID_HEMISPHERICLIGHT=3;const es=J.Black();function ts(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}function is(e,t,i){const s=e.getTextureMatrix();t.updateMatrix(i+"Matrix",s)}function ss(e,t,i,s,n,r=!0){e._bindLight(t,i,s,n,r)}function ns(e,t,i,s,n,r,a,o=!1){a._areMiscDirty&&(a.LOGARITHMICDEPTH=i,a.POINTSIZE=s,a.FOG=n&&function(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==tt.FOGMODE_NONE}(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=r,a.DECAL_AFTER_DETAIL=o)}function rs(e,t,i,s,n,r,a){switch(a.needNormals=!0,void 0===n["LIGHT"+s]&&(a.needRebuild=!0),n["LIGHT"+s]=!0,n["SPOTLIGHT"+s]=!1,n["HEMILIGHT"+s]=!1,n["POINTLIGHT"+s]=!1,n["DIRLIGHT"+s]=!1,i.prepareLightSpecificDefines(n,s),n["LIGHT_FALLOFF_PHYSICAL"+s]=!1,n["LIGHT_FALLOFF_GLTF"+s]=!1,n["LIGHT_FALLOFF_STANDARD"+s]=!1,i.falloffType){case $i.FALLOFF_GLTF:n["LIGHT_FALLOFF_GLTF"+s]=!0;break;case $i.FALLOFF_PHYSICAL:n["LIGHT_FALLOFF_PHYSICAL"+s]=!0;break;case $i.FALLOFF_STANDARD:n["LIGHT_FALLOFF_STANDARD"+s]=!0}if(i.specular.equalsFloats(0,0,0)||(a.specularEnabled=!0),n["SHADOW"+s]=!1,n["SHADOWCSM"+s]=!1,n["SHADOWCSMDEBUG"+s]=!1,n["SHADOWCSMNUM_CASCADES"+s]=!1,n["SHADOWCSMUSESHADOWMAXZ"+s]=!1,n["SHADOWCSMNOBLEND"+s]=!1,n["SHADOWCSM_RIGHTHANDED"+s]=!1,n["SHADOWPCF"+s]=!1,n["SHADOWPCSS"+s]=!1,n["SHADOWPOISSON"+s]=!1,n["SHADOWESM"+s]=!1,n["SHADOWCLOSEESM"+s]=!1,n["SHADOWCUBE"+s]=!1,n["SHADOWLOWQUALITY"+s]=!1,n["SHADOWMEDIUMQUALITY"+s]=!1,t&&t.receiveShadows&&e.shadowsEnabled&&i.shadowEnabled){const t=i.getShadowGenerator(e.activeCamera)??i.getShadowGenerator();if(t){const e=t.getShadowMap();e&&e.renderList&&e.renderList.length>0&&(a.shadowEnabled=!0,t.prepareDefines(n,s))}}i.lightmapMode!=$i.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,n["LIGHTMAPEXCLUDED"+s]=!0,n["LIGHTMAPNOSPECULAR"+s]=i.lightmapMode==$i.LIGHTMAP_SHADOWSONLY):(n["LIGHTMAPEXCLUDED"+s]=!1,n["LIGHTMAPNOSPECULAR"+s]=!1)}function as(e,t,i,s,n,r=null,a=!1){let o=function(e,t){let i=!1;if(e.activeCamera){const s=t.CAMERA_ORTHOGRAPHIC?1:0,n=t.CAMERA_PERSPECTIVE?1:0,r=e.activeCamera.mode===tt.ORTHOGRAPHIC_CAMERA?1:0,a=e.activeCamera.mode===tt.PERSPECTIVE_CAMERA?1:0;(s^r||n^a)&&(t.CAMERA_ORTHOGRAPHIC=1===r,t.CAMERA_PERSPECTIVE=1===a,i=!0)}return i}(e,s);!1!==r&&(o=function(e,t,i){let s=!1;const n=!!(e.clipPlane??t.clipPlane),r=!!(e.clipPlane2??t.clipPlane2),a=!!(e.clipPlane3??t.clipPlane3),o=!!(e.clipPlane4??t.clipPlane4),l=!!(e.clipPlane5??t.clipPlane5),h=!!(e.clipPlane6??t.clipPlane6);return i.CLIPPLANE!==n&&(i.CLIPPLANE=n,s=!0),i.CLIPPLANE2!==r&&(i.CLIPPLANE2=r,s=!0),i.CLIPPLANE3!==a&&(i.CLIPPLANE3=a,s=!0),i.CLIPPLANE4!==o&&(i.CLIPPLANE4=o,s=!0),i.CLIPPLANE5!==l&&(i.CLIPPLANE5=l,s=!0),i.CLIPPLANE6!==h&&(i.CLIPPLANE6=h,s=!0),s}(i,e,s)),s.DEPTHPREPASS!==!t.getColorWrite()&&(s.DEPTHPREPASS=!s.DEPTHPREPASS,o=!0),s.INSTANCES!==n&&(s.INSTANCES=n,o=!0),s.THIN_INSTANCES!==a&&(s.THIN_INSTANCES=a,o=!0),o&&s.markAsUnprocessed()}function os(e,t,i,s,n=null,r=!1){n&&n.push("Light"+e),r||(t.push("vLightData"+e,"vLightDiffuse"+e,"vLightSpecular"+e,"vLightDirection"+e,"vLightFalloff"+e,"vLightGround"+e,"lightMatrix"+e,"shadowsInfo"+e,"depthValues"+e),i.push("shadowTexture"+e),i.push("depthTexture"+e),t.push("viewFrustumZ"+e,"cascadeBlendFactor"+e,"lightSizeUVCorrection"+e,"depthCorrection"+e,"penumbraDarkness"+e,"frustumLengths"+e),s&&(i.push("projectionLightTexture"+e),t.push("textureProjectionMatrix"+e)))}class ls{get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;const t=this._alpha;this._alpha=e,1!==t&&1!==e||this.markAsDirty(ls.MiscDirtyFlag+ls.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(ls.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(ls.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 g),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 g),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new g),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(ls.TextureDirtyFlag))}get alphaMode(){return this._alphaMode}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(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAsDirty(ls.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case ls.WireFrameFillMode:case ls.LineListDrawMode:case ls.LineLoopDrawMode:case ls.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?ls.WireFrameFillMode:ls.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case ls.PointFillMode:case ls.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?ls.PointFillMode:ls.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(ls.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&ce.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._markAllSubMeshesAsMiscDirty()}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.sideOrientation=null,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new g,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=tt.ALPHA_COMBINE,this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new Zi,this._useUBO=!1,this._fillMode=ls.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._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const s=t||M.LastCreatedScene;s&&(this._scene=s,this._dirtyCallbacks={},this._dirtyCallbacks[tt.MATERIAL_TextureDirtyFlag]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[tt.MATERIAL_LightDirtyFlag]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[tt.MATERIAL_FresnelDirtyFlag]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[tt.MATERIAL_AttributesDirtyFlag]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[tt.MATERIAL_MiscDirtyFlag]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[tt.MATERIAL_PrePassDirtyFlag]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[tt.MATERIAL_AllDirtyFlag]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||Qt.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Ti(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._uniformBuffer=new Wi(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),ls.OnEventObservable.notifyObservers(this,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,i){const s=t.materialDefines;return!!s&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,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._forceAlphaTest=e===ls.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===ls.MATERIAL_OPAQUE||this._transparencyMode===ls.MATERIAL_ALPHATEST}needAlphaBlending(){return!this._disableAlphaBlending&&this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1||!this._disableAlphaBlending&&(e.hasVertexAlpha||this.needAlphaBlending())}needAlphaTesting(){return!!this._forceAlphaTest}_shouldTurnAlphaTestOn(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial()===this)for(const i of t._drawWrappers)i&&this._materialContext===i.materialContext&&(i._wasPreviouslyReady=!1,i._wasPreviouslyUsingInstances=null,i._forceRebindOnNextCall=e);e&&this.markAsDirty(ls.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),s=(null==t?this.sideOrientation:t)===ls.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}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,i){const s=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),s._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()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,function(e,t){t.bindToEffect(e,"Scene")}(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._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(e,t){const i={};if(this._serializePlugins(i),ls._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const t of this.pluginManager._plugins){const i=e.pluginManager.getPlugin(t.name);i&&t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}return this._scene.meshes.filter((e=>e.material===this))}forceCompilation(e,t,i,s){const n={clipPlane:!1,useInstances:!1,...i},r=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const o=()=>{if(!this._scene||!this._scene.getEngine())return;const i=r.clipPlane;if(n.clipPlane&&(r.clipPlane=new si(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,r=null;if(e.subMeshes){const t=new Ai(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,n.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?r=t.effect.getCompilationError():(i=!1,setTimeout(o,16)))}i&&(this.allowShaderHotSwapping=a,r&&s&&s(r),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(o,16);n.clipPlane&&(r.clipPlane=i)};o()}forceCompilationAsync(e,t){return new Promise(((i,s)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{s(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(ls._DirtyCallbackArray.length=0,e&ls.TextureDirtyFlag&&ls._DirtyCallbackArray.push(ls._TextureDirtyCallBack),e&ls.LightDirtyFlag&&ls._DirtyCallbackArray.push(ls._LightsDirtyCallBack),e&ls.FresnelDirtyFlag&&ls._DirtyCallbackArray.push(ls._FresnelDirtyCallBack),e&ls.AttributesDirtyFlag&&ls._DirtyCallbackArray.push(ls._AttributeDirtyCallBack),e&ls.MiscDirtyFlag&&ls._DirtyCallbackArray.push(ls._MiscDirtyCallBack),e&ls.PrePassDirtyFlag&&ls._DirtyCallbackArray.push(ls._PrePassDirtyCallBack),ls._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(ls._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){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial(!1)===this)for(const i of t._drawWrappers)i&&i.defines&&i.defines.markAllAsDirty&&this._materialContext===i.materialContext&&e(i.defines)}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(ls._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(ls._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(ls._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(ls._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(ls._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(ls._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(ls._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(ls._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(ls._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(ls._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,i){const s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.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!==i)if(this.meshMap)for(const t in this.meshMap){const i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{const t=s.meshes;for(const i of t)i.material!==this||i.sourceMesh||(i.material=null,this.releaseVertexArrayObject(i,e))}this._uniformBuffer.dispose(),e&&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={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=se.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)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return ce.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";const s=Qt.Instantiate(e.customType).Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _ParsePlugins(e,t,i,s){if(e.plugins)for(const n in e.plugins){const r=e.plugins[n];let a=t.pluginManager?.getPlugin(r.name);if(!a){const e=Qt.Instantiate("BABYLON."+n);e&&(a=new e(t))}a?.parse(r,i,s)}}}ls.TriangleFillMode=tt.MATERIAL_TriangleFillMode,ls.WireFrameFillMode=tt.MATERIAL_WireFrameFillMode,ls.PointFillMode=tt.MATERIAL_PointFillMode,ls.PointListDrawMode=tt.MATERIAL_PointListDrawMode,ls.LineListDrawMode=tt.MATERIAL_LineListDrawMode,ls.LineLoopDrawMode=tt.MATERIAL_LineLoopDrawMode,ls.LineStripDrawMode=tt.MATERIAL_LineStripDrawMode,ls.TriangleStripDrawMode=tt.MATERIAL_TriangleStripDrawMode,ls.TriangleFanDrawMode=tt.MATERIAL_TriangleFanDrawMode,ls.ClockWiseSideOrientation=tt.MATERIAL_ClockWiseSideOrientation,ls.CounterClockWiseSideOrientation=tt.MATERIAL_CounterClockWiseSideOrientation,ls.TextureDirtyFlag=tt.MATERIAL_TextureDirtyFlag,ls.LightDirtyFlag=tt.MATERIAL_LightDirtyFlag,ls.FresnelDirtyFlag=tt.MATERIAL_FresnelDirtyFlag,ls.AttributesDirtyFlag=tt.MATERIAL_AttributesDirtyFlag,ls.MiscDirtyFlag=tt.MATERIAL_MiscDirtyFlag,ls.PrePassDirtyFlag=tt.MATERIAL_PrePassDirtyFlag,ls.AllDirtyFlag=tt.MATERIAL_AllDirtyFlag,ls.MATERIAL_OPAQUE=0,ls.MATERIAL_ALPHATEST=1,ls.MATERIAL_ALPHABLEND=2,ls.MATERIAL_ALPHATESTANDBLEND=3,ls.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,ls.MATERIAL_NORMALBLENDMETHOD_RNM=1,ls.OnEventObservable=new g,ls._AllDirtyCallBack=e=>e.markAllAsDirty(),ls._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),ls._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),ls._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),ls._MiscDirtyCallBack=e=>e.markAsMiscDirty(),ls._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),ls._LightsDirtyCallBack=e=>e.markAsLightDirty(),ls._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),ls._FresnelAndMiscDirtyCallBack=e=>{ls._FresnelDirtyCallBack(e),ls._MiscDirtyCallBack(e)},ls._TextureAndMiscDirtyCallBack=e=>{ls._TextureDirtyCallBack(e),ls._MiscDirtyCallBack(e)},ls._DirtyCallbackArray=[],ls._RunDirtyCallBacks=e=>{for(const t of ls._DirtyCallbackArray)t(e)},e([a()],ls.prototype,"id",void 0),e([a()],ls.prototype,"uniqueId",void 0),e([a()],ls.prototype,"name",void 0),e([a()],ls.prototype,"metadata",void 0),e([a()],ls.prototype,"checkReadyOnEveryCall",void 0),e([a()],ls.prototype,"checkReadyOnlyOnce",void 0),e([a()],ls.prototype,"state",void 0),e([a("alpha")],ls.prototype,"_alpha",void 0),e([a("backFaceCulling")],ls.prototype,"_backFaceCulling",void 0),e([a("cullBackFaces")],ls.prototype,"_cullBackFaces",void 0),e([a()],ls.prototype,"sideOrientation",void 0),e([a("alphaMode")],ls.prototype,"_alphaMode",void 0),e([a()],ls.prototype,"_needDepthPrePass",void 0),e([a()],ls.prototype,"disableDepthWrite",void 0),e([a()],ls.prototype,"disableColorWrite",void 0),e([a()],ls.prototype,"forceDepthWrite",void 0),e([a()],ls.prototype,"depthFunction",void 0),e([a()],ls.prototype,"separateCullingPass",void 0),e([a("fogEnabled")],ls.prototype,"_fogEnabled",void 0),e([a()],ls.prototype,"pointSize",void 0),e([a()],ls.prototype,"zOffset",void 0),e([a()],ls.prototype,"zOffsetUnits",void 0),e([a()],ls.prototype,"pointsCloud",null),e([a()],ls.prototype,"fillMode",null),e([a()],ls.prototype,"useLogarithmicDepth",null),e([a()],ls.prototype,"transparencyMode",null);class hs extends ls{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=(...i)=>{const s=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),s};const i=e.splice;e.splice=(t,s)=>{const n=i.apply(e,[t,s]);return this._markAllSubMeshesAsTexturesDirty(),n}}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,i){for(let s=0;s<this.subMaterials.length;s++){const n=this.subMaterials[s];if(n){if(n._storeEffectOnSubMeshes){if(!n.isReadyForSubMesh(e,t,i))return!1;continue}if(!n.isReady(e))return!1}}return!0}clone(e,t){const i=new hs(e,this.getScene());for(let s=0;s<this.subMaterials.length;s++){let n=null;const r=this.subMaterials[s];n=t&&r?r.clone(e+"-"+r.name):this.subMaterials[s],i.subMaterials.push(n)}return i}serialize(){const e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,K&&(e.tags=K.GetTags(this)),e.materialsUniqueIds=[],e.materials=[];for(let t=0;t<this.subMaterials.length;t++){const i=this.subMaterials[t];i?(e.materialsUniqueIds.push(i.uniqueId),e.materials.push(i.id)):(e.materialsUniqueIds.push(null),e.materials.push(null))}return e}dispose(e,t,i){const s=this.getScene();if(!s)return;if(i)for(let i=0;i<this.subMaterials.length;i++){const s=this.subMaterials[i];s&&s.dispose(e,t)}const n=s.multiMaterials.indexOf(this);n>=0&&s.multiMaterials.splice(n,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new hs(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,K&&K.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}C("BABYLON.MultiMaterial",hs);class cs{}cs.NAME_EFFECTLAYER="EffectLayer",cs.NAME_LAYER="Layer",cs.NAME_LENSFLARESYSTEM="LensFlareSystem",cs.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",cs.NAME_PARTICLESYSTEM="ParticleSystem",cs.NAME_GAMEPAD="Gamepad",cs.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",cs.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",cs.NAME_PREPASSRENDERER="PrePassRenderer",cs.NAME_DEPTHRENDERER="DepthRenderer",cs.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",cs.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",cs.NAME_SPRITE="Sprite",cs.NAME_SUBSURFACE="SubSurface",cs.NAME_OUTLINERENDERER="Outline",cs.NAME_PROCEDURALTEXTURE="ProceduralTexture",cs.NAME_SHADOWGENERATOR="ShadowGenerator",cs.NAME_OCTREE="Octree",cs.NAME_PHYSICSENGINE="PhysicsEngine",cs.NAME_AUDIO="Audio",cs.NAME_FLUIDRENDERER="FluidRenderer",cs.STEP_ISREADYFORMESH_EFFECTLAYER=0,cs.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,cs.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,cs.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,cs.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,cs.STEP_BEFORECAMERADRAW_PREPASS=0,cs.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,cs.STEP_BEFORECAMERADRAW_LAYER=2,cs.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,cs.STEP_BEFORERENDERTARGETDRAW_LAYER=1,cs.STEP_BEFORERENDERINGMESH_PREPASS=0,cs.STEP_BEFORERENDERINGMESH_OUTLINE=1,cs.STEP_AFTERRENDERINGMESH_PREPASS=0,cs.STEP_AFTERRENDERINGMESH_OUTLINE=1,cs.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,cs.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,cs.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,cs.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,cs.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,cs.STEP_BEFORECLEAR_PREPASS=1,cs.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,cs.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,cs.STEP_AFTERRENDERTARGETDRAW_LAYER=1,cs.STEP_AFTERCAMERADRAW_PREPASS=0,cs.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,cs.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,cs.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,cs.STEP_AFTERCAMERADRAW_LAYER=4,cs.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,cs.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,cs.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,cs.STEP_AFTERRENDER_AUDIO=0,cs.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,cs.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,cs.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,cs.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,cs.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,cs.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,cs.STEP_POINTERMOVE_SPRITE=0,cs.STEP_POINTERDOWN_SPRITE=0,cs.STEP_POINTERUP_SPRITE=0;class us extends Array{constructor(e){super(...e)}static Create(){return Object.create(us.prototype)}registerStep(e,t,i){let s=0,n=Number.MAX_VALUE;for(;s<this.length;s++){if(n=this[s].index,e<n)break}this.splice(s,0,{index:e,component:t,action:i.bind(t)})}clear(){this.length=0}}class ds{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class _s{constructor(){this.visibleInstances={},this.batchCache=new fs,this.batchCacheReplacementModeInFrozenMode=new fs,this.instancesBufferSize=2048}}class fs{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class ms{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class ps{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}}class gs extends ji{static _GetDefaultSideOrientation(e){return e||gs.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(li.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(li.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 g),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new g),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new g),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new g),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new g),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===tt.MATERIAL_CounterClockWiseSideOrientation||!this._scene.useRightHandedSystem&&e===tt.MATERIAL_ClockWiseSideOrientation}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(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}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,i=!0){const s=this.getScene();if(e._geometry&&e._geometry.applyToMesh(this),de.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,s.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,K&&K.HasTags(e)&&K.AddTagsTo(this,K.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 t=e.getDescendants(!0);for(let e=0;e<t.length;e++){const i=t[e];i.clone&&i.clone(this.name+"."+i.name,this)}}if(e.morphTargetManager&&(this.morphTargetManager=e.morphTargetManager),s.getPhysicsEngine){const t=s.getPhysicsEngine();if(i&&t)if(1===t.getPluginVersion()){const i=t.getImpostorForPhysicsObject(e);i&&(this.physicsImpostor=i.clone(this))}else 2===t.getPluginVersion()&&e.physicsBody&&e.physicsBody.clone(this)}for(let t=0;t<s.particleSystems.length;t++){const i=s.particleSystems[t];i.emitter===e&&i.clone(i.name,this)}this.skeleton=e.skeleton,this.refreshBoundingInfo(!0,!0),this.computeWorldMatrix(!0)}constructor(e,t=null,i=null,s=null,n,r=!0){super(e,t),this._internalMeshDataInfo=new ps,this.delayLoadState=tt.DELAYLOADSTATE_NONE,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new _s,this._thinInstanceDataStorage=new ms,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=gs.DEFAULTSIDE,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._scene.useRightHandedSystem?this.sideOrientation=tt.MATERIAL_ClockWiseSideOrientation:this.sideOrientation=tt.MATERIAL_CounterClockWiseSideOrientation,this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},s&&this._copySource(s,n,r),null!==i&&(this.parent=i),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 g(this._internalMeshDataInfo._onMeshReadyObserverAdded),s&&s.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const s=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));s.parent=e||this.parent,s.position=this.position.clone(),s.scaling=this.scaling.clone(),this.rotationQuaternion?s.rotationQuaternion=this.rotationQuaternion.clone():s.rotation=this.rotation.clone(),i&&i(this,s);for(const e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===s.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):e.instantiateHierarchy(s,t,i);return s}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 i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);if(e)if(this._geometry){const e=this.getIndices(),i=this.getVerticesData(li.PositionKind);i&&e&&(t+=", flat shading: "+(i.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,i)=>t.distanceOrScreenCoverage<i.distanceOrScreenCoverage?e:t.distanceOrScreenCoverage>i.distanceOrScreenCoverage?-e:0))}addLODLevel(e,t){if(t&&t._masterMesh)return ce.Warn("You cannot use a mesh as LOD level twice"),this;const i=new ds(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let i=0;i<t._LODLevels.length;i++){const s=t._LODLevels[i];if(s.distanceOrScreenCoverage===e)return s.mesh}return null}removeLODLevel(e){const t=this._internalMeshDataInfo;for(let i=0;i<t._LODLevels.length;i++)t._LODLevels[i].mesh===e&&(t._LODLevels.splice(i,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this}getLOD(e,t){const i=this._internalMeshDataInfo;if(!i._LODLevels||0===i._LODLevels.length)return this;const s=t||this.getBoundingInfo().boundingSphere,n=e.mode===ri.ORTHOGRAPHIC_CAMERA?e.minZ:s.centerWorld.subtract(e.globalPosition).length();let r=n,a=1;if(i._useLODScreenCoverage){const t=e.screenArea;let i=s.radiusWorld*e.minZ/n;i=i*i*Math.PI,r=i/t,a=-1}if(a*i._LODLevels[i._LODLevels.length-1].distanceOrScreenCoverage>a*r)return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,this),this;for(let e=0;e<i._LODLevels.length;e++){const t=i._LODLevels[e];if(a*t.distanceOrScreenCoverage<a*r){if(t.mesh){if(t.mesh.delayLoadState===tt.DELAYLOADSTATE_NOTLOADED)return t.mesh._checkDelayState(),this;if(t.mesh.delayLoadState===tt.DELAYLOADSTATE_LOADING)return this;t.mesh._preActivate(),t.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)}return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,t.mesh),t.mesh}}return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,this),this}get geometry(){return this._geometry}getTotalVertices(){return null===this._geometry||void 0===this._geometry?0:this._geometry.getTotalVertices()}getVerticesData(e,t,i,s){if(!this._geometry)return null;let n=s?void 0:this._userInstancedBuffersStorage?.vertexBuffers[e]?.getFloatData(this.instances.length+1,i||t&&1!==this._geometry.meshes.length);return n||(n=this._geometry.getVerticesData(e,t,i)),n}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=[];return this._delayInfo&&this._delayInfo.forEach((function(t){e.push(t)})),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===tt.DELAYLOADSTATE_LOADING)return!1;if(!super.isReady(e))return!1;if(!this.subMeshes||0===this.subMeshes.length)return!0;if(!e)return!0;const i=this.getEngine(),s=this.getScene(),n=t||i.getCaps().instancedArrays&&(this.instances.length>0||this.hasThinInstances);this.computeWorldMatrix();const r=this.material||s.defaultMaterial;if(r)if(r._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,n))return!1}else if(!t.isReady(this,n))return!1}else if(!r.isReady(this,n))return!1;const a=i.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const s=t.values();for(let e=s.next();!0!==e.done;e=s.next()){const t=e.value;if(t&&(!t.getShadowMap()?.renderList||t.getShadowMap()?.renderList&&-1!==t.getShadowMap()?.renderList?.indexOf(this))){const e=t.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let s=0;s<e.length;++s){i.currentRenderPassId=e[s];for(const e of this.subMeshes)if(!t.isReady(e,n,e.getMaterial()?.needAlphaBlendingForMesh(this)??!1))return i.currentRenderPassId=a,!1}i.currentRenderPassId=a}}}for(const e of this._internalMeshDataInfo._LODLevels)if(e.mesh&&!e.mesh.isReady(n))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}_preActivate(){const e=this._internalMeshDataInfo,t=this.getScene().getRenderId();return e._preActivateId===t||(e._preActivateId=t,this._instanceDataStorage.visibleInstances=null),this}_preActivateForIntermediateRendering(e){return this._instanceDataStorage.visibleInstances&&(this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId=e),this}_registerInstanceForRenderId(e,t){return this._instanceDataStorage.visibleInstances||(this._instanceDataStorage.visibleInstances={defaultRenderId:t,selfDefaultRenderId:this._renderId}),this._instanceDataStorage.visibleInstances[t]||(void 0!==this._instanceDataStorage.previousRenderId&&this._instanceDataStorage.isFrozen&&(this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId]=null),this._instanceDataStorage.previousRenderId=t,this._instanceDataStorage.visibleInstances[t]=new Array),this._instanceDataStorage.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 i;i="object"==typeof e?e:{applySkeleton:e,applyMorph:t};const s=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getData(i,null,li.PositionKind),s),this}_createGlobalSubMesh(e){const t=this.getTotalVertices();if(!t||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){const i=this.getIndices();if(!i)return null;const s=i.length;let n=!1;if(e)n=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>s){n=!0;break}if(e.verticesStart+e.verticesCount>t){n=!0;break}}if(!n)return this.subMeshes[0]}return this.releaseSubMeshes(),new Ai(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,s=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let n=0;n<e&&!(s>=t);n++)Ai.CreateFromIndices(0,s,n===e-1?t-s:i,this,void 0,!1),s+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const s=new vi;s.set(t,e);const n=this.getScene();new Ci(Ci.RandomId(),n,s,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=Ci.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,s){return this._geometry?(s?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(li.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(li.PositionKind,i,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(li.NormalKind);if(!t)return this;vi.ComputeNormals(i,e,t),this.updateVerticesData(li.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(Ci.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new Ci(Ci.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const t=new vi;t.indices=e;const s=this.getScene();new Ci(Ci.RandomId(),s,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,s=!0){if(!this._geometry)return this;const n=this.getScene().getEngine();let r;if(this._unIndexed)r=null;else switch(this._getRenderingFillMode(i)){case ls.PointFillMode:r=null;break;case ls.WireFrameFillMode:r=e._getLinesIndexBuffer(this.getIndices(),n);break;default:case ls.TriangleFillMode:r=this._geometry.getIndexBuffer()}return this._bindDirect(t,r,s)}_bindDirect(e,t,i=!0){return this._geometry?(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(e),i&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(e,t,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(e,t),this):this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const s=this.getScene().getEngine();return this._unIndexed||t==ls.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==ls.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),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){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),s=i._isInIntermediateRendering(),n=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,r=this._instanceDataStorage.batchCache;if(r.mustReturn=!1,r.renderSelf[e]=t||!n&&this.isEnabled()&&this.isVisible,r.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,n=i.getRenderId(),a=s?t.intermediateDefaultRenderId:t.defaultRenderId;r.visibleInstances[e]=t[n],!r.visibleInstances[e]&&a&&(r.visibleInstances[e]=t[a])}return r.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==r.visibleInstances[e]&&void 0!==r.visibleInstances[e],this._instanceDataStorage.previousBatch=r,r}_renderWithInstances(e,t,i,s,n){const r=i.visibleInstances[e._id],a=r?r.length:0,o=this._instanceDataStorage,l=o.instancesBufferSize;let h=o.instancesBuffer,c=o.instancesPreviousBuffer;const u=16*(a+1)*4;for(;o.instancesBufferSize<u;)o.instancesBufferSize*=2;o.instancesData&&l==o.instancesBufferSize||(o.instancesData=new Float32Array(o.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!o.instancesPreviousData||l!=o.instancesBufferSize)&&(o.instancesPreviousData=new Float32Array(o.instancesBufferSize/4));let d=0,_=0;const f=i.renderSelf[e._id],m=!h||l!==o.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!o.instancesPreviousBuffer;if(this._instanceDataStorage.manualUpdate||o.isFrozen&&!m)_=(f?1:0)+a;else{const t=this.getWorldMatrix();if(f&&(this._scene.needsPreviousWorldMatrices&&(o.masterMeshPreviousWorldMatrix?(o.masterMeshPreviousWorldMatrix.copyToArray(o.instancesPreviousData,d),o.masterMeshPreviousWorldMatrix.copyFrom(t)):(o.masterMeshPreviousWorldMatrix=t.clone(),o.masterMeshPreviousWorldMatrix.copyToArray(o.instancesPreviousData,d))),t.copyToArray(o.instancesData,d),d+=16,_++),r){if(gs.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&e.getMaterial()?.needAlphaBlendingForMesh(e.getRenderingMesh())){const e=this._scene.activeCamera.globalPosition;for(let t=0;t<r.length;t++){const i=r[t];i._distanceToCamera=B.Distance(i.getBoundingInfo().boundingSphere.centerWorld,e)}r.sort(((e,t)=>e._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera<t._distanceToCamera?1:0))}for(let e=0;e<r.length;e++){const t=r[e],i=t.getWorldMatrix();i.copyToArray(o.instancesData,d),this._scene.needsPreviousWorldMatrices&&(t._previousWorldMatrix?(t._previousWorldMatrix.copyToArray(o.instancesPreviousData,d),t._previousWorldMatrix.copyFrom(i)):(t._previousWorldMatrix=i.clone(),t._previousWorldMatrix.copyToArray(o.instancesPreviousData,d))),d+=16,_++}}}return m?(h&&h.dispose(),c&&c.dispose(),h=new oi(n,o.instancesData,!0,16,!1,!0),o.instancesBuffer=h,this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this._userInstancedBuffersStorage.vertexBuffers.world0=h.createVertexBuffer("world0",0,4),this._userInstancedBuffersStorage.vertexBuffers.world1=h.createVertexBuffer("world1",4,4),this._userInstancedBuffersStorage.vertexBuffers.world2=h.createVertexBuffer("world2",8,4),this._userInstancedBuffersStorage.vertexBuffers.world3=h.createVertexBuffer("world3",12,4),this._scene.needsPreviousWorldMatrices&&(c=new oi(n,o.instancesPreviousData,!0,16,!1,!0),o.instancesPreviousBuffer=c,this._userInstancedBuffersStorage.vertexBuffers.previousWorld0=c.createVertexBuffer("previousWorld0",0,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld1=c.createVertexBuffer("previousWorld1",4,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld2=c.createVertexBuffer("previousWorld2",8,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld3=c.createVertexBuffer("previousWorld3",12,4)),this._invalidateInstanceVertexArrayObject()):this._instanceDataStorage.isFrozen&&!this._instanceDataStorage.forceMatrixUpdates||(h.updateDirectly(o.instancesData,0,_),!this._scene.needsPreviousWorldMatrices||this._instanceDataStorage.manualUpdate&&!this._instanceDataStorage.previousManualUpdate||c.updateDirectly(o.instancesPreviousData,0,_)),this._processInstancedBuffers(r,f),this.getScene()._activeIndices.addCount(e.indexCount*_,!1),n._currentDrawContext&&(n._currentDrawContext.useInstancing=!0),this._bind(e,s,t),this._draw(e,t,_),!this._scene.needsPreviousWorldMatrices||m||!this._instanceDataStorage.manualUpdate||this._instanceDataStorage.isFrozen&&!this._instanceDataStorage.forceMatrixUpdates||this._instanceDataStorage.previousManualUpdate||c.updateDirectly(o.instancesData,0,_),n.unbindInstanceAttributes(),this}_renderWithThinInstances(e,t,i,s){const n=this._thinInstanceDataStorage?.instancesCount??0;this.getScene()._activeIndices.addCount(e.indexCount*n,!1),s._currentDrawContext&&(s._currentDrawContext.useInstancing=!0),this._bind(e,i,t),this._draw(e,t,n),this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&this._thinInstanceDataStorage.matrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,n):this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.matrixData,!1)),s.unbindInstanceAttributes()}_processInstancedBuffers(e,t){}_processRendering(e,t,i,s,n,r,a,o){const l=this.getScene(),h=l.getEngine();if(s=this._getRenderingFillMode(s),r&&t.getRenderingMesh().hasThinInstances)return this._renderWithThinInstances(t,s,i,h),this;if(r)this._renderWithInstances(t,s,n,i,h);else{h._currentDrawContext&&(h._currentDrawContext.useInstancing=!1);let i=0;n.renderSelf[t._id]&&(a&&a(!1,e.getWorldMatrix(),o),i++,this._draw(t,s,this._instanceDataStorage.overridenInstanceCount));const r=n.visibleInstances[t._id];if(r){const e=r.length;i+=e;for(let i=0;i<e;i++){const e=r[i].getWorldMatrix();a&&a(!0,e,o),this._draw(t,s)}}l._activeIndices.addCount(t.indexCount*i,!1)}return this}_rebuild(e=!1){if(this._instanceDataStorage.instancesBuffer&&(e&&this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null),this._userInstancedBuffersStorage){for(const t in this._userInstancedBuffersStorage.vertexBuffers){const i=this._userInstancedBuffersStorage.vertexBuffers[t];i&&(e&&i.dispose(),this._userInstancedBuffersStorage.vertexBuffers[t]=null)}this._userInstancedBuffersStorage.vertexArrayObjects&&(this._userInstancedBuffersStorage.vertexArrayObjects={})}this._internalMeshDataInfo._effectiveMaterial=null,super._rebuild(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,this._instanceDataStorage.previousBatch=null}renderWithRenderPassId(e,t,i,s,n=!0){const r=this._scene.getEngine(),a=r.currentRenderPassId;if(void 0!==e&&(r.currentRenderPassId=e),s)(!n||n&&s.isInFrustum(this._scene._frustumPlanes))&&this.render(s,!!t,i);else for(let e=0;e<this.subMeshes.length;e++){const s=this.subMeshes[e];(!n||n&&s.isInFrustum(this._scene._frustumPlanes))&&this.render(s,!!t,i)}return void 0!==e&&(r.currentRenderPassId=a),this}render(e,t,i){const s=this.getScene();this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!1;const n=s.activeCameras?.length??0;if((n>1&&s.activeCamera===s.activeCameras[0]||n<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const r=this._getInstancesRenderList(e._id,!!i);if(r.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const a=s.getEngine();let o=0,l=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(o=s.activeCamera.maxZ,l=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const h=e.getRenderingMesh(),c=r.hardwareInstancedRendering[e._id]||h.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,u=this._instanceDataStorage,d=e.getMaterial();if(!d)return l&&(l.maxZ=o,s.updateTransformMatrix(!0)),this;if(u.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===d){if(d._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!d._storeEffectOnSubMeshes&&!d._getDrawWrapper()._wasPreviouslyReady)return l&&(l.maxZ=o,s.updateTransformMatrix(!0)),this}else{if(d._storeEffectOnSubMeshes){if(!d.isReadyForSubMesh(this,e,c))return l&&(l.maxZ=o,s.updateTransformMatrix(!0)),this}else if(!d.isReady(this,c))return l&&(l.maxZ=o,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=d}let _;t&&a.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),_=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const f=_?.effect??null;for(const t of s._beforeRenderingMeshStage)t.action(this,e,r,f);if(!_||!f)return l&&(l.maxZ=o,s.updateTransformMatrix(!0)),this;const m=i||this;let p;if(u.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this._internalMeshDataInfo._effectiveMaterial.sideOrientation&&!this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)p=u.sideOrientation;else{const e=m._getWorldMatrixDeterminant();p=this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this),e<0&&(p=p===ls.ClockWiseSideOrientation?ls.CounterClockWiseSideOrientation:ls.ClockWiseSideOrientation),u.sideOrientation=p}const g=this._internalMeshDataInfo._effectiveMaterial._preBind(_,p);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&a.setDepthWrite(!0);const E=this._internalMeshDataInfo._effectiveMaterial,T=E.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),c||this._bind(e,f,T,!1);const A=m.getWorldMatrix();E._storeEffectOnSubMeshes?E.bindForSubMesh(A,this,e):E.bind(A,this),!E.backFaceCulling&&E.separateCullingPass&&(a.setState(!0,E.zOffset,!1,!g,E.cullBackFaces,E.stencil,E.zOffsetUnits),this._processRendering(this,e,f,T,r,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),a.setState(!0,E.zOffset,!1,g,E.cullBackFaces,E.stencil,E.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,f,T,r,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of s._afterRenderingMeshStage)t.action(this,e,r,f);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),l&&(l.maxZ=o,s.updateTransformMatrix(!0)),2!==s.performancePriority||u.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(li.MatricesWeightsKind)&&(this.isVerticesDataPresent(li.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(li.MatricesWeightsKind),t=e.length;for(let i=0;i<t;i+=4){const t=e[i]+e[i+1]+e[i+2]+e[i+3];if(0===t)e[i]=1;else{const s=1/t;e[i]*=s,e[i+1]*=s,e[i+2]*=s,e[i+3]*=s}}this.setVerticesData(li.MatricesWeightsKind,e)}_normalizeSkinWeightsAndExtra(){const e=this.getVerticesData(li.MatricesWeightsExtraKind),t=this.getVerticesData(li.MatricesWeightsKind),i=t.length;for(let s=0;s<i;s+=4){let i=t[s]+t[s+1]+t[s+2]+t[s+3];if(i+=e[s]+e[s+1]+e[s+2]+e[s+3],0===i)t[s]=1;else{const n=1/i;t[s]*=n,t[s+1]*=n,t[s+2]*=n,t[s+3]*=n,e[s]*=n,e[s+1]*=n,e[s+2]*=n,e[s+3]*=n}}this.setVerticesData(li.MatricesWeightsKind,t),this.setVerticesData(li.MatricesWeightsKind,e)}validateSkinning(){const e=this.getVerticesData(li.MatricesWeightsExtraKind),t=this.getVerticesData(li.MatricesWeightsKind);if(null===t||null==this.skeleton)return{skinned:!1,valid:!0,report:"not skinned"};const i=t.length;let s=0,n=0,r=0,a=0;const o=null===e?4:8,l=[];for(let e=0;e<=o;e++)l[e]=0;for(let h=0;h<i;h+=4){let i=t[h],c=i,u=0===c?0:1;for(let n=1;n<o;n++){const r=n<4?t[h+n]:e[h+n-4];r>i&&s++,0!==r&&u++,c+=r,i=r}if(l[u]++,u>r&&(r=u),0===c)n++;else{const i=1/c;let s=0;for(let n=0;n<o;n++)s+=n<4?Math.abs(t[h+n]-t[h+n]*i):Math.abs(e[h+n-4]-e[h+n-4]*i);s>.001&&a++}}const h=this.skeleton.bones.length,c=this.getVerticesData(li.MatricesIndicesKind),u=this.getVerticesData(li.MatricesIndicesExtraKind);let d=0;for(let e=0;e<i;e+=4)for(let t=0;t<o;t++){const i=t<4?c[e+t]:u[e+t-4];(i>=h||i<0)&&d++}return{skinned:!0,valid:0===n&&0===a&&0===d,report:"Number of Weights = "+i/4+"\nMaximum influences = "+r+"\nMissing Weights = "+n+"\nNot Sorted = "+s+"\nNot Normalized = "+a+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+d}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===tt.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=tt.DELAYLOADSTATE_LOADING,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return Qt.LoadFile(this.delayLoadingFile,(t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach((e=>{e.refreshBoundingInfo(),e._syncSubMeshes()})),this.delayLoadState=tt.DELAYLOADSTATE_LOADED,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return this.delayLoadState!==tt.DELAYLOADSTATE_LOADING&&(!!super.isInFrustum(e)&&(this._checkDelayState(),!0))}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const s=this.getScene().multiMaterials;for(i=s.length-1;i>-1;i--)if(s[i].id===e)return this.material=s[i],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(li.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(li.PositionKind);const s=B.Zero();let n;for(n=0;n<i.length;n+=3)B.TransformCoordinatesFromFloatsToRef(i[n],i[n+1],i[n+2],e,s).toArray(i,n);if(this.setVerticesData(li.PositionKind,i,this.getVertexBuffer(li.PositionKind).isUpdatable()),this.isVerticesDataPresent(li.NormalKind)){for(i=this.getVerticesData(li.NormalKind),n=0;n<i.length;n+=3)B.TransformNormalFromFloatsToRef(i[n],i[n+1],i[n+2],e,s).normalize().toArray(i,n);this.setVerticesData(li.NormalKind,i,this.getVertexBuffer(li.NormalKind).isUpdatable())}if(this.isVerticesDataPresent(li.TangentKind)){for(i=this.getVerticesData(li.TangentKind),n=0;n<i.length;n+=4)B.TransformNormalFromFloatsToRef(i[n],i[n+1],i[n+2],e,s).normalize().toArray(i,n);this.setVerticesData(li.TangentKind,i,this.getVertexBuffer(li.TangentKind).isUpdatable())}return e.determinant()<0&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=t,this}bakeCurrentTransformIntoVertices(e=!0){return 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,i,s=!0){return new gs(e,this.getScene(),t,this,i,s)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);const i=this._internalMeshDataInfo;if(i._onBeforeDrawObservable&&i._onBeforeDrawObservable.clear(),i._onBeforeBindObservable&&i._onBeforeBindObservable.clear(),i._onBeforeRenderObservable&&i._onBeforeRenderObservable.clear(),i._onAfterRenderObservable&&i._onAfterRenderObservable.clear(),i._onBetweenPassObservable&&i._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(i.meshMap)for(const e in i.meshMap){const t=i.meshMap[e];t&&(t._internalMeshDataInfo._source=null,i.meshMap[e]=void 0)}i._source&&i._source._internalMeshDataInfo.meshMap&&(i._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)}}i._source=null,this._instanceDataStorage.visibleInstances={},this._disposeInstanceSpecificData(),this._disposeThinInstanceSpecificData(),this._internalMeshDataInfo._checkReadinessObserver&&this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),super.dispose(e,t)}_disposeInstanceSpecificData(){}_disposeThinInstanceSpecificData(){}_invalidateInstanceVertexArrayObject(){}applyDisplacementMap(e,t,i,s,n,r,a=!1,o){const l=this.getScene();return Qt.LoadImage(e,(e=>{const o=e.width,l=e.height,h=this.getEngine().createCanvas(o,l).getContext("2d");h.drawImage(e,0,0);const c=h.getImageData(0,0,o,l).data;this.applyDisplacementMapFromBuffer(c,o,l,t,i,n,r,a),s&&s(this)}),o||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,n,r,a,o=!1){if(!this.isVerticesDataPresent(li.PositionKind)||!this.isVerticesDataPresent(li.NormalKind)||!this.isVerticesDataPresent(li.UVKind))return ce.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(li.PositionKind,!0,!0),h=this.getVerticesData(li.NormalKind),c=this.getVerticesData(li.UVKind);let u=B.Zero();const d=B.Zero(),_=w.Zero();r=r||w.Zero(),a=a||new w(1,1);for(let o=0;o<l.length;o+=3){B.FromArrayToRef(l,o,u),B.FromArrayToRef(h,o,d),w.FromArrayToRef(c,o/3*2,_);const f=4*((Math.abs(_.x*a.x+r.x%1)*(t-1)%t|0)+(Math.abs(_.y*a.y+r.y%1)*(i-1)%i|0)*t),m=.3*(e[f]/255)+.59*(e[f+1]/255)+.11*(e[f+2]/255);d.normalize(),d.scaleInPlace(s+(n-s)*m),u=u.add(d),u.toArray(l,o)}return vi.ComputeNormals(l,this.getIndices(),h),o?(this.setVerticesData(li.PositionKind,l),this.setVerticesData(li.NormalKind,h),this.setVerticesData(li.UVKind,c)):(this.updateVerticesData(li.PositionKind,l),this.updateVerticesData(li.NormalKind,h)),this}_getFlattenedNormals(e,t){const i=new Float32Array(3*e.length);let s=0;const n=this.sideOrientation===(this._scene.useRightHandedSystem?tt.MATERIAL_CounterClockWiseSideOrientation:tt.MATERIAL_ClockWiseSideOrientation);for(let r=0;r<e.length;r+=3){const a=B.FromArray(t,3*e[r]),o=B.FromArray(t,3*e[r+1]),l=B.FromArray(t,3*e[r+2]),h=a.subtract(o),c=l.subtract(o),u=B.Normalize(B.Cross(h,c));n&&u.scaleInPlace(-1);for(let e=0;e<3;e++)i[s++]=u.x,i[s++]=u.y,i[s++]=u.z}return i}_convertToUnIndexedMesh(e=!1){const t=this.getVerticesDataKinds(),i=this.getIndices(),s={},n=(e,t)=>{const s=new Float32Array(i.length*t);let n=0;for(let r=0;r<i.length;r++)for(let a=0;a<t;a++)s[n++]=e[i[r]*t+a];return s},r=this.getBoundingInfo(),a=this.geometry?this.subMeshes.slice(0):[];for(const e of t)s[e]=this.getVerticesData(e);for(const r of t){const t=this.getVertexBuffer(r),a=t.getSize();if(e&&r===li.NormalKind){const e=this._getFlattenedNormals(i,s[li.PositionKind]);this.setVerticesData(li.NormalKind,e,t.isUpdatable(),a)}else this.setVerticesData(r,n(s[r],a),t.isUpdatable(),a)}if(this.morphTargetManager){for(let t=0;t<this.morphTargetManager.numTargets;t++){const s=this.morphTargetManager.getTarget(t),r=s.getPositions();s.setPositions(n(r,3));const a=s.getNormals();a&&s.setNormals(e?this._getFlattenedNormals(i,r):n(a,3));const o=s.getTangents();o&&s.setTangents(n(o,3));const l=s.getUVs();l&&s.setUVs(n(l,2))}this.morphTargetManager.synchronize()}for(let e=0;e<i.length;e++)i[e]=e;this.setIndices(i),this._unIndexed=!0,this.releaseSubMeshes();for(const e of a){const t=e.getBoundingInfo();Ai.AddToMesh(e.materialIndex,e.indexStart,e.indexCount,e.indexStart,e.indexCount,this).setBoundingInfo(t)}return this.setBoundingInfo(r),this.synchronizeInstances(),this}convertToFlatShadedMesh(){return this._convertToUnIndexedMesh(!0)}convertToUnIndexedMesh(){return this._convertToUnIndexedMesh()}flipFaces(e=!1){const t=vi.ExtractFromMesh(this);let i;if(e&&this.isVerticesDataPresent(li.NormalKind)&&t.normals)for(i=0;i<t.normals.length;i++)t.normals[i]*=-1;if(t.indices){let e;for(i=0;i<t.indices.length;i+=3)e=t.indices[i+1],t.indices[i+1]=t.indices[i+2],t.indices[i+2]=e}return t.applyToMesh(this,this.isVertexBufferUpdatable(li.PositionKind)),this}increaseVertices(e=1){const t=vi.ExtractFromMesh(this),i=t.indices&&!Array.isArray(t.indices)&&Array.from?Array.from(t.indices):t.indices,s=t.positions&&!Array.isArray(t.positions)&&Array.from?Array.from(t.positions):t.positions,n=t.uvs&&!Array.isArray(t.uvs)&&Array.from?Array.from(t.uvs):t.uvs,r=t.normals&&!Array.isArray(t.normals)&&Array.from?Array.from(t.normals):t.normals;if(i&&s){t.indices=i,t.positions=s,n&&(t.uvs=n),r&&(t.normals=r);const a=e+1,o=new Array;for(let e=0;e<a+1;e++)o[e]=new Array;let l,h;const c=new B(0,0,0),u=new B(0,0,0),d=new w(0,0),_=new Array,f=new Array,m=new Array;let p,g,E,T=s.length;n&&(g=n.length),r&&(E=r.length);for(let e=0;e<i.length;e+=3){f[0]=i[e],f[1]=i[e+1],f[2]=i[e+2];for(let e=0;e<3;e++)if(l=f[e],h=f[(e+1)%3],void 0===m[l]&&void 0===m[h]?(m[l]=new Array,m[h]=new Array):(void 0===m[l]&&(m[l]=new Array),void 0===m[h]&&(m[h]=new Array)),void 0===m[l][h]&&void 0===m[h][l]){m[l][h]=[],c.x=(s[3*h]-s[3*l])/a,c.y=(s[3*h+1]-s[3*l+1])/a,c.z=(s[3*h+2]-s[3*l+2])/a,r&&(u.x=(r[3*h]-r[3*l])/a,u.y=(r[3*h+1]-r[3*l+1])/a,u.z=(r[3*h+2]-r[3*l+2])/a),n&&(d.x=(n[2*h]-n[2*l])/a,d.y=(n[2*h+1]-n[2*l+1])/a),m[l][h].push(l);for(let e=1;e<a;e++)m[l][h].push(s.length/3),s[T++]=s[3*l]+e*c.x,s[T++]=s[3*l+1]+e*c.y,s[T++]=s[3*l+2]+e*c.z,r&&(r[E++]=r[3*l]+e*u.x,r[E++]=r[3*l+1]+e*u.y,r[E++]=r[3*l+2]+e*u.z),n&&(n[g++]=n[2*l]+e*d.x,n[g++]=n[2*l+1]+e*d.y);m[l][h].push(h),m[h][l]=new Array,p=m[l][h].length;for(let e=0;e<p;e++)m[h][l][e]=m[l][h][p-1-e]}o[0][0]=i[e],o[1][0]=m[i[e]][i[e+1]][1],o[1][1]=m[i[e]][i[e+2]][1];for(let t=2;t<a;t++){o[t][0]=m[i[e]][i[e+1]][t],o[t][t]=m[i[e]][i[e+2]][t],c.x=(s[3*o[t][t]]-s[3*o[t][0]])/t,c.y=(s[3*o[t][t]+1]-s[3*o[t][0]+1])/t,c.z=(s[3*o[t][t]+2]-s[3*o[t][0]+2])/t,r&&(u.x=(r[3*o[t][t]]-r[3*o[t][0]])/t,u.y=(r[3*o[t][t]+1]-r[3*o[t][0]+1])/t,u.z=(r[3*o[t][t]+2]-r[3*o[t][0]+2])/t),n&&(d.x=(n[2*o[t][t]]-n[2*o[t][0]])/t,d.y=(n[2*o[t][t]+1]-n[2*o[t][0]+1])/t);for(let e=1;e<t;e++)o[t][e]=s.length/3,s[T++]=s[3*o[t][0]]+e*c.x,s[T++]=s[3*o[t][0]+1]+e*c.y,s[T++]=s[3*o[t][0]+2]+e*c.z,r&&(r[E++]=r[3*o[t][0]]+e*u.x,r[E++]=r[3*o[t][0]+1]+e*u.y,r[E++]=r[3*o[t][0]+2]+e*u.z),n&&(n[g++]=n[2*o[t][0]]+e*d.x,n[g++]=n[2*o[t][0]+1]+e*d.y)}o[a]=m[i[e+1]][i[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(li.PositionKind))}else ce.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions")}forceSharedVertices(){const e=vi.ExtractFromMesh(this),t=e.uvs,i=e.indices,s=e.positions,n=e.colors,r=e.matricesIndices,a=e.matricesWeights,o=e.matricesIndicesExtra,l=e.matricesWeightsExtra;if(void 0===i||void 0===s||null===i||null===s)ce.Warn("VertexData contains empty entries");else{const h=new Array,c=new Array,u=new Array,d=new Array,_=new Array,f=new Array,m=new Array,p=new Array;let g=new Array,E=0;const T={};let A,R;for(let e=0;e<i.length;e+=3){R=[i[e],i[e+1],i[e+2]],g=[];for(let e=0;e<3;e++){g[e]="";for(let t=0;t<3;t++)Math.abs(s[3*R[e]+t])<1e-8&&(s[3*R[e]+t]=0),g[e]+=s[3*R[e]+t]+"|"}if(g[0]!=g[1]&&g[0]!=g[2]&&g[1]!=g[2])for(let e=0;e<3;e++){if(A=T[g[e]],void 0===A){T[g[e]]=E,A=E++;for(let t=0;t<3;t++)h.push(s[3*R[e]+t]);if(null!=n)for(let t=0;t<4;t++)d.push(n[4*R[e]+t]);if(null!=t)for(let i=0;i<2;i++)u.push(t[2*R[e]+i]);if(null!=r)for(let t=0;t<4;t++)_.push(r[4*R[e]+t]);if(null!=a)for(let t=0;t<4;t++)f.push(a[4*R[e]+t]);if(null!=o)for(let t=0;t<4;t++)m.push(o[4*R[e]+t]);if(null!=l)for(let t=0;t<4;t++)p.push(l[4*R[e]+t])}c.push(A)}}const v=new Array;vi.ComputeNormals(h,c,v),e.positions=h,e.indices=c,e.normals=v,null!=t&&(e.uvs=u),null!=n&&(e.colors=d),null!=r&&(e.matricesIndices=_),null!=a&&(e.matricesWeights=f),null!=o&&(e.matricesIndicesExtra=m),null!=a&&(e.matricesWeightsExtra=p),e.applyToMesh(this,this.isVertexBufferUpdatable(li.PositionKind))}}static _instancedMeshFactory(e,t){throw W("InstancedMesh")}static _PhysicsImpostorParser(e,t,i){throw W("PhysicsImpostor")}createInstance(e){return gs._instancedMeshFactory(e,this)}synchronizeInstances(){for(let e=0;e<this.instances.length;e++){this.instances[e]._syncSubMeshes()}return this}optimizeIndices(e){const t=this.getIndices(),i=this.getVerticesData(li.PositionKind);if(!i||!t)return this;const s=[];for(let e=0;e<i.length;e+=3)s.push(B.FromArray(i,e));const n=[];return jt.SyncAsyncForLoop(s.length,40,(e=>{const t=s.length-1-e,i=s[t];for(let e=0;e<t;++e){const r=s[e];if(i.equals(r)){n[t]=e;break}}}),(()=>{for(let e=0;e<t.length;++e)t[e]=n[t[e]]||t[e];const i=this.subMeshes.slice(0);this.setIndices(t),this.subMeshes=i,e&&e(this)})),this}serialize(e={}){e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,e.type=this.getClassName(),K&&K.HasTags(this)&&(e.tags=K.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.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 i=this.subMeshes[t];e.subMeshes.push({materialIndex:i.materialIndex,verticesStart:i.verticesStart,verticesCount:i.verticesCount,indexStart:i.indexStart,indexCount:i.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.numBoneInfluencers=this.numBoneInfluencers),this.getScene()._getComponent(cs.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 i=this.instances[t];if(i.doNotSerialize)continue;const s={name:i.name,id:i.id,isEnabled:i.isEnabled(!1),isVisible:i.isVisible,isPickable:i.isPickable,checkCollisions:i.checkCollisions,position:i.position.asArray(),scaling:i.scaling.asArray()};if(i.parent&&i.parent._serializeAsParent(s),i.rotationQuaternion?s.rotationQuaternion=i.rotationQuaternion.asArray():i.rotation&&(s.rotation=i.rotation.asArray()),this.getScene()._getComponent(cs.NAME_PHYSICSENGINE)){const e=i.getPhysicsImpostor();e&&(s.physicsMass=e.getParam("mass"),s.physicsFriction=e.getParam("friction"),s.physicsRestitution=e.getParam("mass"),s.physicsImpostor=e.type)}i.metadata&&(s.metadata=i.metadata),i.actionManager&&(s.actions=i.actionManager.serialize(i.name)),e.instances.push(s),se.AppendSerializedAnimations(i,s),s.ranges=i.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 se.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 ce.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 i=e.getActiveTarget(t),s=i.getPositions();if(!s)return void ce.Error("Invalid morph target. Target must have positions.");this.geometry.setVerticesData(li.PositionKind+t,s,!1,3);const n=i.getNormals();n&&this.geometry.setVerticesData(li.NormalKind+t,n,!1,3);const r=i.getTangents();r&&this.geometry.setVerticesData(li.TangentKind+t,r,!1,3);const a=i.getUVs();a&&this.geometry.setVerticesData(li.UVKind+"_"+t,a,!1,2)}}else{let e=0;for(;this.geometry.isVerticesDataPresent(li.PositionKind+e);)this.geometry.removeVerticesData(li.PositionKind+e),this.geometry.isVerticesDataPresent(li.NormalKind+e)&&this.geometry.removeVerticesData(li.NormalKind+e),this.geometry.isVerticesDataPresent(li.TangentKind+e)&&this.geometry.removeVerticesData(li.TangentKind+e),this.geometry.isVerticesDataPresent(li.UVKind+e)&&this.geometry.removeVerticesData(li.UVKind+"_"+e),e++}}static Parse(e,t,i){let s;if(s=e.type&&"LinesMesh"===e.type?gs._LinesMeshParser(e,t):e.type&&"GroundMesh"===e.type?gs._GroundMeshParser(e,t):e.type&&"GoldbergMesh"===e.type?gs._GoldbergMeshParser(e,t):e.type&&"GreasedLineMesh"===e.type?gs._GreasedLineMeshParser(e,t):e.type&&"TrailMesh"===e.type?gs._TrailMeshParser(e,t):new gs(e.name,t),s.id=e.id,s._waitingParsedUniqueId=e.uniqueId,K&&K.AddTagsTo(s,e.tags),s.position=B.FromArray(e.position),void 0!==e.metadata&&(s.metadata=e.metadata),e.rotationQuaternion?s.rotationQuaternion=k.FromArray(e.rotationQuaternion):e.rotation&&(s.rotation=B.FromArray(e.rotation)),s.scaling=B.FromArray(e.scaling),e.localMatrix?s.setPreTransformMatrix(G.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(G.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s.isVisible=e.isVisible,s.infiniteDistance=e.infiniteDistance,s.alwaysSelectAsActiveMesh=!!e.alwaysSelectAsActiveMesh,s.showBoundingBox=e.showBoundingBox,s.showSubMeshesBoundingBox=e.showSubMeshesBoundingBox,void 0!==e.applyFog&&(s.applyFog=e.applyFog),void 0!==e.pickable&&(s.isPickable=e.pickable),void 0!==e.alphaIndex&&(s.alphaIndex=e.alphaIndex),s.receiveShadows=e.receiveShadows,void 0!==e.billboardMode&&(s.billboardMode=e.billboardMode),void 0!==e.visibility&&(s.visibility=e.visibility),s.checkCollisions=e.checkCollisions,s.doNotSyncBoundingInfo=!!e.doNotSyncBoundingInfo,e.ellipsoid&&(s.ellipsoid=B.FromArray(e.ellipsoid)),e.ellipsoidOffset&&(s.ellipsoidOffset=B.FromArray(e.ellipsoidOffset)),null!=e.overrideMaterialSideOrientation&&(s.sideOrientation=e.overrideMaterialSideOrientation),void 0!==e.sideOrientation&&(s.sideOrientation=e.sideOrientation),void 0!==e.isBlocker&&(s.isBlocker=e.isBlocker),s._shouldGenerateFlatShading=e.useFlatShading,e.freezeWorldMatrix&&(s._waitingData.freezeWorldMatrix=e.freezeWorldMatrix),void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.actions&&(s._waitingData.actions=e.actions),void 0!==e.overlayAlpha&&(s.overlayAlpha=e.overlayAlpha),void 0!==e.overlayColor&&(s.overlayColor=J.FromArray(e.overlayColor)),void 0!==e.renderOverlay&&(s.renderOverlay=e.renderOverlay),s.isUnIndexed=!!e.isUnIndexed,s.hasVertexAlpha=e.hasVertexAlpha,e.delayLoadingFile?(s.delayLoadState=tt.DELAYLOADSTATE_NOTLOADED,s.delayLoadingFile=i+e.delayLoadingFile,s.buildBoundingInfo(B.FromArray(e.boundingBoxMinimum),B.FromArray(e.boundingBoxMaximum)),e._binaryInfo&&(s._binaryInfo=e._binaryInfo),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(li.UVKind),e.hasUVs2&&s._delayInfo.push(li.UV2Kind),e.hasUVs3&&s._delayInfo.push(li.UV3Kind),e.hasUVs4&&s._delayInfo.push(li.UV4Kind),e.hasUVs5&&s._delayInfo.push(li.UV5Kind),e.hasUVs6&&s._delayInfo.push(li.UV6Kind),e.hasColors&&s._delayInfo.push(li.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(li.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(li.MatricesWeightsKind),s._delayLoadingFunction=Ci._ImportGeometry,Ii.ForceFullSceneLoadingForIncremental&&s._checkDelayState()):Ci._ImportGeometry(e,s),e.materialUniqueId?s._waitingMaterialId=e.materialUniqueId:e.materialId&&(s._waitingMaterialId=e.materialId),e.morphTargetManagerId>-1&&(s.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(s.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(s.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t<e.animations.length;t++){const i=e.animations[t],n=b("BABYLON.Animation");n&&s.animations.push(n.Parse(i))}re.ParseAnimationRanges(s,e,t)}if(e.autoAnimate&&t.beginAnimation(s,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.layerMask&&!isNaN(e.layerMask)?s.layerMask=Math.abs(parseInt(e.layerMask)):s.layerMask=268435455,e.physicsImpostor&&(s.physicsImpostor=gs._PhysicsImpostorParser(t,s,e)),e.lodMeshIds&&(s._waitingData.lods={ids:e.lodMeshIds,distances:e.lodDistances?e.lodDistances:null,coverages:e.lodCoverages?e.lodCoverages:null}),e.instances)for(let i=0;i<e.instances.length;i++){const n=e.instances[i],r=s.createInstance(n.name);if(n.id&&(r.id=n.id),K&&(n.tags?K.AddTagsTo(r,n.tags):K.AddTagsTo(r,e.tags)),r.position=B.FromArray(n.position),void 0!==n.metadata&&(r.metadata=n.metadata),void 0!==n.parentId&&(r._waitingParentId=n.parentId),void 0!==n.parentInstanceIndex&&(r._waitingParentInstanceIndex=n.parentInstanceIndex),void 0!==n.isEnabled&&null!==n.isEnabled&&r.setEnabled(n.isEnabled),void 0!==n.isVisible&&null!==n.isVisible&&(r.isVisible=n.isVisible),void 0!==n.isPickable&&null!==n.isPickable&&(r.isPickable=n.isPickable),n.rotationQuaternion?r.rotationQuaternion=k.FromArray(n.rotationQuaternion):n.rotation&&(r.rotation=B.FromArray(n.rotation)),r.scaling=B.FromArray(n.scaling),null!=n.checkCollisions&&null!=n.checkCollisions&&(r.checkCollisions=n.checkCollisions),null!=n.pickable&&null!=n.pickable&&(r.isPickable=n.pickable),null!=n.showBoundingBox&&null!=n.showBoundingBox&&(r.showBoundingBox=n.showBoundingBox),null!=n.showSubMeshesBoundingBox&&null!=n.showSubMeshesBoundingBox&&(r.showSubMeshesBoundingBox=n.showSubMeshesBoundingBox),null!=n.alphaIndex&&null!=n.showSubMeshesBoundingBox&&(r.alphaIndex=n.alphaIndex),n.physicsImpostor&&(r.physicsImpostor=gs._PhysicsImpostorParser(t,r,n)),void 0!==n.actions&&(r._waitingData.actions=n.actions),n.animations){for(let e=0;e<n.animations.length;e++){const t=n.animations[e],i=b("BABYLON.Animation");i&&r.animations.push(i.Parse(t))}re.ParseAnimationRanges(r,n,t),n.autoAnimate&&t.beginAnimation(r,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1)}}if(e.thinInstances){const t=e.thinInstances;if(s.thinInstanceEnablePicking=!!t.enablePicking,t.matrixData?(s.thinInstanceSetBuffer("matrix",new Float32Array(t.matrixData),16,!1),s._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,s._thinInstanceDataStorage.instancesCount=t.instancesCount):s._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,e.thinInstances.userThinInstance){const t=e.thinInstances.userThinInstance;for(const e in t.data)s.thinInstanceSetBuffer(e,new Float32Array(t.data[e]),t.strides[e],!1),s._userThinInstanceBuffersStorage.sizes[e]=t.sizes[e]}}return s}setPositionsForCPUSkinning(){const e=this._internalMeshDataInfo;if(!e._sourcePositions){const t=this.getVerticesData(li.PositionKind);if(!t)return e._sourcePositions;e._sourcePositions=new Float32Array(t),this.isVertexBufferUpdatable(li.PositionKind)||this.setVerticesData(li.PositionKind,t,!0)}return e._sourcePositions}setNormalsForCPUSkinning(){const e=this._internalMeshDataInfo;if(!e._sourceNormals){const t=this.getVerticesData(li.NormalKind);if(!t)return e._sourceNormals;e._sourceNormals=new Float32Array(t),this.isVertexBufferUpdatable(li.NormalKind)||this.setVerticesData(li.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(li.PositionKind))return this;if(!this.isVerticesDataPresent(li.MatricesIndicesKind))return this;if(!this.isVerticesDataPresent(li.MatricesWeightsKind))return this;const t=this.isVerticesDataPresent(li.NormalKind),i=this._internalMeshDataInfo;if(!i._sourcePositions){const e=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=e}t&&!i._sourceNormals&&this.setNormalsForCPUSkinning();let s=this.getVerticesData(li.PositionKind);if(!s)return this;s instanceof Float32Array||(s=new Float32Array(s));let n=this.getVerticesData(li.NormalKind);if(t){if(!n)return this;n instanceof Float32Array||(n=new Float32Array(n))}const r=this.getVerticesData(li.MatricesIndicesKind),a=this.getVerticesData(li.MatricesWeightsKind);if(!a||!r)return this;const o=this.numBoneInfluencers>4,l=o?this.getVerticesData(li.MatricesIndicesExtraKind):null,h=o?this.getVerticesData(li.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),u=B.Zero(),d=new G,_=new G;let f,m=0;for(let e=0;e<s.length;e+=3,m+=4){let p;for(f=0;f<4;f++)p=a[m+f],p>0&&(G.FromFloat32ArrayToRefScaled(c,Math.floor(16*r[m+f]),p,_),d.addToSelf(_));if(o)for(f=0;f<4;f++)p=h[m+f],p>0&&(G.FromFloat32ArrayToRefScaled(c,Math.floor(16*l[m+f]),p,_),d.addToSelf(_));B.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],d,u),u.toArray(s,e),t&&(B.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],d,u),u.toArray(n,e)),d.reset()}return this.updateVerticesData(li.PositionKind,s),t&&this.updateVerticesData(li.NormalKind,n),this}static MinMax(e){let t=null,i=null;return e.forEach((function(e){const s=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(s.minimumWorld),i.maximizeInPlace(s.maximumWorld)):(t=s.minimumWorld,i=s.maximumWorld)})),t&&i?{min:t,max:i}:{min:B.Zero(),max:B.Zero()}}static Center(e){const t=e instanceof Array?gs.MinMax(e):e;return B.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,n,r){return Jt(gs._MergeMeshesCoroutine(e,t,i,s,n,r,!1))}static MergeMeshesAsync(e,t=!0,i,s,n,r){return a=gs._MergeMeshesCoroutine(e,t,i,s,n,r,!0),o=function(e=25){let t;return(i,s,n)=>{const r=performance.now();void 0===t||r-t>e?(t=r,setTimeout((()=>{Zt(i,s,n)}),0)):Zt(i,s,n)}}(),new Promise(((e,t)=>{$t(a,o,e,t)}));var a,o}static*_MergeMeshesCoroutine(e,t=!0,i,s,n,r,a){if(0===(e=e.filter(Boolean)).length)return null;let o;if(!i){let t=0;for(o=0;o<e.length;o++)if(t+=e[o].getTotalVertices(),t>=65536)return ce.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}r&&(n=!1);const l=new Array,h=new Array,c=new Array,u=e[0].sideOrientation;for(o=0;o<e.length;o++){const t=e[o];if(t.isAnInstance)return ce.Warn("Cannot merge instance meshes."),null;if(u!==t.sideOrientation)return ce.Warn("Cannot merge meshes with different sideOrientation values."),null;if(n&&c.push(t.getTotalIndices()),r)if(t.material){const e=t.material;if(e instanceof hs){for(let t=0;t<e.subMaterials.length;t++)l.indexOf(e.subMaterials[t])<0&&l.push(e.subMaterials[t]);for(let i=0;i<t.subMeshes.length;i++)h.push(l.indexOf(e.subMaterials[t.subMeshes[i].materialIndex])),c.push(t.subMeshes[i].indexCount)}else{l.indexOf(e)<0&&l.push(e);for(let i=0;i<t.subMeshes.length;i++)h.push(l.indexOf(e)),c.push(t.subMeshes[i].indexCount)}}else for(let e=0;e<t.subMeshes.length;e++)h.push(0),c.push(t.subMeshes[e].indexCount)}const d=e[0],_=e=>{const t=e.computeWorldMatrix(!0);return{vertexData:vi.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:f,transform:m}=_(d);a&&(yield);const p=new Array(e.length-1);for(let t=1;t<e.length;t++)p[t-1]=_(e[t]),a&&(yield);const g=f._mergeCoroutine(m,p,i,a,!t);let E=g.next();for(;!E.done;)a&&(yield),E=g.next();const T=E.value;s||(s=new gs(d.name+"_merged",d.getScene()));const A=T._applyToCoroutine(s,void 0,a);let R=A.next();for(;!R.done;)a&&(yield),R=A.next();if(s.checkCollisions=d.checkCollisions,s.sideOrientation=d.sideOrientation,t)for(o=0;o<e.length;o++)e[o].dispose();if(n||r){s.releaseSubMeshes(),o=0;let e=0;for(;o<c.length;)Ai.CreateFromIndices(0,e,c[o],s,void 0,!1),e+=c[o],o++;for(const e of s.subMeshes)e.refreshBoundingInfo();s.computeWorldMatrix(!0)}if(r){const e=new hs(d.name+"_merged",d.getScene());e.subMaterials=l;for(let e=0;e<s.subMeshes.length;e++)s.subMeshes[e].materialIndex=h[e];s.material=e}else s.material=d.material;return s}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===ls.CounterClockWiseSideOrientation}_getRenderingFillMode(e){const t=this.getScene();return t.forcePointsCloud?ls.PointFillMode:t.forceWireframe?ls.WireFrameFillMode:this.overrideRenderingFillMode??e}setMaterialByID(e){return this.setMaterialById(e)}static CreateRibbon(e,t,i,s,n,r,a,o,l){throw new Error("Import MeshBuilder to populate this function")}static CreateDisc(e,t,i,s,n,r){throw new Error("Import MeshBuilder to populate this function")}static CreateBox(e,t,i,s,n){throw new Error("Import MeshBuilder to populate this function")}static CreateSphere(e,t,i,s,n,r){throw new Error("Import MeshBuilder to populate this function")}static CreateHemisphere(e,t,i,s){throw new Error("Import MeshBuilder to populate this function")}static CreateCylinder(e,t,i,s,n,r,a,o,l){throw new Error("Import MeshBuilder to populate this function")}static CreateTorus(e,t,i,s,n,r,a){throw new Error("Import MeshBuilder to populate this function")}static CreateTorusKnot(e,t,i,s,n,r,a,o,l,h){throw new Error("Import MeshBuilder to populate this function")}static CreateLines(e,t,i,s,n){throw new Error("Import MeshBuilder to populate this function")}static CreateDashedLines(e,t,i,s,n,r,a,o){throw new Error("Import MeshBuilder to populate this function")}static CreatePolygon(e,t,i,s,n,r,a){throw new Error("Import MeshBuilder to populate this function")}static ExtrudePolygon(e,t,i,s,n,r,a,o){throw new Error("Import MeshBuilder to populate this function")}static ExtrudeShape(e,t,i,s,n,r,a,o,l,h){throw new Error("Import MeshBuilder to populate this function")}static ExtrudeShapeCustom(e,t,i,s,n,r,a,o,l,h,c,u){throw new Error("Import MeshBuilder to populate this function")}static CreateLathe(e,t,i,s,n,r,a){throw new Error("Import MeshBuilder to populate this function")}static CreatePlane(e,t,i,s,n){throw new Error("Import MeshBuilder to populate this function")}static CreateGround(e,t,i,s,n,r){throw new Error("Import MeshBuilder to populate this function")}static CreateTiledGround(e,t,i,s,n,r,a,o,l){throw new Error("Import MeshBuilder to populate this function")}static CreateGroundFromHeightMap(e,t,i,s,n,r,a,o,l,h,c){throw new Error("Import MeshBuilder to populate this function")}static CreateTube(e,t,i,s,n,r,a,o,l,h){throw new Error("Import MeshBuilder to populate this function")}static CreatePolyhedron(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static CreateIcoSphere(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static CreateDecal(e,t,i,s,n,r){throw new Error("Import MeshBuilder to populate this function")}static CreateCapsule(e,t,i){throw new Error("Import MeshBuilder to populate this function")}static ExtendToGoldberg(e){throw new Error("Import MeshBuilder to populate this function")}}gs.FRONTSIDE=vi.FRONTSIDE,gs.BACKSIDE=vi.BACKSIDE,gs.DOUBLESIDE=vi.DOUBLESIDE,gs.DEFAULTSIDE=vi.DEFAULTSIDE,gs.NO_CAP=0,gs.CAP_START=1,gs.CAP_END=2,gs.CAP_ALL=3,gs.NO_FLIP=0,gs.FLIP_TILE=1,gs.ROTATE_TILE=2,gs.FLIP_ROW=3,gs.ROTATE_ROW=4,gs.FLIP_N_ROTATE_TILE=5,gs.FLIP_N_ROTATE_ROW=6,gs.CENTER=0,gs.LEFT=1,gs.RIGHT=2,gs.TOP=3,gs.BOTTOM=4,gs.INSTANCEDMESH_SORT_TRANSPARENT=!1,gs._GroundMeshParser=(e,t)=>{throw W("GroundMesh")},gs._GoldbergMeshParser=(e,t)=>{throw W("GoldbergMesh")},gs._LinesMeshParser=(e,t)=>{throw W("LinesMesh")},gs._GreasedLineMeshParser=(e,t)=>{throw W("GreasedLineMesh")},gs._GreasedLineRibbonMeshParser=(e,t)=>{throw W("GreasedLineRibbonMesh")},gs._TrailMeshParser=(e,t)=>{throw W("TrailMesh")},C("BABYLON.Mesh",gs);class Es{}Es.POINTERDOWN=1,Es.POINTERUP=2,Es.POINTERMOVE=4,Es.POINTERWHEEL=8,Es.POINTERPICK=16,Es.POINTERTAP=32,Es.POINTERDOUBLETAP=64;class Ts{constructor(e,t){this.type=e,this.event=t}}class As extends Ts{constructor(e,t,i,s){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new w(i,s)}}class Rs extends Ts{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,s=null){super(e,t),this._pickInfo=i,this._inputManager=s}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}class vs{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=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}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==Es.POINTERDOWN?e.type===Es.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=_e.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const i=e-this._lastInteractionTime-this._idleRotationWaitTime,s=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*s,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}resetLastInteractionTime(e){this._lastInteractionTime=e??_e.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha)<A}_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=_e.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 Is;!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(Is||(Is={}));class Ss{constructor(){this._easingMode=Ss.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 Ss.EASINGMODE_EASEIN:return this.easeInCore(e);case Ss.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-e)}return e>=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}Ss.EASINGMODE_EASEIN=0,Ss.EASINGMODE_EASEOUT=1,Ss.EASINGMODE_EASEINOUT=2;class Cs{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new Cs(this.name,this.from,this.to)}}class bs{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 bs(this.width*e,this.height*t)}clone(){return new bs(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 bs(0,0)}add(e){return new bs(this.width+e.width,this.height+e.height)}subtract(e){return new bs(this.width-e.width,this.height-e.height)}scale(e){return new bs(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,n=e.height+(t.height-e.height)*i;return new bs(s,n)}}const ys=Object.freeze(new k(0,0,0,0)),Ms=Object.freeze(B.Zero()),xs=Object.freeze(w.Zero()),Os=Object.freeze(bs.Zero()),Ds=Object.freeze(J.Black()),Ps=Object.freeze(new ee(0,0,0,0)),Ns={key:0,repeatCount:0,loopMode:2};class Ls{static _PrepareAnimation(e,t,i,s,n,r,a,o){let l;if(!isNaN(parseFloat(n))&&isFinite(n)?l=Ls.ANIMATIONTYPE_FLOAT:n instanceof k?l=Ls.ANIMATIONTYPE_QUATERNION:n instanceof B?l=Ls.ANIMATIONTYPE_VECTOR3:n instanceof w?l=Ls.ANIMATIONTYPE_VECTOR2:n instanceof J?l=Ls.ANIMATIONTYPE_COLOR3:n instanceof ee?l=Ls.ANIMATIONTYPE_COLOR4:n instanceof bs&&(l=Ls.ANIMATIONTYPE_SIZE),null==l)return null;const h=new Ls(e,t,i,l,a),c=[{frame:0,value:n},{frame:s,value:r}];return h.setKeys(c),void 0!==o&&h.setEasingFunction(o),h}static CreateAnimation(e,t,i,s){const n=new Ls(e+"Animation",e,i,t,Ls.ANIMATIONLOOPMODE_CONSTANT);return n.setEasingFunction(s),n}static CreateAndStartAnimation(e,t,i,s,n,r,a,o,l,h,c){const u=Ls._PrepareAnimation(e,i,s,n,r,a,o,l);return u?(t.getScene&&(c=t.getScene()),c?c.beginDirectAnimation(t,[u],0,n,1===u.loopMode,1,h):null):null}static CreateAndStartHierarchyAnimation(e,t,i,s,n,r,a,o,l,h,c){const u=Ls._PrepareAnimation(e,s,n,r,a,o,l,h);if(!u)return null;return t.getScene().beginDirectHierarchyAnimation(t,i,[u],0,r,1===u.loopMode,1,c)}static CreateMergeAndStartAnimation(e,t,i,s,n,r,a,o,l,h){const c=Ls._PrepareAnimation(e,i,s,n,r,a,o,l);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,n,1===c.loopMode,1,h)):null}static MakeAnimationAdditive(e,t,i,s=!1,n){let r;r="object"==typeof t?t:{referenceFrame:t??0,range:i,cloneOriginalAnimation:s,clonedAnimationName:n};let a=e;if(r.cloneOriginalAnimation&&(a=e.clone(),a.name=r.clonedAnimationName||a.name),!a._keys.length)return a;const o=r.referenceFrame&&r.referenceFrame>=0?r.referenceFrame:0;let l=0;const h=a._keys[0];let c=a._keys.length-1;const u=a._keys[c],d={referenceValue:h.value,referencePosition:X.Vector3[0],referenceQuaternion:X.Quaternion[0],referenceScaling:X.Vector3[1],keyPosition:X.Vector3[2],keyQuaternion:X.Quaternion[1],keyScaling:X.Vector3[3]};let _=h.frame,f=u.frame;if(r.range){const e=a.getRange(r.range);e&&(_=e.from,f=e.to)}else _=r.fromFrame??_,f=r.toFrame??f;if(_!==h.frame&&(l=a.createKeyForFrame(_)),f!==u.frame&&(c=a.createKeyForFrame(f)),1===a._keys.length){const e=a._getKeyValue(a._keys[0]);d.referenceValue=e.clone?e.clone():e}else if(o<=h.frame){const e=a._getKeyValue(h.value);d.referenceValue=e.clone?e.clone():e}else if(o>=u.frame){const e=a._getKeyValue(u.value);d.referenceValue=e.clone?e.clone():e}else{Ns.key=0;const e=a._interpolate(o,Ns);d.referenceValue=e.clone?e.clone():e}a.dataType===Ls.ANIMATIONTYPE_QUATERNION?d.referenceValue.normalize().conjugateInPlace():a.dataType===Ls.ANIMATIONTYPE_MATRIX&&(d.referenceValue.decompose(d.referenceScaling,d.referenceQuaternion,d.referencePosition),d.referenceQuaternion.normalize().conjugateInPlace());let m=Number.MAX_VALUE;const p=r.clipKeys?[]:null;for(let e=l;e<=c;e++){let t=a._keys[e];if((p||r.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},p&&(m===Number.MAX_VALUE&&(m=t.frame),t.frame-=m,p.push(t))),!e||a.dataType===Ls.ANIMATIONTYPE_FLOAT||t.value!==h.value)switch(a.dataType){case Ls.ANIMATIONTYPE_MATRIX:t.value.decompose(d.keyScaling,d.keyQuaternion,d.keyPosition),d.keyPosition.subtractInPlace(d.referencePosition),d.keyScaling.divideInPlace(d.referenceScaling),d.referenceQuaternion.multiplyToRef(d.keyQuaternion,d.keyQuaternion),G.ComposeToRef(d.keyScaling,d.keyQuaternion,d.keyPosition,t.value);break;case Ls.ANIMATIONTYPE_QUATERNION:d.referenceValue.multiplyToRef(t.value,t.value);break;case Ls.ANIMATIONTYPE_VECTOR2:case Ls.ANIMATIONTYPE_VECTOR3:case Ls.ANIMATIONTYPE_COLOR3:case Ls.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(d.referenceValue,t.value);break;case Ls.ANIMATIONTYPE_SIZE:t.value.width-=d.referenceValue.width,t.value.height-=d.referenceValue.height;break;default:t.value-=d.referenceValue}}return p&&a.setKeys(p,!0),a}static TransitionTo(e,t,i,s,n,r,a,o=null){if(a<=0)return i[e]=t,o&&o(),null;const l=n*(a/1e3);r.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(r);const h=s.beginAnimation(i,0,l,!1);return h.onAnimationEnd=o,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,s,n,r){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=s,this.loopMode=n,this.enableBlending=r,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=s,this.loopMode=void 0===n?Ls.ANIMATIONLOOPMODE_CYCLE:n,this.uniqueId=Ls._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 i in this._ranges)e&&(t+=", ",e=!1),t+=i;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,i){this._ranges[e]||(this._ranges[e]=new Cs(e,t,i))}deleteRange(e,t=!0){const i=this._ranges[e];if(i){if(t){const e=i.from,t=i.to;for(let i=this._keys.length-1;i>=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t<i;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,i){return q.Lerp(e,t,i)}floatInterpolateFunctionWithTangents(e,t,i,s,n){return q.Hermite(e,t,i,s,n)}quaternionInterpolateFunction(e,t,i){return k.Slerp(e,t,i)}quaternionInterpolateFunctionWithTangents(e,t,i,s,n){return k.Hermite(e,t,i,s,n).normalize()}vector3InterpolateFunction(e,t,i){return B.Lerp(e,t,i)}vector3InterpolateFunctionWithTangents(e,t,i,s,n){return B.Hermite(e,t,i,s,n)}vector2InterpolateFunction(e,t,i){return w.Lerp(e,t,i)}vector2InterpolateFunctionWithTangents(e,t,i,s,n){return w.Hermite(e,t,i,s,n)}sizeInterpolateFunction(e,t,i){return bs.Lerp(e,t,i)}color3InterpolateFunction(e,t,i){return J.Lerp(e,t,i)}color3InterpolateFunctionWithTangents(e,t,i,s,n){return J.Hermite(e,t,i,s,n)}color4InterpolateFunction(e,t,i){return ee.Lerp(e,t,i)}color4InterpolateFunctionWithTangents(e,t,i,s,n){return ee.Hermite(e,t,i,s,n)}_getKeyValue(e){return"function"==typeof e?e():e}evaluate(e){return Ns.key=0,this._interpolate(e,Ns)}_interpolate(e,t,i=!1){if(t.loopMode===Ls.ANIMATIONLOOPMODE_CONSTANT&&t.repeatCount>0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const s=this._keys,n=s.length;let r=t.key;for(;r>=0&&e<s[r].frame;)--r;for(;r+1<=n-1&&e>=s[r+1].frame;)++r;if(t.key=r,r<0)return i?void 0:this._getKeyValue(s[0].value);if(r+1>n-1)return i?void 0:this._getKeyValue(s[n-1].value);const a=s[r],o=s[r+1];if(i&&(e===a.frame||e===o.frame))return;const l=this._getKeyValue(a.value),h=this._getKeyValue(o.value);if(1===a.interpolation)return o.frame>e?l:h;const c=void 0!==a.outTangent&&void 0!==o.inTangent,u=o.frame-a.frame;let d=(e-a.frame)/u;const _=a.easingFunction||this.getEasingFunction();switch(null!==_&&(d=_.ease(d)),this.dataType){case Ls.ANIMATIONTYPE_FLOAT:{const e=c?this.floatInterpolateFunctionWithTangents(l,a.outTangent*u,h,o.inTangent*u,d):this.floatInterpolateFunction(l,h,d);switch(t.loopMode){case Ls.ANIMATIONLOOPMODE_CYCLE:case Ls.ANIMATIONLOOPMODE_CONSTANT:case Ls.ANIMATIONLOOPMODE_YOYO:return e;case Ls.ANIMATIONLOOPMODE_RELATIVE:case Ls.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+e}break}case Ls.ANIMATIONTYPE_QUATERNION:{const e=c?this.quaternionInterpolateFunctionWithTangents(l,a.outTangent.scale(u),h,o.inTangent.scale(u),d):this.quaternionInterpolateFunction(l,h,d);switch(t.loopMode){case Ls.ANIMATIONLOOPMODE_CYCLE:case Ls.ANIMATIONLOOPMODE_CONSTANT:case Ls.ANIMATIONLOOPMODE_YOYO:return e;case Ls.ANIMATIONLOOPMODE_RELATIVE:case Ls.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||ys).scale(t.repeatCount))}return e}case Ls.ANIMATIONTYPE_VECTOR3:{const e=c?this.vector3InterpolateFunctionWithTangents(l,a.outTangent.scale(u),h,o.inTangent.scale(u),d):this.vector3InterpolateFunction(l,h,d);switch(t.loopMode){case Ls.ANIMATIONLOOPMODE_CYCLE:case Ls.ANIMATIONLOOPMODE_CONSTANT:case Ls.ANIMATIONLOOPMODE_YOYO:return e;case Ls.ANIMATIONLOOPMODE_RELATIVE:case Ls.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Ms).scale(t.repeatCount))}break}case Ls.ANIMATIONTYPE_VECTOR2:{const e=c?this.vector2InterpolateFunctionWithTangents(l,a.outTangent.scale(u),h,o.inTangent.scale(u),d):this.vector2InterpolateFunction(l,h,d);switch(t.loopMode){case Ls.ANIMATIONLOOPMODE_CYCLE:case Ls.ANIMATIONLOOPMODE_CONSTANT:case Ls.ANIMATIONLOOPMODE_YOYO:return e;case Ls.ANIMATIONLOOPMODE_RELATIVE:case Ls.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||xs).scale(t.repeatCount))}break}case Ls.ANIMATIONTYPE_SIZE:switch(t.loopMode){case Ls.ANIMATIONLOOPMODE_CYCLE:case Ls.ANIMATIONLOOPMODE_CONSTANT:case Ls.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,h,d);case Ls.ANIMATIONLOOPMODE_RELATIVE:case Ls.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,h,d).add((t.offsetValue||Os).scale(t.repeatCount))}break;case Ls.ANIMATIONTYPE_COLOR3:{const e=c?this.color3InterpolateFunctionWithTangents(l,a.outTangent.scale(u),h,o.inTangent.scale(u),d):this.color3InterpolateFunction(l,h,d);switch(t.loopMode){case Ls.ANIMATIONLOOPMODE_CYCLE:case Ls.ANIMATIONLOOPMODE_CONSTANT:case Ls.ANIMATIONLOOPMODE_YOYO:return e;case Ls.ANIMATIONLOOPMODE_RELATIVE:case Ls.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Ds).scale(t.repeatCount))}break}case Ls.ANIMATIONTYPE_COLOR4:{const e=c?this.color4InterpolateFunctionWithTangents(l,a.outTangent.scale(u),h,o.inTangent.scale(u),d):this.color4InterpolateFunction(l,h,d);switch(t.loopMode){case Ls.ANIMATIONLOOPMODE_CYCLE:case Ls.ANIMATIONLOOPMODE_CONSTANT:case Ls.ANIMATIONLOOPMODE_YOYO:return e;case Ls.ANIMATIONLOOPMODE_RELATIVE:case Ls.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Ps).scale(t.repeatCount))}break}case Ls.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case Ls.ANIMATIONLOOPMODE_CYCLE:case Ls.ANIMATIONLOOPMODE_CONSTANT:case Ls.ANIMATIONLOOPMODE_YOYO:return Ls.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,h,d,t.workValue):l;case Ls.ANIMATIONLOOPMODE_RELATIVE:case Ls.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}}return 0}matrixInterpolateFunction(e,t,i,s){return Ls.AllowMatrixDecomposeForInterpolation?s?(G.DecomposeLerpToRef(e,t,i,s),s):G.DecomposeLerp(e,t,i):s?(G.LerpToRef(e,t,i,s),s):G.Lerp(e,t,i)}clone(){const e=new Ls(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(const t in this._ranges){const i=this._ranges[t];i&&(e._ranges[t]=i.clone())}}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){Ns.key=0;const t=this._interpolate(e,Ns,!0);if(!t)return this._keys[Ns.key].frame===e?Ns.key:Ns.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(Ns.key+1,0,i),Ns.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 i=this.getKeys();for(let s=0;s<i.length;s++){const n=i[s],r={};switch(r.frame=n.frame,t){case Ls.ANIMATIONTYPE_FLOAT:r.values=[n.value],void 0!==n.inTangent&&r.values.push(n.inTangent),void 0!==n.outTangent&&(void 0===n.inTangent&&r.values.push(void 0),r.values.push(n.outTangent)),void 0!==n.interpolation&&(void 0===n.inTangent&&r.values.push(void 0),void 0===n.outTangent&&r.values.push(void 0),r.values.push(n.interpolation));break;case Ls.ANIMATIONTYPE_QUATERNION:case Ls.ANIMATIONTYPE_MATRIX:case Ls.ANIMATIONTYPE_VECTOR3:case Ls.ANIMATIONTYPE_COLOR3:case Ls.ANIMATIONTYPE_COLOR4:r.values=n.value.asArray(),null!=n.inTangent&&r.values.push(n.inTangent.asArray()),null!=n.outTangent&&(void 0===n.inTangent&&r.values.push(void 0),r.values.push(n.outTangent.asArray())),void 0!==n.interpolation&&(void 0===n.inTangent&&r.values.push(void 0),void 0===n.outTangent&&r.values.push(void 0),r.values.push(n.interpolation))}e.keys.push(r)}e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const s={};s.name=t,s.from=i.from,s.to=i.to,e.ranges.push(s)}return e}static _UniversalLerp(e,t,i){const s=e.constructor;return s.Lerp?s.Lerp(e,t,i):s.Slerp?s.Slerp(e,t,i):e.toFixed?e*(1-i)+i*t:t}static Parse(e){const t=new Ls(e.name,e.property,e.framePerSecond,e.dataType,e.loopBehavior),i=e.dataType,s=[];let n,r;for(e.enableBlending&&(t.enableBlending=e.enableBlending),e.blendingSpeed&&(t.blendingSpeed=e.blendingSpeed),r=0;r<e.keys.length;r++){const t=e.keys[r];let a,o,l;switch(i){case Ls.ANIMATIONTYPE_FLOAT:n=t.values[0],t.values.length>=2&&(a=t.values[1]),t.values.length>=3&&(o=t.values[2]),t.values.length>=4&&(l=t.values[3]);break;case Ls.ANIMATIONTYPE_QUATERNION:if(n=k.FromArray(t.values),t.values.length>=8){const e=k.FromArray(t.values.slice(4,8));e.equals(k.Zero())||(a=e)}if(t.values.length>=12){const e=k.FromArray(t.values.slice(8,12));e.equals(k.Zero())||(o=e)}t.values.length>=13&&(l=t.values[12]);break;case Ls.ANIMATIONTYPE_MATRIX:n=G.FromArray(t.values),t.values.length>=17&&(l=t.values[16]);break;case Ls.ANIMATIONTYPE_COLOR3:n=J.FromArray(t.values),t.values[3]&&(a=J.FromArray(t.values[3])),t.values[4]&&(o=J.FromArray(t.values[4])),t.values[5]&&(l=t.values[5]);break;case Ls.ANIMATIONTYPE_COLOR4:n=ee.FromArray(t.values),t.values[4]&&(a=ee.FromArray(t.values[4])),t.values[5]&&(o=ee.FromArray(t.values[5])),t.values[6]&&(l=ee.FromArray(t.values[6]));break;case Ls.ANIMATIONTYPE_VECTOR3:default:n=B.FromArray(t.values),t.values[3]&&(a=B.FromArray(t.values[3])),t.values[4]&&(o=B.FromArray(t.values[4])),t.values[5]&&(l=t.values[5])}const h={};h.frame=t.frame,h.value=n,null!=a&&(h.inTangent=a),null!=o&&(h.outTangent=o),null!=l&&(h.interpolation=l),s.push(h)}if(t.setKeys(s),e.ranges)for(r=0;r<e.ranges.length;r++)n=e.ranges[r],t.createRange(n.name,n.from,n.to);return t}static AppendSerializedAnimations(e,t){se.AppendSerializedAnimations(e,t)}static ParseFromFileAsync(e,t){return new Promise(((i,s)=>{const n=new fe;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){let t=JSON.parse(n.responseText);if(t.animations&&(t=t.animations),t.length){const e=[];for(const i of t)e.push(this.Parse(i));i(e)}else{const s=this.Parse(t);e&&(s.name=e),i(s)}}else s("Unable to load the animation")})),n.open("GET",t),n.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const s=new fe;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){const i=JSON.parse(JSON.parse(s.responseText).jsonPayload);if(i.animations){const s=JSON.parse(i.animations),n=[];for(const t of s.animations){const i=this.Parse(t);i.snippetId=e,n.push(i)}t(n)}else{const s=JSON.parse(i.animation),n=this.Parse(s);n.snippetId=e,t(n)}}else i("Unable to load the snippet "+e)})),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()}))}}Ls._UniqueIdGenerator=0,Ls.AllowMatricesInterpolation=!1,Ls.AllowMatrixDecomposeForInterpolation=!0,Ls.SnippetUrl=tt.SnippetUrl,Ls.ANIMATIONTYPE_FLOAT=0,Ls.ANIMATIONTYPE_VECTOR3=1,Ls.ANIMATIONTYPE_QUATERNION=2,Ls.ANIMATIONTYPE_MATRIX=3,Ls.ANIMATIONTYPE_COLOR3=4,Ls.ANIMATIONTYPE_COLOR4=7,Ls.ANIMATIONTYPE_VECTOR2=5,Ls.ANIMATIONTYPE_SIZE=6,Ls.ANIMATIONLOOPMODE_RELATIVE=0,Ls.ANIMATIONLOOPMODE_CYCLE=1,Ls.ANIMATIONLOOPMODE_CONSTANT=2,Ls.ANIMATIONLOOPMODE_YOYO=4,Ls.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,Ls.CreateFromSnippetAsync=Ls.ParseFromSnippetAsync,C("BABYLON.Animation",Ls),re._AnimationRangeFactory=(e,t,i)=>new Cs(e,t,i);class Fs{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,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))}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||(Fs.EasingFunction.setEasingMode(Fs.EasingMode),this._radiusBounceTransition=Ls.CreateAnimation("radius",Ls.ANIMATIONTYPE_FLOAT,60,Fs.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=Ls.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()}}Fs.EasingFunction=new class extends Ss{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)}}(.3),Fs.EasingMode=Ss.EASINGMODE_EASEOUT;class ws{constructor(){this.onTargetFramingAnimationEndObservable=new g,this._mode=ws.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._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}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();ws.EasingFunction.setEasingMode(ws.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==Es.POINTERDOWN?e.type===Es.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,i=null){e.computeWorldMatrix(!0);const s=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(s.minimumWorld,s.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(s.min,s.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const s=new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new B(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t<e.length;t++){const i=e[t].getHierarchyBoundingVectors(!0);B.CheckExtends(i.min,s,n),B.CheckExtends(i.max,s,n)}this.zoomOnBoundingInfo(s,n,t,i)}zoomOnBoundingInfo(e,t,i=!1,s=null){let n;if(!this._attachedCamera)return!1;const r=e.y,a=r+(t.y-r)*this._positionScale,o=t.subtract(e).scale(.5);if(i)n=new B(0,a,0);else{const t=e.add(o);n=new B(t.x,a,t.z)}this._vectorTransition||(this._vectorTransition=Ls.CreateAnimation("target",Ls.ANIMATIONTYPE_VECTOR3,60,ws.EasingFunction)),this._betaIsAnimating=!0;let l=Ls.TransitionTo("target",n,this._attachedCamera,this._attachedCamera.getScene(),60,this._vectorTransition,this._framingTime);l&&this._animatables.push(l);let h=0;if(this._mode===ws.FitFrustumSidesMode){const i=this._calculateLowerRadiusFromModelBoundingSphere(e,t);this.autoCorrectCameraLimitsAndSensibility&&(this._attachedCamera.lowerRadiusLimit=o.length()+this._attachedCamera.minZ),h=i}else this._mode===ws.IgnoreBoundsSizeMode&&(h=this._calculateLowerRadiusFromModelBoundingSphere(e,t),this.autoCorrectCameraLimitsAndSensibility&&null===this._attachedCamera.lowerRadiusLimit&&(this._attachedCamera.lowerRadiusLimit=this._attachedCamera.minZ));if(this.autoCorrectCameraLimitsAndSensibility){const i=t.subtract(e).length();this._attachedCamera.panningSensibility=5e3/i,this._attachedCamera.wheelPrecision=100/h}return this._radiusTransition||(this._radiusTransition=Ls.CreateAnimation("radius",Ls.ANIMATIONTYPE_FLOAT,60,ws.EasingFunction)),l=Ls.TransitionTo("radius",h,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusTransition,this._framingTime,(()=>{this.stopAllAnimations(),s&&s(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),l&&this._animatables.push(l),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let s=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===ws.IgnoreBoundsSizeMode&&(s=s<i.lowerRadiusLimit?i.lowerRadiusLimit:s),i.upperRadiusLimit&&(s=s>i.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=_e.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,i=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=Ls.CreateAnimation("beta",Ls.ANIMATIONTYPE_FLOAT,60,ws.EasingFunction));const e=Ls.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=_e.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)}}ws.EasingFunction=new class extends Ss{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)}},ws.EasingMode=Ss.EASINGMODE_EASEINOUT,ws.IgnoreBoundsSizeMode=0,ws.FitFrustumSidesMode=1,re.AddNodeConstructor("TargetCamera",((e,t)=>()=>new Bs(e,B.Zero(),t)));class Bs extends ri{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=B.Zero(),this._tmpTargetVector=B.Zero(),this.cameraDirection=new B(0,0,0),this.cameraRotation=new w(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new k,this.rotation=new B(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=B.Zero(),this._initialFocalDistance=1,this._viewMatrix=G.Zero(),this._camMatrix=G.Zero(),this._cameraTransformMatrix=G.Zero(),this._cameraRotationMatrix=G.Zero(),this._referencePoint=new B(0,0,1),this._transformedReferencePoint=B.Zero(),this._deferredPositionUpdate=new B,this._deferredRotationQuaternionUpdate=new k,this._deferredRotationUpdate=new B,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=B.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();const t=this.getTarget().subtract(this.position);return t.normalize(),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.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)}_initCache(){super._initCache(),this._cache.lockedTarget=new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new k(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+=A),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),G.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);const t=e.subtract(this.position);t.x>=0?this.rotation.y=-Math.atan(t.z/t.x)+Math.PI/2:this.rotation.y=-Math.atan(t.z/t.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&k.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}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(X.Matrix[0]),B.TransformNormalToRef(this.cameraDirection,X.Matrix[0],X.Vector3[0]),this._deferredPositionUpdate.addInPlace(X.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.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=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),t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!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()&&(k.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))}}t&&(Math.abs(this.cameraDirection.x)<this.speed*A&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<this.speed*A&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<this.speed*A&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),i&&(Math.abs(this.cameraRotation.x)<this.speed*A&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<this.speed*A&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),super._checkInputs()}_updateCameraRotationMatrix(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):G.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)}_rotateUpVectorWithCameraRotationMatrix(){return B.TransformNormalToRef(this._defaultUp,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),B.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?Ki.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(k.FromEulerVectorToRef(this.rotation,this._tmpQuaternion),Ki.Y.rotateByQuaternionToRef(this._tmpQuaternion,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix}_computeViewMatrix(e,t,i){if(this.ignoreParentScaling){if(this.parent){const s=this.parent.getWorldMatrix();B.TransformCoordinatesToRef(e,s,this._globalPosition),B.TransformCoordinatesToRef(t,s,this._tmpTargetVector),B.TransformNormalToRef(i,s,this._tmpUpVector),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e),this._tmpTargetVector.copyFrom(t),this._tmpUpVector.copyFrom(i);this.getScene().useRightHandedSystem?G.LookAtRHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix):G.LookAtLHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix)}else if(this.getScene().useRightHandedSystem?G.LookAtRHToRef(e,t,i,this._viewMatrix):G.LookAtLHToRef(e,t,i,this._viewMatrix),this.parent){const e=this.parent.getWorldMatrix();this._viewMatrix.invert(),this._viewMatrix.multiplyToRef(e,this._viewMatrix),this._viewMatrix.getTranslationToRef(this._globalPosition),this._viewMatrix.invert(),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e)}createRigCamera(e,t){if(this.cameraRigMode!==ri.RIG_MODE_NONE){const t=new Bs(e,this.position.clone(),this.getScene());return t.isRigCamera=!0,t.rigParent=this,this.cameraRigMode===ri.RIG_MODE_VR&&(this.rotationQuaternion||(this.rotationQuaternion=new k),t._cameraRigParams={},t.rotationQuaternion=new k),t.mode=this.mode,t.orthoLeft=this.orthoLeft,t.orthoRight=this.orthoRight,t.orthoTop=this.orthoTop,t.orthoBottom=this.orthoBottom,t}return null}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case ri.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ri.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ri.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case ri.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ri.RIG_MODE_STEREOSCOPIC_INTERLACED:{const i=this.cameraRigMode===ri.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,s=this.cameraRigMode===ri.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*i,e),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*s,t);break}case ri.RIG_MODE_VR:e.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(e,t){this.getTarget().subtractToRef(this.position,Bs._TargetFocalPoint),Bs._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);const i=Bs._TargetFocalPoint.addInPlace(this.position);G.TranslationToRef(-i.x,-i.y,-i.z,Bs._TargetTransformMatrix),Bs._TargetTransformMatrix.multiplyToRef(G.RotationAxis(t.upVector,e),Bs._RigCamTransformMatrix),G.TranslationToRef(i.x,i.y,i.z,Bs._TargetTransformMatrix),Bs._RigCamTransformMatrix.multiplyToRef(Bs._TargetTransformMatrix,Bs._RigCamTransformMatrix),B.TransformCoordinatesToRef(this.position,Bs._RigCamTransformMatrix,t.position),t.setTarget(i)}getClassName(){return"TargetCamera"}}Bs._RigCamTransformMatrix=new G,Bs._TargetTransformMatrix=new G,Bs._TargetFocalPoint=new B,e([c()],Bs.prototype,"rotation",void 0),e([a()],Bs.prototype,"speed",void 0),e([u("lockedTargetId")],Bs.prototype,"lockedTarget",void 0);var Us,ks={};class Gs{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?ce.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 i=this.attached[t];if(i===e)return i.detachControl(),i.camera=null,delete this.attached[t],void this.rebuildInputCheck()}}removeByType(e){for(const t in this.attached){const i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.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=!ri.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 i=this.attached[e],s=se.Serialize(i);t[i.getClassName()]=s}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=ks[e];if(i){const s=t[e],n=se.Parse((()=>new i),s,null);this.add(n)}}}else for(const t in this.attached){const i=ks[this.attached[t].getClassName()];if(i){const s=se.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(s)}}}}class Vs{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Qt.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let s=0,n=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=r=>{const a=r.event,o="touch"===a.pointerType;if(r.type!==Es.POINTERMOVE&&-1===this.buttons.indexOf(a.button))return;const l=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(r.type!==Es.POINTERDOWN&&r.type!==Es.POINTERDOUBLETAP&&o&&this._pointA?.pointerId!==a.pointerId&&this._pointB?.pointerId!==a.pointerId)return;if(r.type!==Es.POINTERDOWN||-1!==this._currentActiveButton&&!o)if(r.type===Es.POINTERDOUBLETAP)this.onDoubleTap(a.pointerType);else if(r.type!==Es.POINTERUP||this._currentActiveButton!==a.button&&!o){if(r.type===Es.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,i=this._pointA.y-this._pointB.y,o=t*t+i*i,l={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:a.pointerId,type:r.type};this.onMultiTouch(this._pointA,this._pointB,s,o,n,l),n=l,s=o}}else{try{l?.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!==s||n)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,n,null),s=0,n=null),this._currentActiveButton=-1,this.onButtonUp(a),e||a.preventDefault()}else{try{l?.setPointerCapture(a.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:a.clientX,y:a.clientY,pointerId:a.pointerId,type:a.pointerType};else{if(null!==this._pointB)return;this._pointB={x:a.clientX,y:a.clientY,pointerId:a.pointerId,type:a.pointerType}}-1!==this._currentActiveButton||o||(this._currentActiveButton=a.button),this.onButtonDown(a),e||(a.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Es.POINTERDOWN|Es.POINTERUP|Es.POINTERMOVE|Es.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,n=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const r=this.camera.getScene().getEngine().getHostWindow();r&&Qt.RegisterTopRootEvents(r,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Qt.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._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,s,n,r){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}e([a()],Vs.prototype,"buttons",void 0);class Xs extends Vs{constructor(){super(...arguments),this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.useNaturalPinchZoom=!1,this.pinchZoom=!0,this.panningSensibility=1e3,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this.pinchInwards=!0,this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}getClassName(){return"ArcRotateCameraPointersInput"}_computeMultiTouchPanning(e,t){if(0!==this.panningSensibility&&e&&t){const i=t.x-e.x,s=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=s/this.panningSensibility}}_computePinchZoom(e,t){const i=this.camera.radius||Xs.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=.001*(t-e)*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){0!==this.panningSensibility&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,s,n,r){0===i&&null===n||0===s&&null===r||(this.multiTouchPanAndZoom?(this._computePinchZoom(i,s),this._computeMultiTouchPanning(n,r)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(s)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,s),this._isPinching=!0):this._computeMultiTouchPanning(n,r)):this.multiTouchPanning?this._computeMultiTouchPanning(n,r):this.pinchZoom&&this._computePinchZoom(i,s))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}Xs.MinimumRadiusForPinch=.001,e([a()],Xs.prototype,"buttons",void 0),e([a()],Xs.prototype,"angularSensibilityX",void 0),e([a()],Xs.prototype,"angularSensibilityY",void 0),e([a()],Xs.prototype,"pinchPrecision",void 0),e([a()],Xs.prototype,"pinchDeltaPercentage",void 0),e([a()],Xs.prototype,"useNaturalPinchZoom",void 0),e([a()],Xs.prototype,"pinchZoom",void 0),e([a()],Xs.prototype,"panningSensibility",void 0),e([a()],Xs.prototype,"multiTouchPanning",void 0),e([a()],Xs.prototype,"multiTouchPanAndZoom",void 0),ks.ArcRotateCameraPointersInput=Xs;class Hs{}Hs.KEYDOWN=1,Hs.KEYUP=2;class zs{constructor(e,t){this.type=e,this.event=t}}class Ws extends zs{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}}class Ys{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=Qt.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===Hs.KEYDOWN){if(this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault())}}else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.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;for(let t=0;t<this._keys.length;t++){const i=this._keys[t];-1!==this.keysLeft.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX-=1/this.panningSensibility:e.inertialAlphaOffset-=this.angularSpeed:-1!==this.keysUp.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY+=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset+=1/this.zoomingSensibility:e.inertialBetaOffset-=this.angularSpeed:-1!==this.keysRight.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX+=1/this.panningSensibility:e.inertialAlphaOffset+=this.angularSpeed:-1!==this.keysDown.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY-=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset-=1/this.zoomingSensibility:e.inertialBetaOffset+=this.angularSpeed:-1!==this.keysReset.indexOf(i)&&e.useInputToRestoreState&&e.restoreState()}}}getClassName(){return"ArcRotateCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}}e([a()],Ys.prototype,"keysUp",void 0),e([a()],Ys.prototype,"keysDown",void 0),e([a()],Ys.prototype,"keysLeft",void 0),e([a()],Ys.prototype,"keysRight",void 0),e([a()],Ys.prototype,"keysReset",void 0),e([a()],Ys.prototype,"panningSensibility",void 0),e([a()],Ys.prototype,"zoomingSensibility",void 0),e([a()],Ys.prototype,"useAltToZoom",void 0),e([a()],Ys.prototype,"angularSpeed",void 0),ks.ArcRotateCameraKeyboardMoveInput=Ys,function(e){e[e.PointerMove=0]="PointerMove",e[e.PointerDown=1]="PointerDown",e[e.PointerUp=2]="PointerUp"}(Us||(Us={}));class Ks{}Ks.DOM_DELTA_PIXEL=0,Ks.DOM_DELTA_LINE=1,Ks.DOM_DELTA_PAGE=2;class qs{constructor(){this.wheelPrecision=3,this.zoomToMouseLocation=!1,this.wheelDeltaPercentage=0,this.customComputeDeltaFromMouseWheel=null,this._viewOffset=new B(0,0,0),this._globalOffset=new B(0,0,0),this._inertialPanning=B.Zero()}_computeDeltaFromMouseWheelLegacyEvent(e,t){let i=0;const s=.01*e*this.wheelDeltaPercentage*t;return i=e>0?s/(1+this.wheelDeltaPercentage):s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Qt.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Es.POINTERWHEEL)return;const i=t.event;let s=0;const n=i.deltaMode===Ks.DOM_DELTA_LINE?40:1,r=-i.deltaY*n;if(this.customComputeDeltaFromMouseWheel)s=this.customComputeDeltaFromMouseWheel(r,this,i);else if(this.wheelDeltaPercentage){if(s=this._computeDeltaFromMouseWheelLegacyEvent(r,this.camera.radius),s>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+s;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=q.Clamp(e,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(r,e)}}else s=r/(40*this.wheelPrecision);s&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(s)):this.camera.inertialRadiusOffset+=s),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Es.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;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){const e=this.camera,t=e.target.subtract(e.position);this._hitPlane=si.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,G.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=B.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(s))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const s=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/i<s&&(e=(t.radius-s)*i-t.inertialRadiusOffset)}if(t.upperRadiusLimit){const s=t.upperRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/i>s&&(e=(t.radius-s)*i-t.inertialRadiusOffset)}const s=e/i/t.radius,n=this._getPosition(),r=X.Vector3[6];n.subtractToRef(t.target,r),r.scaleInPlace(s),r.scaleInPlace(i),this._inertialPanning.addInPlace(r),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)<A&&(e.x=0),Math.abs(e.y)<A&&(e.y=0),Math.abs(e.z)<A&&(e.z=0)}}e([a()],qs.prototype,"wheelPrecision",void 0),e([a()],qs.prototype,"zoomToMouseLocation",void 0),e([a()],qs.prototype,"wheelDeltaPercentage",void 0),ks.ArcRotateCameraMouseWheelInput=qs;class Qs extends Gs{constructor(e){super(e)}addMouseWheel(){return this.add(new qs),this}addPointers(){return this.add(new Xs),this}addKeyboard(){return this.add(new Ys),this}}re.AddNodeConstructor("ArcRotateCamera",((e,t)=>()=>new js(e,0,0,1,B.Zero(),t)));class js extends Bs{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 G,this._upToYMatrix=new G,this._upVector=B.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){G.RotationAlignToRef(B.UpReadOnly,this._upVector,this._yToUpMatrix),G.RotationAlignToRef(this._upVector,B.UpReadOnly,this._upToYMatrix)}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 bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Fs,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 ws,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 vs,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,n,r,a=!0){super(e,B.Zero(),r,a),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=B.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=w.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this.restoreStateInterpolationFactor=0,this._viewMatrix=new G,this.panningAxis=new B(1,1,0),this._transformedDirection=new B,this.mapPanning=!1,this._progressiveRestore=!1,this.onMeshTargetChangedObservable=new g,this.checkCollisions=!1,this.collisionRadius=new B(.5,.5,.5),this._previousPosition=B.Zero(),this._collisionVelocity=B.Zero(),this._newPosition=B.Zero(),this._computationVector=B.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);const s=Math.cos(this.alpha),n=Math.sin(this.alpha),r=Math.cos(this.beta);let a=Math.sin(this.beta);0===a&&(a=1e-4);const o=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*s*a,this.radius*r,this.radius*n*a),o.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=l.clone(),l=l.negate()),this._computeViewMatrix(this._position,o,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=B.Zero(),n&&this.setTarget(n),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new Qs(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new B(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=w.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>A&&this.restoreStateInterpolationFactor<1?(this._progressiveRestore=!0,this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!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)}_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,i=!0,s=2){const n=arguments;t=Qt.BackCompatCameraNoPreventDefault(n),this._useCtrlForPanning=i,this._panningMouseButton=s,"boolean"==typeof n[0]&&(n.length>1&&(this._useCtrlForPanning=n[1]),n.length>2&&(this._panningMouseButton=n[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()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),this._progressiveRestore){const e=this._scene.getEngine().getDeltaTime()/1e3,t=1-Math.pow(2,-e/this.restoreStateInterpolationFactor);this.setTarget(B.Lerp(this.getTarget(),this._storedTarget,t)),k.RotationAlphaBetaGammaToRef(this._storedAlpha,this._storedBeta,0,X.Quaternion[0]),k.RotationAlphaBetaGammaToRef(this.alpha,this.beta,0,X.Quaternion[1]),k.SlerpToRef(X.Quaternion[1],X.Quaternion[0],t,X.Quaternion[2]),X.Quaternion[2].normalize(),X.Quaternion[2].toAlphaBetaGammaToRef(X.Vector3[0]),this.alpha=X.Vector3[0].x,this.beta=X.Vector3[0].y,this.radius+=(this._storedRadius-this.radius)*t,w.LerpToRef(this.targetScreenOffset,this._storedTargetScreenOffset,t,this.targetScreenOffset),(B.DistanceSquared(this.getTarget(),this._storedTarget)<A&&X.Quaternion[2].equalsWithEpsilon(X.Quaternion[0])&&Math.pow(this._storedRadius-this.radius,2)<A&&w.Distance(this.targetScreenOffset,this._storedTargetScreenOffset)<A||0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset||0!==this.inertialPanningX||0!==this.inertialPanningY)&&(this._progressiveRestore=!1)}if(0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)<A&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<A&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<this.speed*A&&(this.inertialRadiusOffset=0)}if(0!==this.inertialPanningX||0!==this.inertialPanningY){const e=new B(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY);if(this._viewMatrix.invertToRef(this._cameraTransformMatrix),e.multiplyInPlace(this.panningAxis),B.TransformNormalToRef(e,this._cameraTransformMatrix,this._transformedDirection),this.mapPanning){const e=this.upVector,t=B.CrossToRef(this._transformedDirection,e,this._transformedDirection);B.CrossToRef(e,t,this._transformedDirection)}else this.panningAxis.y||(this._transformedDirection.y=0);if(!this._targetHost)if(this.panningDistanceLimit){this._transformedDirection.addInPlace(this._target);B.DistanceSquared(this._transformedDirection,this.panningOriginTarget)<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection)}else{if(this.parent){const e=X.Matrix[0];this.parent.getWorldMatrix().getRotationMatrixToRef(e),e.transposeToRef(e),B.TransformCoordinatesToRef(this._transformedDirection,e,this._transformedDirection)}this._target.addInPlace(this._transformedDirection)}this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia,Math.abs(this.inertialPanningX)<this.speed*A&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<this.speed*A&&(this.inertialPanningY=0)}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)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||B.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,s=!1){if(s=this.overrideCloneAlphaBetaRadius??s,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,s=this._getTargetPosition();if(s&&!i&&s.equals(t))return;this._targetHost=null,this._target=t,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}s||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let s=Math.sin(this.beta);0===s&&(s=1e-4),0===this.radius&&(this.radius=1e-4);const n=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*s,this.radius*i,this.radius*t*s),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||B.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),n.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&&s<0&&(e=e.negate()),this._computeViewMatrix(this._position,n,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=n,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=gs.MinMax(e);let s=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);s=Math.max(Math.min(s,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=s*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:s},t)}focusOn(e,t=!1){let i,s;if(void 0===e.min){const t=e||this.getScene().meshes;i=gs.MinMax(t),s=B.Distance(i.min,i.max)}else{i=e,s=e.distance}this._target=gs.Center(i),t||(this.maxZ=2*s)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case ri.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ri.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ri.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ri.RIG_MODE_STEREOSCOPIC_INTERLACED:case ri.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case ri.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const s=new js(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return s._cameraRigParams={},s.isRigCamera=!0,s.rigParent=this,s.upVector=this.upVector,s.mode=this.mode,s.orthoLeft=this.orthoLeft,s.orthoRight=this.orthoRight,s.orthoBottom=this.orthoBottom,s.orthoTop=this.orthoTop,s}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case ri.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ri.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ri.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ri.RIG_MODE_STEREOSCOPIC_INTERLACED:case ri.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case ri.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const s=B.Distance(e,t),n=this.getScene().getEngine().getAspectRatio(this),r=Math.tan(this.fov/2),a=r*n,o=.5*s*i,l=o*Math.sqrt(1+1/(a*a)),h=o*Math.sqrt(1+1/(r*r));return Math.max(l,h)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}e([a()],js.prototype,"alpha",void 0),e([a()],js.prototype,"beta",void 0),e([a()],js.prototype,"radius",void 0),e([a()],js.prototype,"overrideCloneAlphaBetaRadius",void 0),e([c("target")],js.prototype,"_target",void 0),e([u("targetHost")],js.prototype,"_targetHost",void 0),e([a()],js.prototype,"inertialAlphaOffset",void 0),e([a()],js.prototype,"inertialBetaOffset",void 0),e([a()],js.prototype,"inertialRadiusOffset",void 0),e([a()],js.prototype,"lowerAlphaLimit",void 0),e([a()],js.prototype,"upperAlphaLimit",void 0),e([a()],js.prototype,"lowerBetaLimit",void 0),e([a()],js.prototype,"upperBetaLimit",void 0),e([a()],js.prototype,"lowerRadiusLimit",void 0),e([a()],js.prototype,"upperRadiusLimit",void 0),e([a()],js.prototype,"inertialPanningX",void 0),e([a()],js.prototype,"inertialPanningY",void 0),e([a()],js.prototype,"pinchToPanMaxDistance",void 0),e([a()],js.prototype,"panningDistanceLimit",void 0),e([c()],js.prototype,"panningOriginTarget",void 0),e([a()],js.prototype,"panningInertia",void 0),e([a()],js.prototype,"zoomToMouseLocation",null),e([a()],js.prototype,"zoomOnFactor",void 0),e([h()],js.prototype,"targetScreenOffset",void 0),e([a()],js.prototype,"allowUpsideDown",void 0),e([a()],js.prototype,"useInputToRestoreState",void 0),e([a()],js.prototype,"restoreStateInterpolationFactor",void 0),C("BABYLON.ArcRotateCamera",js);class Zs extends re{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 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(e,t){super(e,t,!1),this.diffuse=new J(1,1,1),this.specular=new J(1,1,1),this.falloffType=Zs.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=Zs.INTENSITYMODE_AUTOMATIC,this._radius=1e-5,this.renderPriority=0,this._shadowEnabled=!0,this._excludeWithLayerMask=0,this._includeOnlyWithLayerMask=0,this._lightmapMode=0,this._shadowGenerators=null,this._excludedMeshesIds=new Array,this._includedOnlyMeshesIds=new Array,this._isLight=!0,this.getScene().addLight(this),this._uniformBuffer=new Wi(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=[],this.excludedMeshes=[],this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,s,n=!0){const r=e.toString();let a=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+r),this._renderId!==t.getRenderId()||this._lastUseSpecular!==s||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=s;const e=this.getScaledIntensity();this.transferToEffect(i,r),this.diffuse.scaleToRef(e,te.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",te.Color3[0],this.range,r),s&&(this.specular.scaleToRef(e,te.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",te.Color3[1],this.radius,r)),a=!0}if(this.transferTexturesToEffect(i,r),t.shadowsEnabled&&this.shadowEnabled&&n){const e=this.getShadowGenerator(t.activeCamera)??this.getShadowGenerator();e&&(e.bindShadowLight(r,i),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"][this.getTypeID()],this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].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 B.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||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(e,t=null){const i=Zs.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=se.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=se.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach((t=>{e.excludedMeshesIds.push(t.id)}))),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((t=>{e.includedOnlyMeshesIds.push(t.id)}))),se.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const s=re.Construct("Light_Type_"+e,t,i);return s||null}static Parse(e,t){const i=Zs.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=se.Parse(i,e,t);if(e.excludedMeshesIds&&(s._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(s._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(s.falloffType=e.falloffType),void 0!==e.lightmapMode&&(s.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t<e.animations.length;t++){const i=e.animations[t],n=b("BABYLON.Animation");n&&s.animations.push(n.Parse(i))}re.ParseAnimationRanges(s,e,t)}return e.autoAnimate&&t.beginAnimation(s,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&s.setEnabled(e.isEnabled),s}_hookArrayForExcluded(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);for(const e of i)e._resyncLightSource(this);return s};const i=e.splice;e.splice=(t,s)=>{const n=i.apply(e,[t,s]);for(const e of n)e._resyncLightSource(this);return n};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._resyncMeshes(),s};const i=e.splice;e.splice=(t,s)=>{const n=i.apply(e,[t,s]);return this._resyncMeshes(),n},this._resyncMeshes()}_resyncMeshes(){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 e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===Zs.INTENSITYMODE_AUTOMATIC&&(i=t===Zs.LIGHTTYPEID_DIRECTIONALLIGHT?Zs.INTENSITYMODE_ILLUMINANCE:Zs.INTENSITYMODE_LUMINOUSINTENSITY),t){case Zs.LIGHTTYPEID_POINTLIGHT:case Zs.LIGHTTYPEID_SPOTLIGHT:switch(i){case Zs.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Zs.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Zs.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case Zs.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Zs.INTENSITYMODE_ILLUMINANCE:e=1;break;case Zs.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001);e=2*Math.PI*(1-Math.cos(t));break}}break;case Zs.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Zs.FALLOFF_DEFAULT=$i.FALLOFF_DEFAULT,Zs.FALLOFF_PHYSICAL=$i.FALLOFF_PHYSICAL,Zs.FALLOFF_GLTF=$i.FALLOFF_GLTF,Zs.FALLOFF_STANDARD=$i.FALLOFF_STANDARD,Zs.LIGHTMAP_DEFAULT=$i.LIGHTMAP_DEFAULT,Zs.LIGHTMAP_SPECULAR=$i.LIGHTMAP_SPECULAR,Zs.LIGHTMAP_SHADOWSONLY=$i.LIGHTMAP_SHADOWSONLY,Zs.INTENSITYMODE_AUTOMATIC=$i.INTENSITYMODE_AUTOMATIC,Zs.INTENSITYMODE_LUMINOUSPOWER=$i.INTENSITYMODE_LUMINOUSPOWER,Zs.INTENSITYMODE_LUMINOUSINTENSITY=$i.INTENSITYMODE_LUMINOUSINTENSITY,Zs.INTENSITYMODE_ILLUMINANCE=$i.INTENSITYMODE_ILLUMINANCE,Zs.INTENSITYMODE_LUMINANCE=$i.INTENSITYMODE_LUMINANCE,Zs.LIGHTTYPEID_POINTLIGHT=$i.LIGHTTYPEID_POINTLIGHT,Zs.LIGHTTYPEID_DIRECTIONALLIGHT=$i.LIGHTTYPEID_DIRECTIONALLIGHT,Zs.LIGHTTYPEID_SPOTLIGHT=$i.LIGHTTYPEID_SPOTLIGHT,Zs.LIGHTTYPEID_HEMISPHERICLIGHT=$i.LIGHTTYPEID_HEMISPHERICLIGHT,e([l()],Zs.prototype,"diffuse",void 0),e([l()],Zs.prototype,"specular",void 0),e([a()],Zs.prototype,"falloffType",void 0),e([a()],Zs.prototype,"intensity",void 0),e([a()],Zs.prototype,"range",null),e([a()],Zs.prototype,"intensityMode",null),e([a()],Zs.prototype,"radius",null),e([a()],Zs.prototype,"_renderPriority",void 0),e([r("_reorderLightsInScene")],Zs.prototype,"renderPriority",void 0),e([a("shadowEnabled")],Zs.prototype,"_shadowEnabled",void 0),e([a("excludeWithLayerMask")],Zs.prototype,"_excludeWithLayerMask",void 0),e([a("includeOnlyWithLayerMask")],Zs.prototype,"_includeOnlyWithLayerMask",void 0),e([a("lightmapMode")],Zs.prototype,"_lightmapMode",void 0),re.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new $s(e,B.Zero(),t)));class $s extends Zs{constructor(e,t,i){super(e,i),this.groundColor=new J(0,0,0),this.direction=t||B.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=B.Normalize(e.subtract(B.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=B.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){const i=B.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=G.Identity()),this._worldMatrix}getTypeID(){return Zs.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}e([l()],$s.prototype,"groundColor",void 0),e([c()],$s.prototype,"direction",void 0),C("BABYLON.HemisphericLight",$s);class Js{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 i=this.get(e);return void 0!==i||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return void 0!==i?i:(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 i=e(t,this._data[t]);if(i)return i}return null}}class en{constructor(){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.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,s){for(const n in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,n)&&this._BabylonFileParsers[n](e,t,i,s)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach((t=>e=e.concat(t.bones))),e}}function tn(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}en._BabylonFileParsers={},en._IndividualBabylonFileParsers={},C("BABYLON.AbstractScene",en);class sn{constructor(){this._dirty=!0,this._tempColor=new ee(0,0,0,0),this._globalCurve=new ee(0,0,0,0),this._highlightsCurve=new ee(0,0,0,0),this._midtonesCurve=new ee(0,0,0,0),this._shadowsCurve=new ee(0,0,0,0),this._positiveCurve=new ee(0,0,0,0),this._negativeCurve=new ee(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=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"}static Bind(e,t,i="vCameraColorCurvePositive",s="vCameraColorCurveNeutral",n="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(s,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(n,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,s,n){null!=e&&(e=sn._Clamp(e,0,360),t=sn._Clamp(t,-100,100),i=sn._Clamp(i,-100,100),s=sn._Clamp(s,-100,100),t=sn._ApplyColorGradingSliderNonlinear(t),t*=.5,s=sn._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),sn._FromHSBToRef(e,t,50+.25*s,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(e,t,i,s){let n=sn._Clamp(e,0,360);const r=sn._Clamp(t/100,0,1),a=sn._Clamp(i/100,0,1);if(0===r)s.r=a,s.g=a,s.b=a;else{n/=60;const e=Math.floor(n),t=n-e,i=a*(1-r),o=a*(1-r*t),l=a*(1-r*(1-t));switch(e){case 0:s.r=a,s.g=l,s.b=i;break;case 1:s.r=o,s.g=a,s.b=i;break;case 2:s.r=i,s.g=a,s.b=l;break;case 3:s.r=i,s.g=o,s.b=a;break;case 4:s.r=l,s.g=i,s.b=a;break;default:s.r=a,s.g=i,s.b=o}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return se.Clone((()=>new sn),this)}serialize(){return se.Serialize(this)}static Parse(e){return se.Parse((()=>new sn),e,null,null)}}sn.PrepareUniforms=tn,e([a()],sn.prototype,"_globalHue",void 0),e([a()],sn.prototype,"_globalDensity",void 0),e([a()],sn.prototype,"_globalSaturation",void 0),e([a()],sn.prototype,"_globalExposure",void 0),e([a()],sn.prototype,"_highlightsHue",void 0),e([a()],sn.prototype,"_highlightsDensity",void 0),e([a()],sn.prototype,"_highlightsSaturation",void 0),e([a()],sn.prototype,"_highlightsExposure",void 0),e([a()],sn.prototype,"_midtonesHue",void 0),e([a()],sn.prototype,"_midtonesDensity",void 0),e([a()],sn.prototype,"_midtonesSaturation",void 0),e([a()],sn.prototype,"_midtonesExposure",void 0),se._ColorCurvesParser=sn.Parse;class nn{constructor(){this.colorCurves=new sn,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=nn.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new ee(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=nn.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new g}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(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled)return e.VIGNETTE=!1,e.TONEMAPPING=0,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,void(e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===nn._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,this._toneMappingEnabled)switch(this._toneMappingType){case nn.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case nn.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1}else e.TONEMAPPING=0;e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||!!e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&sn.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),s=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const n=null!=t?t:s/i;let r=Math.tan(.5*this.vignetteCameraFov),a=r*n;const o=Math.sqrt(a*r);a=zt(a,o,this.vignetteStretch),r=zt(r,o,this.vignetteStretch),e.setFloat4("vignetteSettings1",a,r,-a*this.vignetteCenterX,-r*this.vignetteCenterY);const l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}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 se.Clone((()=>new nn),this)}serialize(){return se.Serialize(this)}static Parse(e){const t=se.Parse((()=>new nn),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}nn.TONEMAPPING_STANDARD=0,nn.TONEMAPPING_ACES=1,nn.TONEMAPPING_KHR_PBR_NEUTRAL=2,nn.PrepareUniforms=function(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&&tn(e),t.DITHER&&e.push("ditherIntensity")},nn.PrepareSamplers=function(e,t){t.COLORGRADING&&e.push("txColorTransform")},nn._VIGNETTEMODE_MULTIPLY=0,nn._VIGNETTEMODE_OPAQUE=1,e([function(e){return n(7,e)}()],nn.prototype,"colorCurves",void 0),e([a()],nn.prototype,"_colorCurvesEnabled",void 0),e([o("colorGradingTexture")],nn.prototype,"_colorGradingTexture",void 0),e([a()],nn.prototype,"_colorGradingEnabled",void 0),e([a()],nn.prototype,"_colorGradingWithGreenDepth",void 0),e([a()],nn.prototype,"_colorGradingBGR",void 0),e([a()],nn.prototype,"_exposure",void 0),e([a()],nn.prototype,"_toneMappingEnabled",void 0),e([a()],nn.prototype,"_toneMappingType",void 0),e([a()],nn.prototype,"_contrast",void 0),e([a()],nn.prototype,"vignetteStretch",void 0),e([a()],nn.prototype,"vignetteCenterX",void 0),e([a()],nn.prototype,"vignetteCenterY",void 0),e([a()],nn.prototype,"vignetteWeight",void 0),e([d()],nn.prototype,"vignetteColor",void 0),e([a()],nn.prototype,"vignetteCameraFov",void 0),e([a()],nn.prototype,"_vignetteBlendMode",void 0),e([a()],nn.prototype,"_vignetteEnabled",void 0),e([a()],nn.prototype,"_ditheringEnabled",void 0),e([a()],nn.prototype,"_ditheringIntensity",void 0),e([a()],nn.prototype,"_skipFinalColorClamp",void 0),e([a()],nn.prototype,"_applyByPostProcess",void 0),e([a()],nn.prototype,"_isEnabled",void 0),se._ImageProcessingConfigurationParser=nn.Parse,C("BABYLON.ImageProcessingConfiguration",nn);class rn{constructor(e,t,i,s,n,r){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=n,this.additionalData=r}static CreateNew(e,t,i){const s=e.getScene();return new rn(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new rn(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new rn(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new rn(e,t.x,t.y,null,i,s)}}class an{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[li.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[li.PositionKind]=new li(this._scene.getEngine(),e,li.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)}_rebuild(){const e=this._vertexBuffers[li.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!!i&&(!(!(t=t||i._postProcesses.filter((e=>null!=e)))||0===t.length||!this._scene.postProcessesEnabled)&&(t[0].activate(i,e,null!=t),!0))}directRender(e,t=null,i=!1,s=0,n=0,r=!1){const a=this._scene.getEngine();for(let o=0;o<e.length;o++){o<e.length-1?e[o+1].activate(this._scene.activeCamera,t?.texture):(t?a.bindFramebuffer(t,s,void 0,void 0,i,n):r||a.restoreDefaultFramebuffer(),a._debugInsertMarker?.(`post process ${e[o].name} output`));const l=e[o],h=l.apply();h&&(l.onBeforeRenderObservable.notifyObservers(h),this._prepareBuffers(),a.bindBuffers(this._vertexBuffers,this._indexBuffer,h),a.drawElementsType(tt.MATERIAL_TriangleFillMode,0,6),l.onAfterRenderObservable.notifyObservers(h))}a.setDepthBuffer(!0),a.setDepthWrite(!0)}_finalizeFrame(e,t,i,s,n=!1){const r=this._scene.activeCamera;if(!r)return;if(0===(s=s||r._postProcesses.filter((e=>null!=e))).length||!this._scene.postProcessesEnabled)return;const a=this._scene.getEngine();for(let o=0,l=s.length;o<l;o++){const h=s[o];if(o<l-1?h._outputTexture=s[o+1].activate(r,t?.texture):(t?(a.bindFramebuffer(t,i,void 0,void 0,n),h._outputTexture=t):(a.restoreDefaultFramebuffer(),h._outputTexture=null),a._debugInsertMarker?.(`post process ${s[o].name} output`)),e)break;const c=h.apply();c&&(h.onBeforeRenderObservable.notifyObservers(c),this._prepareBuffers(),a.bindBuffers(this._vertexBuffers,this._indexBuffer,c),a.drawElementsType(tt.MATERIAL_TriangleFillMode,0,6),h.onAfterRenderObservable.notifyObservers(c))}a.setDepthBuffer(!0),a.setDepthWrite(!0),a.setAlphaMode(tt.ALPHA_DISABLE)}dispose(){const e=this._vertexBuffers[li.PositionKind];e&&(e.dispose(),this._vertexBuffers[li.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)}}class on{set opaqueSortCompareFn(e){this._opaqueSortCompareFn=e||on.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){this._alphaTestSortCompareFn=e||on.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){this._transparentSortCompareFn=e||on.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,i=null,s=null,n=null){this.index=e,this._opaqueSubMeshes=new ei(256),this._transparentSubMeshes=new ei(256),this._alphaTestSubMeshes=new ei(256),this._depthOnlySubMeshes=new ei(256),this._particleSystems=new ei(256),this._spriteManagers=new ei(256),this._empty=!0,this._edgesRenderers=new ti(16),this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=s,this.transparentSortCompareFn=n}render(e,t,i,s){if(e)return void e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);const n=this._scene.getEngine();0!==this._depthOnlySubMeshes.length&&(n.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),n.setColorWrite(!0)),0!==this._opaqueSubMeshes.length&&this._renderOpaque(this._opaqueSubMeshes),0!==this._alphaTestSubMeshes.length&&this._renderAlphaTest(this._alphaTestSubMeshes);const r=n.getStencilBuffer();if(n.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(s),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),0!==this._transparentSubMeshes.length||this._scene.useOrderIndependentTransparency){if(n.setStencilBuffer(r),this._scene.useOrderIndependentTransparency){const e=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);e.length&&this._renderTransparent(e)}else this._renderTransparent(this._transparentSubMeshes);n.setAlphaMode(tt.ALPHA_DISABLE)}if(n.setStencilBuffer(!1),this._edgesRenderers.length){for(let e=0;e<this._edgesRenderers.length;e++)this._edgesRenderers.data[e].render();n.setAlphaMode(tt.ALPHA_DISABLE)}n.setStencilBuffer(r)}_renderOpaqueSorted(e){on._RenderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera,!1)}_renderAlphaTestSorted(e){on._RenderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera,!1)}_renderTransparentSorted(e){on._RenderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera,!0)}static _RenderSorted(e,t,i,s){let n,r=0;const a=i?i.globalPosition:on._ZeroVector;if(s)for(;r<e.length;r++)n=e.data[r],n._alphaIndex=n.getMesh().alphaIndex,n._distanceToCamera=B.Distance(n.getBoundingInfo().boundingSphere.centerWorld,a);const o=e.length===e.data.length?e.data:e.data.slice(0,e.length);t&&o.sort(t);const l=o[0].getMesh().getScene();for(r=0;r<o.length;r++)if(n=o[r],!l._activeMeshesFrozenButKeepClipping||n.isInFrustum(l._frustumPlanes)){if(s){const e=n.getMaterial();if(e&&e.needDepthPrePass){const t=e.getScene().getEngine();t.setColorWrite(!1),t.setAlphaMode(tt.ALPHA_DISABLE),n.render(!1),t.setColorWrite(!0)}}n.render(s)}}static defaultTransparentSortCompare(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:on.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 i=e.getMesh(),s=t.getMesh();return i.material&&s.material?i.material.uniqueId-s.material.uniqueId:i.uniqueId-s.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,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&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 i=0;i<this._particleSystems.length;i++){const s=this._particleSystems.data[i];if(0===(t&&t.layerMask&s.layerMask))continue;const n=s.emitter;n.position&&e&&-1===e.indexOf(n)||this._scene._activeParticles.addCount(s.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 i=this._spriteManagers.data[t];0!==(e&&e.layerMask&i.layerMask)&&i.render()}this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)}}on._ZeroVector=B.Zero();class ln{}class hn{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._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new ln,this._maintainStateBetweenFrames=!1,this._scene=e;for(let e=hn.MIN_RENDERINGGROUPS;e<hn.MAX_RENDERINGGROUPS;e++)this._autoClearDepthStencil[e]={autoClear:!0,depth:!0,stencil:!0}}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,i,s){const n=this._renderingGroupInfo;if(n.scene=this._scene,n.camera=this._scene.activeCamera,this._scene.spriteManagers&&s)for(let e=0;e<this._scene.spriteManagers.length;e++){const t=this._scene.spriteManagers[e];this.dispatchSprites(t)}for(let r=hn.MIN_RENDERINGGROUPS;r<hn.MAX_RENDERINGGROUPS;r++){this._depthStencilBufferAlreadyCleaned=r===hn.MIN_RENDERINGGROUPS;const a=this._renderingGroups[r];if(!a||a._empty)continue;const o=1<<r;if(n.renderingGroupId=r,this._scene.onBeforeRenderingGroupObservable.notifyObservers(n,o),hn.AUTOCLEAR){const e=this._useSceneAutoClearSetup?this._scene.getAutoClearDepthStencilSetup(r):this._autoClearDepthStencil[r];e&&e.autoClear&&this._clearDepthStencilBuffer(e.depth,e.stencil)}for(const e of this._scene._beforeRenderingGroupDrawStage)e.action(r);a.render(e,s,i,t);for(const e of this._scene._afterRenderingGroupDrawStage)e.action(r);this._scene.onAfterRenderingGroupObservable.notifyObservers(n,o)}}reset(){if(!this.maintainStateBetweenFrames)for(let e=hn.MIN_RENDERINGGROUPS;e<hn.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.prepare()}}resetSprites(){if(!this.maintainStateBetweenFrames)for(let e=hn.MIN_RENDERINGGROUPS;e<hn.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=hn.MIN_RENDERINGGROUPS;e<hn.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.dispose()}}_prepareRenderingGroup(e){void 0===this._renderingGroups[e]&&(this._renderingGroups[e]=new on(e,this._scene,this._customOpaqueSortCompareFn[e],this._customAlphaTestSortCompareFn[e],this._customTransparentSortCompareFn[e]))}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,i){void 0===t&&(t=e.getMesh()),this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(t.renderingGroupId).dispatch(e,t,i))}setRenderingOrder(e,t=null,i=null,s=null){if(this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=i,this._customTransparentSortCompareFn[e]=s,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,i=!0,s=!0){this._autoClearDepthStencil[e]={autoClear:t,depth:i,stencil:s}}getAutoClearDepthStencilSetup(e){return this._autoClearDepthStencil[e]}}hn.MAX_RENDERINGGROUPS=4,hn.MIN_RENDERINGGROUPS=0,hn.AUTOCLEAR=!0;class cn{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1,this.disposeWhenUnowned=!0}static get HasTriggers(){for(const e in cn.Triggers)if(Object.prototype.hasOwnProperty.call(cn.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in cn.Triggers)if(Object.prototype.hasOwnProperty.call(cn.Triggers,e)){const t=parseInt(e);if(t>=tt.ACTION_OnPickTrigger&&t<=tt.ACTION_OnPickUpTrigger)return!0}return!1}static HasSpecificTrigger(e){for(const t in cn.Triggers)if(Object.prototype.hasOwnProperty.call(cn.Triggers,t)){if(parseInt(t)===e)return!0}return!1}}var un,dn,_n,fn,mn,pn,gn;cn.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"}(un||(un={})),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"}(dn||(dn={})),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"}(_n||(_n={})),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"}(fn||(fn={})),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"}(mn||(mn={})),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"}(pn||(pn={})),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"}(gn||(gn={}));class En{static CreateDeviceEvent(e,t,i,s,n,r,a){switch(e){case un.Keyboard:return this._CreateKeyboardEvent(i,s,n,r);case un.Mouse:if(i===dn.MouseWheelX||i===dn.MouseWheelY||i===dn.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,n,r);case un.Touch:return this._CreatePointerEvent(e,t,i,s,n,r,a);default:throw`Unable to generate event for device ${un[e]}`}}static _CreatePointerEvent(e,t,i,s,n,r,a){const o=this._CreateMouseEvent(e,t,i,s,n,r);e===un.Mouse?(o.deviceType=un.Mouse,o.pointerId=1,o.pointerType="mouse"):(o.deviceType=un.Touch,o.pointerId=a??t,o.pointerType="touch");let l=0;return l+=n.pollInput(e,t,dn.LeftClick),l+=2*n.pollInput(e,t,dn.RightClick),l+=4*n.pollInput(e,t,dn.MiddleClick),o.buttons=l,i===dn.Move?o.type="pointermove":i>=dn.LeftClick&&i<=dn.RightClick&&(o.type=1===s?"pointerdown":"pointerup",o.button=i-2),o}static _CreateWheelEvent(e,t,i,s,n,r){const a=this._CreateMouseEvent(e,t,i,s,n,r);switch(a.pointerId=1,a.type="wheel",a.deltaMode=Ks.DOM_DELTA_PIXEL,a.deltaX=0,a.deltaY=0,a.deltaZ=0,i){case dn.MouseWheelX:a.deltaX=s;break;case dn.MouseWheelY:a.deltaY=s;break;case dn.MouseWheelZ:a.deltaZ=s}return a}static _CreateMouseEvent(e,t,i,s,n,r){const a=this._CreateEvent(r),o=n.pollInput(e,t,dn.Horizontal),l=n.pollInput(e,t,dn.Vertical);return r?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-r.getBoundingClientRect().x,a.offsetY=a.movementY-r.getBoundingClientRect().y):(a.movementX=n.pollInput(e,t,10),a.movementY=n.pollInput(e,t,11),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,n),a.clientX=o,a.clientY=l,a.x=o,a.y=l,a.deviceType=e,a.deviceSlot=t,a.inputIndex=i,a}static _CreateKeyboardEvent(e,t,i,s){const n=this._CreateEvent(s);return this._CheckNonCharacterKeys(n,i),n.deviceType=un.Keyboard,n.deviceSlot=0,n.inputIndex=e,n.type=1===t?"keydown":"keyup",n.key=String.fromCharCode(e),n.keyCode=e,n}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(un.Keyboard),s=i&&1===t.pollInput(un.Keyboard,0,tt.INPUT_ALT_KEY),n=i&&1===t.pollInput(un.Keyboard,0,tt.INPUT_CTRL_KEY),r=i&&(1===t.pollInput(un.Keyboard,0,tt.INPUT_META_KEY1)||1===t.pollInput(un.Keyboard,0,tt.INPUT_META_KEY2)||1===t.pollInput(un.Keyboard,0,tt.INPUT_META_KEY3)),a=i&&1===t.pollInput(un.Keyboard,0,tt.INPUT_SHIFT_KEY);e.altKey=s,e.ctrlKey=n,e.metaKey=r,e.shiftKey=a}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class Tn{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,s,n)=>{const r=En.CreateDeviceEvent(e,t,s,n,this);i(e,t,r)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===un.Mouse||e===un.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const An=Object.keys(dn).length/2;class Rn{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Qt.IsSafari(),this._usingMacOS=oe()&&/(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._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._pointerMacOSChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=oe()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=oe()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=Qt.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=s,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const s=this._inputs[e][t];if(!s)throw`Unable to find device ${un[e]}`;e>=un.DualShock&&e<=un.DualSense&&this._updateDevice(e,t,i);const n=s[i];if(void 0===n)throw`Unable to find input ${i} for device ${un[e]} in slot ${t}`;return i===dn.Move&&Qt.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),n}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 i=e[+t];if(i)for(let e=0;e<i.length;e++)i[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._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(un.Mouse,0,0,0)}_addGamePad(e){const t=this._getGamepadDeviceType(e.id),i=e.index;this._gamepads=this._gamepads||new Array(e.index+1),this._registerDevice(t,i,e.buttons.length+e.axes.length),this._gamepads[i]=t}_addPointerDevice(e,t,i,s){this._pointerActive||(this._pointerActive=!0),this._registerDevice(e,t,An);const n=this._inputs[e][t];n[0]=i,n[1]=s}_registerDevice(e,t,i){if(void 0===t)throw`Unable to register device ${un[e]} to undefined slot.`;if(this._inputs[e]||(this._inputs[e]={}),!this._inputs[e][t]){const s=new Array(i);s.fill(0),this._inputs[e][t]=s,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(un.Keyboard,0,255));const t=this._inputs[un.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(un.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(un.Keyboard,0,255));const t=this._inputs[un.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const i=En.CreateDeviceEvent(un.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(un.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(un.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[un.Keyboard][0];for(let t=0;t<e.length;t++)if(0!==e[t]){e[t]=0;const i=En.CreateDeviceEvent(un.Keyboard,0,t,0,this,this._elementToAttachTo);this._onInputChanged(un.Keyboard,0,i)}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=oe()&&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 i=t===un.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===un.Touch&&-1===i){const s=this._activeTouchIds.indexOf(-1);if(!(s>=0))return void Qt.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=s,this._activeTouchIds[s]=e.pointerId,this._onDeviceConnected(t,i)}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const n=e;n.inputIndex=dn.Move,s[dn.Horizontal]=e.clientX,s[dn.Vertical]=e.clientY,t===un.Touch&&0===s[dn.LeftClick]&&(s[dn.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,n),this._usingSafari||-1===e.button||(n.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,n))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===un.Mouse?0:e.pointerId;if(t===un.Touch){let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t&&(t=this._activeTouchIds.indexOf(-1)),!(t>=0))return void Qt.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=t,this._activeTouchIds[t]=e.pointerId}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===un.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const n=s[dn.Horizontal],r=s[dn.Vertical];if(t===un.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){}s[dn.Horizontal]=e.clientX,s[dn.Vertical]=e.clientY,s[e.button+2]=1;const a=e;a.inputIndex=e.button+2,this._onInputChanged(t,i,a),n===e.clientX&&r===e.clientY||(a.inputIndex=dn.Move,this._onInputChanged(t,i,a))}},this._pointerUpEvent=e=>{const t=this._getPointerType(e),i=t===un.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===un.Touch){if(-1===i)return;this._activeTouchIds[i]=-1}const s=this._inputs[t]?.[i];if(s&&0!==s[e.button+2]){const n=s[dn.Horizontal],r=s[dn.Vertical];s[dn.Horizontal]=e.clientX,s[dn.Vertical]=e.clientY,s[e.button+2]=0;const a=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),n===e.clientX&&r===e.clientY||(a.inputIndex=dn.Move,this._onInputChanged(t,i,a)),a.inputIndex=e.button+2,t===un.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,i,a),t===un.Touch&&this._onDeviceDisconnected(t,i)}},this._pointerCancelEvent=e=>{if("mouse"===e.pointerType){const e=this._inputs[un.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=dn.LeftClick;t<=dn.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=En.CreateDeviceEvent(un.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(un.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[un.Touch][t][dn.LeftClick]=0;const i=En.CreateDeviceEvent(un.Touch,t,dn.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(un.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(un.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1;const t=function(){};try{const i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch(e){}this._pointerBlurEvent=()=>{if(this.isDeviceAvailable(un.Mouse)){const e=this._inputs[un.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=dn.LeftClick;t<=dn.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=En.CreateDeviceEvent(un.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(un.Mouse,0,i)}}if(this.isDeviceAvailable(un.Touch)){const e=this._inputs[un.Touch];for(let t=0;t<this._activeTouchIds.length;t++){const i=this._activeTouchIds[t];if(this._elementToAttachTo.hasPointerCapture?.(i)&&this._elementToAttachTo.releasePointerCapture(i),-1!==i&&1===e[t]?.[dn.LeftClick]){e[t][dn.LeftClick]=0;const s=En.CreateDeviceEvent(un.Touch,t,dn.LeftClick,0,this,this._elementToAttachTo,i);this._onInputChanged(un.Touch,t,s),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(un.Touch,t)}}}},this._pointerWheelEvent=e=>{const t=un.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,An));const i=this._inputs[t][0];if(i){i[dn.MouseWheelX]=e.deltaX||0,i[dn.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[dn.MouseWheelZ]=e.deltaZ||0;const s=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[dn.MouseWheelX]&&(s.inputIndex=dn.MouseWheelX,this._onInputChanged(t,0,s)),0!==i[dn.MouseWheelY]&&(s.inputIndex=dn.MouseWheelY,this._onInputChanged(t,0,s)),0!==i[dn.MouseWheelZ]&&(s.inputIndex=dn.MouseWheelZ,this._onInputChanged(t,0,s))}},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("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,!!e&&{passive:!1}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add((()=>{if(this.isDeviceAvailable(un.Mouse)){const e=this._inputs[un.Mouse][0];e[dn.MouseWheelX]=0,e[dn.MouseWheelY]=0,e[dn.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const s=navigator.getGamepads()[t];if(s&&e===this._gamepads[t]){const n=this._inputs[e][t];i>=s.buttons.length?n[i]=s.axes[i-s.buttons.length].valueOf():n[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?un.DualSense:un.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?un.Xbox:-1!==e.indexOf("057e")?un.Switch:un.Generic}_getPointerType(e){let t=un.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=un.Touch),t}}class vn{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new g,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class In{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t<this._devices.length;t++){const i=this._devices[t];for(const s in i){const i=+s;e._addDevice(new vn(this._deviceInputSystem,t,i))}}this._registeredManagers.push(e)},this.unregisterManager=e=>{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(un).length/2;this._devices=new Array(t);const i=(e,t)=>{this._devices[e]||(this._devices[e]=new Array),this._devices[e][t]||(this._devices[e][t]=t);for(const i of this._registeredManagers){const s=new vn(this._deviceInputSystem,e,t);i._addDevice(s)}},s=(e,t)=>{this._devices[e]?.[t]&&delete this._devices[e][t];for(const i of this._registeredManagers)i._removeDevice(e,t)},n=(e,t,i)=>{if(i)for(const s of this._registeredManagers)s._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new Tn(i,s,n):this._deviceInputSystem=new Rn(e,i,s,n)}dispose(){this._deviceInputSystem.dispose()}}class Sn{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(un).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new In(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new g((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new g,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]=new Array),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 i=this._devices[e]?.[t];this.onDeviceDisconnectedObservable.notifyObservers(i),this._devices[e]?.[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){this._devices[e]?.[t]?.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case un.Keyboard:case un.Mouse:this._firstDevice[e]=0;break;case un.Touch:case un.DualSense:case un.DualShock:case un.Xbox:case un.Switch:case un.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i<t.length;i++)if(t[i]){this._firstDevice[e]=i;break}break}}}}class Cn{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 bn{constructor(e){this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._totalPointersPressed=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 w(0,0),this._previousStartingPointerPosition=new w(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||M.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 w(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 i=this._scene,s=i.getEngine(),n=s.getInputElement();n&&(n.tabIndex=s.canvasTabIndex,i.doNotHandleCursors||(n.style.cursor=i.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,i);for(const s of i._pointerMoveStage){e=e||this._pickMove(t);const i=!!e?.pickedMesh;e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,i,n)}const r=t.inputIndex>=dn.MouseWheelX&&t.inputIndex<=dn.MouseWheelZ?Es.POINTERWHEEL:Es.POINTERMOVE;let a;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,r)),e?(a=new Rs(r,t,e),this._setRayOnPointerInfo(e,t)):(a=new Rs(r,t,null,this),this._movePointerInfo=a),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(a,r)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,G.Identity(),i.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,i){const s=this._scene,n=new As(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(n.originalPickingInfo=e,n.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(n.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(n,i),!!n.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const s=i.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(s.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=dn.Move,this._checkPrePointerObservable(e,i,Es.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,Es.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const s=e.pickedMesh._getActionManagerForTrigger();if(s){if(s.hasPickTriggers)switch(s.processTrigger(tt.ACTION_OnPickDownTrigger,rn.CreateNew(e.pickedMesh,t,e)),t.button){case 0:s.processTrigger(tt.ACTION_OnLeftPickTrigger,rn.CreateNew(e.pickedMesh,t,e));break;case 1:s.processTrigger(tt.ACTION_OnCenterPickTrigger,rn.CreateNew(e.pickedMesh,t,e));break;case 2:s.processTrigger(tt.ACTION_OnRightPickTrigger,rn.CreateNew(e.pickedMesh,t,e))}s.hasSpecificTrigger(tt.ACTION_OnLongPressTrigger)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(tt.ACTION_OnLongPressTrigger)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);e?.pickedMesh&&s&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>bn.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,s.processTrigger(tt.ACTION_OnLongPressTrigger,rn.CreateNew(e.pickedMesh,t)))}),bn.LongPressDelay)}}else for(const s of i._pointerDownStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const n=Es.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,n),s=new Rs(n,t,e),this._setRayOnPointerInfo(e,t)):s=new Rs(n,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,n)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=dn.Move;const n=new Cn;i?n.doubleClick=!0:n.singleClick=!0,this._checkPrePointerObservable(e,s,Es.POINTERUP)||this._processPointerUp(e,s,n)}_processPointerUp(e,t,i){const s=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const i=Es.POINTERPICK,n=new Rs(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(n,i)}const n=e.pickedMesh._getActionManagerForTrigger();if(n&&!i.ignore){n.processTrigger(tt.ACTION_OnPickUpTrigger,rn.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&n.processTrigger(tt.ACTION_OnPickTrigger,rn.CreateNew(e.pickedMesh,t,e));const s=e.pickedMesh._getActionManagerForTrigger(tt.ACTION_OnDoublePickTrigger);i.doubleClick&&s&&s.processTrigger(tt.ACTION_OnDoublePickTrigger,rn.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const n of s._pointerUpStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(tt.ACTION_OnPickOutTrigger);e&&e.processTrigger(tt.ACTION_OnPickOutTrigger,rn.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const n=new Rs(Es.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(n,Es.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,Es.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let n=0;if(i.singleClick?n=Es.POINTERTAP:i.doubleClick&&(n=Es.POINTERDOUBLETAP),n){const i=new Rs(n,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(n)&&s.onPointerObservable.notifyObservers(i,n)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const n=this._scene,r=n.getEngine();s||(s=r.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new Sn(r),this._initActionManager=e=>{if(!this._meshPickProceed){const t=n.skipPointerUpPicking||0===n._registeredActions&&!this._checkForPicking()&&!n.onPointerUp?null:n.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,n.pointerUpPredicate,n.pointerUpFastCheck,n.cameraToUseForPointers,n.pointerUpTrianglePredicate);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>bn.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){const t=this._delayedClicks[e].evt,i=Es.POINTERTAP,s=new Rs(i,t,this._currentPickResult);n.onPointerObservable.hasObservers()&&n.onPointerObservable.hasSpecificMask(i)&&n.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,s)=>{const n=new Cn;this._currentPickResult=null;let r=null,a=e.hasSpecificMask(Es.POINTERPICK)||t.hasSpecificMask(Es.POINTERPICK)||e.hasSpecificMask(Es.POINTERTAP)||t.hasSpecificMask(Es.POINTERTAP)||e.hasSpecificMask(Es.POINTERDOUBLETAP)||t.hasSpecificMask(Es.POINTERDOUBLETAP);!a&&cn&&(r=this._initActionManager(r,n),r&&(a=r.hasPickTriggers));let o=!1;if(a){const a=i.button;if(n.hasSwiped=this._isPointerSwiping(),!n.hasSwiped){let l=!bn.ExclusiveDoubleClickMode;if(l||(l=!e.hasSpecificMask(Es.POINTERDOUBLETAP)&&!t.hasSpecificMask(Es.POINTERDOUBLETAP),l&&!cn.HasSpecificTrigger(tt.ACTION_OnDoublePickTrigger)&&(r=this._initActionManager(r,n),r&&(l=!r.hasSpecificTrigger(tt.ACTION_OnDoublePickTrigger)))),l)(Date.now()-this._previousStartingPointerTime>bn.DoubleClickDelay||a!==this._previousButtonPressed)&&(n.singleClick=!0,s(n,this._currentPickResult),o=!0);else{const e={evt:i,clickInfo:n,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,a,n,s),bn.DoubleClickDelay)};this._delayedClicks[a]=e}let h=e.hasSpecificMask(Es.POINTERDOUBLETAP)||t.hasSpecificMask(Es.POINTERDOUBLETAP);!h&&cn.HasSpecificTrigger(tt.ACTION_OnDoublePickTrigger)&&(r=this._initActionManager(r,n),r&&(h=r.hasSpecificTrigger(tt.ACTION_OnDoublePickTrigger))),h&&(a===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime<bn.DoubleClickDelay&&!this._doubleClickOccured?(n.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,bn.ExclusiveDoubleClickMode?(this._delayedClicks[a]&&(clearTimeout(this._delayedClicks[a]?.timeoutId),this._delayedClicks[a]=null),s(n,this._previousPickResult)):s(n,this._currentPickResult)):(this._previousStartingPointerTime=0,this._doubleClickOccured=!0,n.doubleClick=!0,n.ignore=!1,bn.ExclusiveDoubleClickMode&&this._delayedClicks[a]&&(clearTimeout(this._delayedClicks[a]?.timeoutId),this._delayedClicks[a]=null),s(n,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||s(n,this._currentPickResult)},this._onPointerMove=e=>{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>bn.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>bn.DragMovementThreshold),r.isPointerLock&&r._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=dn.MouseWheelX&&e.inputIndex<=dn.MouseWheelZ?Es.POINTERWHEEL:Es.POINTERMOVE))return;if(!n.cameraToUseForPointers&&!n.activeCamera)return;if(n.skipPointerMovePicking)return void this._processPointerMove(new zi,e);n.pointerMovePredicate||(n.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||n.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!n.cameraToUseForPointers||!!(n.cameraToUseForPointers.layerMask&e.layerMask)));const t=n._registeredActions>0||n.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,bn.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 i=this._delayedClicks[t].evt,s=Es.POINTERTAP,r=new Rs(s,i,this._currentPickResult);n.onPointerObservable.hasObservers()&&n.onPointerObservable.hasSpecificMask(s)&&n.onPointerObservable.notifyObservers(r,s),this._delayedClicks[t]=null}if(this._updatePointerPosition(e),-1===this._swipeButtonPressed&&(this._swipeButtonPressed=e.button),n.preventDefaultOnPointerDown&&s&&(e.preventDefault(),s.focus()),this._startingPointerPosition.x=this._pointerX,this._startingPointerPosition.y=this._pointerY,this._startingPointerTime=Date.now(),this._checkPrePointerObservable(null,e,Es.POINTERDOWN))return;if(!n.cameraToUseForPointers&&!n.activeCamera)return;let t;this._pointerCaptures[e.pointerId]=!0,n.pointerDownPredicate||(n.pointerDownPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!n.cameraToUseForPointers||!!(n.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,t=n.skipPointerDownPicking||0===n._registeredActions&&!this._checkForPicking()&&!n.onPointerDown?new zi:n.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,n.pointerDownPredicate,n.pointerDownFastCheck,n.cameraToUseForPointers,n.pointerDownTrianglePredicate),this._processPointerDown(t,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),n.preventDefaultOnPointerUp&&s&&(e.preventDefault(),s.focus()),this._initClickEvent(n.onPrePointerObservable,n.onPointerObservable,e,((t,i)=>{if(n.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,Es.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&&n.onPrePointerObservable.hasSpecificMask(Es.POINTERTAP)&&this._checkPrePointerObservable(null,e,Es.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&n.onPrePointerObservable.hasSpecificMask(Es.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,Es.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(n.cameraToUseForPointers||n.activeCamera)&&(n.pointerUpPredicate||(n.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!n.cameraToUseForPointers||!!(n.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(cn&&cn.HasTriggers||this._checkForPicking()||n.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,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=Hs.KEYDOWN;if(n.onPreKeyboardObservable.hasObservers()){const i=new Ws(t,e);if(n.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(n.onKeyboardObservable.hasObservers()){const i=new zs(t,e);n.onKeyboardObservable.notifyObservers(i,t)}n.actionManager&&n.actionManager.processTrigger(tt.ACTION_OnKeyDownTrigger,rn.CreateNewFromScene(n,e))},this._onKeyUp=e=>{const t=Hs.KEYUP;if(n.onPreKeyboardObservable.hasObservers()){const i=new Ws(t,e);if(n.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(n.onKeyboardObservable.hasObservers()){const i=new zs(t,e);n.onKeyboardObservable.notifyObservers(i,t)}n.actionManager&&n.actionManager.processTrigger(tt.ACTION_OnKeyUpTrigger,rn.CreateNewFromScene(n,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((s=>{s.deviceType===un.Mouse?s.onInputChangedObservable.add((n=>{this._originMouseEvent=n,n.inputIndex===dn.LeftClick||n.inputIndex===dn.MiddleClick||n.inputIndex===dn.RightClick||n.inputIndex===dn.BrowserBack||n.inputIndex===dn.BrowserForward?t&&1===s.getInput(n.inputIndex)?this._onPointerDown(n):e&&0===s.getInput(n.inputIndex)&&this._onPointerUp(n):i&&(n.inputIndex===dn.Move?this._onPointerMove(n):n.inputIndex!==dn.MouseWheelX&&n.inputIndex!==dn.MouseWheelY&&n.inputIndex!==dn.MouseWheelZ||this._onPointerMove(n))})):s.deviceType===un.Touch?s.onInputChangedObservable.add((n=>{n.inputIndex===dn.LeftClick&&(t&&1===s.getInput(n.inputIndex)?(this._onPointerDown(n),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===s.getInput(n.inputIndex)&&(this._onPointerUp(n),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&n.inputIndex===dn.Move&&this._onPointerMove(n)})):s.deviceType===un.Keyboard&&s.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,i,s){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const n=this._meshUnderPointerId[t];let r;n&&(r=n._getActionManagerForTrigger(tt.ACTION_OnPointerOutTrigger),r&&r.processTrigger(tt.ACTION_OnPointerOutTrigger,rn.CreateNew(n,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,r=e._getActionManagerForTrigger(tt.ACTION_OnPointerOverTrigger),r&&r.processTrigger(tt.ACTION_OnPointerOverTrigger,rn.CreateNew(e,s,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}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]}}bn.DragMovementThreshold=10,bn.LongPressDelay=500,bn.DoubleClickDelay=300,bn.ExclusiveDoubleClickMode=!1;class yn{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}yn._UniqueIdCounter=1;class Mn{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var xn,On;!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(xn||(xn={}));class Dn extends en{static DefaultMaterialFactory(e){throw W("StandardMaterial")}static CollisionCoordinatorFactory(){throw W("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}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(tt.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(tt.MATERIAL_MiscDirtyFlag))}get forcePointsCloud(){return this._forcePointsCloud}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 bn.DragMovementThreshold}static set DragMovementThreshold(e){bn.DragMovementThreshold=e}static get LongPressDelay(){return bn.LongPressDelay}static set LongPressDelay(e){bn.LongPressDelay=e}static get DoubleClickDelay(){return bn.DoubleClickDelay}static set DoubleClickDelay(e){bn.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return bn.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){bn.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,n=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return X.Vector4[0].set(s.x,s.y,s.z,n?-1:1),e&&(i?e.setFloat3(t,X.Vector4[0].x,X.Vector4[0].y,X.Vector4[0].z):e.setVector4(t,X.Vector4[0])),X.Vector4[0]}finalizeSceneUbo(){const e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(tt.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(tt.MATERIAL_MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(tt.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(tt.MATERIAL_LightDirtyFlag))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(tt.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=I(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 defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=Dn.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(tt.MATERIAL_AttributesDirtyFlag))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=Dn.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}constructor(e,t){super(),this._inputManager=new bn(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new ee(.2,.2,.3,1),this.ambientColor=new J(0,0,0),this.environmentIntensity=1,this._performancePriority=0,this.onScenePerformancePriorityChangedObservable=new g,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,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 g,this._onDisposeObserver=null,this.onBeforeRenderObservable=new g,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new g,this.onAfterRenderCameraObservable=new g,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new g,this.onAfterAnimationsObservable=new g,this.onBeforeDrawPhaseObservable=new g,this.onAfterDrawPhaseObservable=new g,this.onReadyObservable=new g,this.onBeforeCameraRenderObservable=new g,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new g,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new g,this.onAfterActiveMeshesEvaluationObservable=new g,this.onBeforeParticlesRenderingObservable=new g,this.onAfterParticlesRenderingObservable=new g,this.onDataLoadedObservable=new g,this.onNewCameraAddedObservable=new g,this.onCameraRemovedObservable=new g,this.onNewLightAddedObservable=new g,this.onLightRemovedObservable=new g,this.onNewGeometryAddedObservable=new g,this.onGeometryRemovedObservable=new g,this.onNewTransformNodeAddedObservable=new g,this.onTransformNodeRemovedObservable=new g,this.onNewMeshAddedObservable=new g,this.onMeshRemovedObservable=new g,this.onNewSkeletonAddedObservable=new g,this.onSkeletonRemovedObservable=new g,this.onNewMaterialAddedObservable=new g,this.onNewMultiMaterialAddedObservable=new g,this.onMaterialRemovedObservable=new g,this.onMultiMaterialRemovedObservable=new g,this.onNewTextureAddedObservable=new g,this.onTextureRemovedObservable=new g,this.onBeforeRenderTargetsRenderObservable=new g,this.onAfterRenderTargetsRenderObservable=new g,this.onBeforeStepObservable=new g,this.onAfterStepObservable=new g,this.onActiveCameraChanged=new g,this.onActiveCamerasChanged=new g,this.onBeforeRenderingGroupObservable=new g,this.onAfterRenderingGroupObservable=new g,this.onMeshImportedObservable=new g,this.onAnimationFileImportedObservable=new g,this._registeredForLateAnimationBindings=new ti(256),this._pointerPickingConfiguration=new Mn,this.onPrePointerObservable=new g,this.onPointerObservable=new g,this.onPreKeyboardObservable=new g,this.onKeyboardObservable=new g,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Dn.FOGMODE_NONE,this.fogColor=new J(.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.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new B(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new ti(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new wi,this._activeIndices=new wi,this._activeParticles=new wi,this._activeBones=new wi,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._pendingData=new Array,this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new ei(256),this._processedMaterials=new ei(256),this._renderTargets=new ti(256),this._materialsRenderTargets=new ti(256),this._activeParticleSystems=new ei(256),this._activeSkeletons=new ti(32),this._softwareSkinnedMeshes=new ti(32),this._activeAnimatables=new Array,this._transformMatrix=G.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=us.Create(),this._beforeClearStage=us.Create(),this._beforeRenderTargetClearStage=us.Create(),this._gatherRenderTargetsStage=us.Create(),this._gatherActiveCameraRenderTargetsStage=us.Create(),this._isReadyForMeshStage=us.Create(),this._beforeEvaluateActiveMeshStage=us.Create(),this._evaluateSubMeshStage=us.Create(),this._preActiveMeshStage=us.Create(),this._cameraDrawRenderTargetStage=us.Create(),this._beforeCameraDrawStage=us.Create(),this._beforeRenderTargetDrawStage=us.Create(),this._beforeRenderingGroupDrawStage=us.Create(),this._beforeRenderingMeshStage=us.Create(),this._afterRenderingMeshStage=us.Create(),this._afterRenderingGroupDrawStage=us.Create(),this._afterCameraDrawStage=us.Create(),this._afterCameraPostProcessStage=us.Create(),this._afterRenderTargetDrawStage=us.Create(),this._afterRenderTargetPostProcessStage=us.Create(),this._afterRenderStage=us.Create(),this._pointerMoveStage=us.Create(),this._pointerDownStage=us.Create(),this._pointerUpStage=us.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};e=this._engine=e||M.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(M._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new hn(this),an&&(this.postProcessManager=new an(this)),ae()&&this.attachControl(),this._createUbo(),nn&&(this._imageProcessingConfiguration=new nn),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.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,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}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,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){if(this._isDisposed)return!1;let t;const i=this.getEngine(),s=i.currentRenderPassId;i.currentRenderPassId=this.activeCamera?.renderPassId??s;let n=!0;for(this._pendingData.length>0&&(n=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&(n&&=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t<this.meshes.length;t++){const s=this.meshes[t];if(!s.subMeshes||0===s.subMeshes.length)continue;if(!s.isReady(!0)){n=!1;continue}const r=s.hasThinInstances||"InstancedMesh"===s.getClassName()||"InstancedLinesMesh"===s.getClassName()||i.getCaps().instancedArrays&&s.instances.length>0;for(const e of this._isReadyForMeshStage)e.action(s,r)||(n=!1);if(!e)continue;const a=s.material||this.defaultMaterial;if(a)if(a._storeEffectOnSubMeshes)for(const e of s.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()||(n=!1)}for(t=0;t<this.geometries.length;t++){this.geometries[t].delayLoadState===tt.DELAYLOADSTATE_LOADING&&(n=!1)}if(this.activeCameras&&this.activeCameras.length>0)for(const e of this.activeCameras)e.isReady(!0)||(n=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(n=!1));for(const e of this.particleSystems)e.isReady()||(n=!1);if(this.layers)for(const e of this.layers)e.isReady()||(n=!1);return i.areAllEffectsReady()||(n=!1),i.currentRenderPassId=s,n}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,i=this._pendingData.indexOf(e);-1!==i&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise((t=>{this.executeWhenReady((()=>{t()}),e)}))}_checkIsReady(e=!1){return this._registerTransientComponents(),this.isReady(e)?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):void(this._executeWhenReadyTimeoutId=setTimeout((()=>{this.incrementRenderId(),this._checkIsReady(e)}),100))}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=_e.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,s){i||s||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?ni.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=ni.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,s):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new Wi(this._engine,void 0,!1,e??"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return yn.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.addMesh(e)})))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return-1!==i&&(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.removeMesh(e)})),i}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()}return this.onLightRemovedObservable.notifyObservers(e),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)),t}removeAnimation(e){const t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),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}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());this.onNewLightAddedObservable.notifyObservers(e)}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort($i.CompareLightsPriority)}addCamera(e){this._blockEntityCollection||(this.cameras.push(e),this.onNewCameraAddedObservable.notifyObservers(e),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),this.onNewSkeletonAddedObservable.notifyObservers(e))}addParticleSystem(e){this._blockEntityCollection||this.particleSystems.push(e)}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||this.animationGroups.push(e)}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),this.onNewMultiMaterialAddedObservable.notifyObservers(e))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneMaterialArray||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),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))}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 i=this.materials[e];if(t(i))return i}if(e)for(let e=0;e<this.multiMaterials.length;e++){const i=this.multiMaterials[e];if(t(i))return i}return null}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 i=this.skeletons[t];for(let t=0;t<i.bones.length;t++)if(i.bones[t].id===e)return i.bones[t]}return null}getBoneByName(e){for(let t=0;t<this.skeletons.length;t++){const i=this.skeletons[t];for(let t=0;t<i.bones.length;t++)if(i.bones[t].name===e)return i.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}pushGeometry(e,t){return!(!t&&this._getGeometryByUniqueId(e.uniqueId))&&(this.addGeometry(e),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];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const n=this.getCameraById(e);if(n)return n;const r=this.getBoneById(e);return r||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const s=this.getLightByName(e);if(s)return s;const n=this.getCameraByName(e);if(n)return n;const r=this.getBoneByName(e);return r||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 i=this.morphTargetManagers[t];for(let t=0;t<i.numTargets;++t){const s=i.getTarget(t);if(s.id===e)return s}}return null}getMorphTargetByName(e){for(let t=0;t<this.morphTargetManagers.length;++t){const i=this.morphTargetManagers[t];for(let t=0;t<i.numTargets;++t){const s=i.getTarget(t);if(s.name===e)return s}}return null}getPostProcessByName(e){for(let t=0;t<this.postProcesses.length;++t){const i=this.postProcesses[t];if(i.name===e)return i}return null}isActiveMesh(e){return-1!==this._activeMeshes.indexOf(e)}get uid(){return this._uid||(this._uid=Qt.RandomId()),this._uid}addExternalData(e,t){return this._externalData||(this._externalData=new Js),this._externalData.add(e,t)}getExternalData(e){return this._externalData?this._externalData.get(e):null}getOrAddExternalDataWithFactory(e,t){return this._externalData||(this._externalData=new Js),this._externalData.getOrAddWithFactory(e,t)}removeExternalData(e){return this._externalData.remove(e)}_evaluateSubMesh(e,t,i,s){if(s||e.isInFrustum(this._frustumPlanes)){for(const i of this._evaluateSubMeshStage)i.action(t,e);const i=e.getMaterial();null!=i&&(i.hasRenderTargetTextures&&null!=i.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(i)&&(this._processedMaterials.push(i),this._materialsRenderTargets.concatWithNoDuplicate(i.getRenderTargetTextures())),this._renderingManager.dispatch(e,t,i))}}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,i,s=!0,n=!1){return this.executeWhenReady((()=>{if(this.activeCamera){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=n,this._skipEvaluateActiveMeshesCompletely=e,s)for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._freeze();t&&t()}else i&&i("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)}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!==tt.SNAPSHOTRENDERING_FAST)&&this._activeMeshesFrozen&&this._activeMeshes.length||this.onBeforeRenderObservable.addOnce((()=>e.dispose()))}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===tt.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 i=0;i<t;i++){const t=e.data[i];if(t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!1,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(tt.ACTION_OnIntersectionEnterTrigger,tt.ACTION_OnIntersectionExitTrigger)&&this._meshesForIntersections.pushNoDuplicate(t);let s=this.customLODSelector?this.customLODSelector(t,this.activeCamera):t.getLOD(this.activeCamera);if(t._internalAbstractMeshDataInfo._currentLOD=s,t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0,null!=s&&(s!==t&&0!==s.billboardMode&&s.computeWorldMatrix(),t._preActivate(),t.isVisible&&t.visibility>0&&t.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||t.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(t),this.activeCamera._activeMeshes.push(t),s!==t&&s._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(t);t._activate(this._renderId,!1)&&(t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(s=t):s._internalAbstractMeshDataInfo._onlyForInstances=!1,s._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(t,s)),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 i=t.emitter;i.position&&!i.isEnabled()||(this._activeParticleSystems.push(t),t.animate(),this._renderingManager.dispatchParticles(t))}this.onAfterParticlesRenderingObservable.notifyObservers(this)}}_activeMesh(e,t){this._skeletonsEnabled&&null!==t.skeleton&&void 0!==t.skeleton&&(this._activeSkeletons.pushNoDuplicate(t.skeleton)&&(t.skeleton.prepare(),this._activeBones.addCount(t.skeleton.bones.length,!1)),t.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(t));let i=e.hasInstances||e.isAnInstance||this.dispatchAllSubMeshesOfActiveMeshes||this._skipFrustumClipping||t.alwaysSelectAsActiveMesh;if(t&&t.subMeshes&&t.subMeshes.length>0){const s=this.getActiveSubMeshCandidates(t),n=s.length;i=i||1===n;for(let r=0;r<n;r++){const n=s.data[r];this._evaluateSubMesh(n,t,e,i)}}}updateTransformMatrix(e){const t=this.activeCamera;if(t)if(t._renderingMultiview){const i=t._rigCameras[0],s=t._rigCameras[1];this.setTransformMatrix(i.getViewMatrix(),i.getProjectionMatrix(e),s.getViewMatrix(),s.getProjectionMatrix(e))}else this.setTransformMatrix(t.getViewMatrix(),t.getProjectionMatrix(e))}_bindFrameBuffer(e,t=!0){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,i=!0){if(e&&e._skipRendering)return;const s=this._engine;if(this._activeCamera=e,!this.activeCamera)throw new Error("Active camera not set");if(s.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,!this.prePass&&i){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._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 n=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Qt.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e<this._renderTargets.length;e++){const t=this._renderTargets.data[e];if(t._shouldRender()){this._renderId++;const e=t.activeCamera&&t.activeCamera!==this.activeCamera;t.render(e,this.dumpNextRenderTargets),n=!0}}Qt.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)n=e.action(this.activeCamera)||n;this._intermediateRendering=!1}this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??tt.RENDERPASS_MAIN,n&&!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),s.snapshotRendering&&s.snapshotRenderingMode===tt.SNAPSHOTRENDERING_FAST&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),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===tt.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 i=t.actionManager.actions[e];if(i.trigger===tt.ACTION_OnIntersectionEnterTrigger||i.trigger===tt.ACTION_OnIntersectionExitTrigger){const e=i.getTriggerParameter(),s=e.mesh?e.mesh:e,n=s.intersectsMesh(t,e.usePreciseIntersection),r=t._intersectionsInProgress.indexOf(s);n&&-1===r?i.trigger===tt.ACTION_OnIntersectionEnterTrigger?(i._executeCurrent(rn.CreateNew(t,void 0,s)),t._intersectionsInProgress.push(s)):i.trigger===tt.ACTION_OnIntersectionExitTrigger&&t._intersectionsInProgress.push(s):!n&&r>-1&&(i.trigger===tt.ACTION_OnIntersectionExitTrigger&&i._executeCurrent(rn.CreateNew(t,void 0,s)),t.actionManager.hasSpecificTrigger(tt.ACTION_OnIntersectionExitTrigger,(e=>{const t=e.mesh?e.mesh:e;return s===t}))&&i.trigger!==tt.ACTION_OnIntersectionExitTrigger||t._intersectionsInProgress.splice(r,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Dn.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Dn.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const n=this._engine.getLockstepMaxSteps();let r=Math.floor(e/t);for(r=Math.min(r,n);e>0&&s<r;)this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=t*i,this._animate(t),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(t),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,s++,e-=t;this._timeAccumulator=e<0?0:e}else{const e=this.useConstantAnimationDeltaTime?16:Math.max(Dn.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Dn.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 i=e.rigCameras[t].outputRenderTarget;i&&(i._cleared=!1)}}resetDrawCache(e){if(this.meshes)for(const t of this.meshes)t.resetDrawCache(e)}render(e=!0,t=!1){if(this.isDisposed)return;this.onReadyObservable.hasObservers()&&null===this._executeWhenReadyTimeoutId&&this._checkIsReady(),this._frameId++,this._defaultFrameBufferCleared=!1,this._checkCameraRenderTarget(this.activeCamera),this.activeCameras?.length&&this.activeCameras.forEach(this._checkCameraRenderTarget),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(tt.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!==tt.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!==tt.RIG_MODE_NONE))for(let e=0;e<this.activeCamera._rigCameras.length;e++)this.activeCamera._rigCameras[e].update();this.onBeforeRenderObservable.notifyObservers(this);const i=this.getEngine();this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);const s=this.activeCameras?.length?this.activeCameras[0]:this.activeCamera;if(this.renderTargetsEnabled){Qt.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!0;for(let e=0;e<this.customRenderTargets.length;e++){const t=this.customRenderTargets[e];if(t._shouldRender()){if(this._renderId++,this.activeCamera=t.activeCamera||this.activeCamera,!this.activeCamera)throw new Error("Active camera not set");i.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),t.render(s!==this.activeCamera,this.dumpNextRenderTargets)}}Qt.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=s?.renderPassId??tt.RENDERPASS_MAIN,this.activeCamera=s,this._activeCamera&&this._activeCamera.cameraRigMode!==tt.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;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.importedMeshesFiles=[],this.stopAllAnimations&&(this._activeAnimatables.forEach((e=>{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){ce.Error("An error occurred while calling onDisposeObservable!",e)}this.detachControl();if(this._engine.getInputElement())for(let e=0;e<this.cameras.length;e++)this.cameras[e].detachControl();this._disposeList(this.animationGroups),this._disposeList(this.lights),this._disposeList(this.meshes,(e=>e.dispose(!0))),this._disposeList(this.transformNodes,(e=>e.dispose(!0)));const t=this.cameras;this._disposeList(t),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),M._LastCreatedScene===this&&(this._engine.scenes.length>0?M._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:M._LastCreatedScene=null),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.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t??(e=>e.dispose());for(const e of i)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 B(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new B(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return e=e||(()=>!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const s=e.getBoundingInfo(),n=s.boundingBox.minimumWorld,r=s.boundingBox.maximumWorld;B.CheckExtends(n,t,i),B.CheckExtends(r,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,s,n=!1){throw W("Ray")}createPickingRayToRef(e,t,i,s,n,r=!1,a=!1){throw W("Ray")}createPickingRayInCameraSpace(e,t,i){throw W("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw W("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,n,r){const a=W("Ray",!0);return a&&ce.Warn(a),new zi}pickWithBoundingInfo(e,t,i,s,n){const r=W("Ray",!0);return r&&ce.Warn(r),new zi}pickWithRay(e,t,i,s){throw W("Ray")}multiPick(e,t,i,s,n){throw W("Ray")}multiPickWithRay(e,t,i){throw W("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}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(tt.MATERIAL_TextureDirtyFlag)}_getByTags(e,t,i){if(void 0===t)return e;const s=[];for(const n in e){const r=e[n];K&&K.MatchesQuery(r,t)&&(!i||i(r))&&s.push(r)}return s}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,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,s)}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(tt.MATERIAL_AllDirtyFlag))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,s,n,r,a){const o=Nt(e,t,i,s?this.offlineProvider:void 0,n,r,a);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}_loadFileAsync(e,t,i,s,n){return new Promise(((r,a)=>{this._loadFile(e,(e=>{r(e)}),t,i,s,((e,t)=>{a(t)}),n)}))}_requestFile(e,t,i,s,n,r,a){const o=Lt(e,t,i,s?this.offlineProvider:void 0,n,r,a);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}_requestFileAsync(e,t,i,s,n){return new Promise(((r,a)=>{this._requestFile(e,(e=>{r(e)}),t,i,s,(e=>{a(e)}),n)}))}_readFile(e,t,i,s,n){const r=Pt(e,t,i,s,n);return this._activeRequests.push(r),r.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),r}_readFileAsync(e,t,i){return new Promise(((s,n)=>{this._readFile(e,(e=>{s(e)}),t,i,(e=>{n(e)}))}))}getPerfCollector(){throw W("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)}}Dn.FOGMODE_NONE=tt.FOGMODE_NONE,Dn.FOGMODE_EXP=tt.FOGMODE_EXP,Dn.FOGMODE_EXP2=tt.FOGMODE_EXP2,Dn.FOGMODE_LINEAR=tt.FOGMODE_LINEAR,Dn.MinDeltaTime=1,Dn.MaxDeltaTime=1e3,C("BABYLON.Scene",Dn),function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(On||(On={}));class Pn{static get ForceFullSceneLoadingForIncremental(){return Ii.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Ii.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Ii.ShowLoadingScreen}static set ShowLoadingScreen(e){Ii.ShowLoadingScreen=e}static get loggingLevel(){return Ii.loggingLevel}static set loggingLevel(e){Ii.loggingLevel=e}static get CleanBoneMatrixWeights(){return Ii.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Ii.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return Pn._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){const t=Pn._RegisteredPlugins[e];return t||(ce.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"),Pn.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in Pn._RegisteredPlugins){const i=Pn._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Pn._RegisteredPlugins[t]}return Pn.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf("."),s=e.substring(i,e.length).toLowerCase();return Pn._GetPluginForExtension(s)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let s="Unable to load from "+(e.rawData?"binary data":e.url);return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,s,n,r,a,o){const l=Pn._GetDirectLoad(e.url);if(e.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";const h=a?Pn._GetPluginForExtension(a):l?Pn._GetPluginForDirectLoad(e.url):Pn._GetPluginForFilename(e.url);if(e.rawData&&!h.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";const c=h.plugin.createPlugin?.()??h.plugin;if(!c)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(Pn.OnPluginActivatedObservable.notifyObservers(c),l&&(c.canDirectLoad&&c.canDirectLoad(e.url)||!wt(e.url))){if(c.directLoad){const e=c.directLoad(t,l);e instanceof Promise?e.then((e=>{i(c,e)})).catch((e=>{n("Error in directLoad of _loadData: "+e,e)})):i(c,e)}else i(c,l);return c}const u=h.isBinary,d=(e,s)=>{t.isDisposed?n("Scene has been disposed"):i(c,e,s)};let _=null,f=!1;c.onDisposeObservable?.add((()=>{f=!0,_&&(_.abort(),_=null),r()}));const m=()=>{if(f)return;const i=(e,t)=>{n(e?.statusText,t)};if(!c.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";_=c.loadFile?c.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,d,s,u,i,o):t._loadFile(e.file||e.url,d,s,!0,u,i)},p=t.getEngine();let g=p.enableOfflineSupport;if(g){let i=!1;for(const s of t.disableOfflineSupportExceptionRules)if(s.test(e.url)){i=!0;break}g=!i}return g&&Ui.OfflineProviderFactory?t.offlineProvider=Ui.OfflineProviderFactory(e.url,m,p.disableManifestCheck):m(),c}static _GetFileInfo(e,t){let i,s,n=null,r=null;if(t)if(t.name){const e=t;i=`file:${e.name}`,s=e.name,n=e}else if(ArrayBuffer.isView(t))i="",s=Xt(),r=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,s="";else{const n=t;if("/"===n.substr(0,1))return Qt.Error("Wrong sceneFilename parameter"),null;i=e+n,s=n}else i=e,s=Qt.GetFilename(e),e=Qt.GetFolderPath(e);return{url:i,rootUrl:e,name:s,file:n,rawData:r}}static GetPluginForExtension(e){return Pn._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!Pn._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){const t=e.extensions;Pn._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{Pn._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}}))}}static ImportMesh(e,t,i="",s=M.LastCreatedScene,n=null,r=null,a=null,o=null,l=""){if(!s)return ce.Error("No scene available to import mesh to"),null;const h=Pn._GetFileInfo(t,i);if(!h)return null;const c={};s.addPendingData(c);const u=()=>{s.removePendingData(c)},d=(e,t)=>{const i=Pn._FormatErrorMessage(h,e,t);a?a(s,i,new Ie(i,Te,t)):ce.Error(i),u()},_=r?e=>{try{r(e)}catch(e){d("Error in onProgress callback: "+e,e)}}:void 0,f=(e,t,i,r,a,o,l,u)=>{if(s.importedMeshesFiles.push(h.url),n)try{n(e,t,i,r,a,o,l,u)}catch(e){d("Error in onSuccess callback: "+e,e)}s.removePendingData(c)};return Pn._LoadData(h,s,((t,i,n)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,n)),t.importMesh){const n=[],r=[],a=[];if(!t.importMesh(e,s,i,h.rootUrl,n,r,a,d))return;s.loadingPluginName=t.name,f(n,r,a,[],[],[],[],[])}else{t.importMeshAsync(e,s,i,h.rootUrl,_,h.name).then((e=>{s.loadingPluginName=t.name,f(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights,e.spriteManagers)})).catch((e=>{d(e.message,e)}))}}),_,d,u,o,l)}static ImportMeshAsync(e,t,i="",s=M.LastCreatedScene,n=null,r=null,a=""){return new Promise(((o,l)=>{Pn.ImportMesh(e,t,i,s,((e,t,i,s,n,r,a,l)=>{o({meshes:e,particleSystems:t,skeletons:i,animationGroups:s,transformNodes:n,geometries:r,lights:a,spriteManagers:l})}),n,((e,t,i)=>{l(i||new Error(t))}),r,a)}))}static Load(e,t="",i=M.LastCreatedEngine,s=null,n=null,r=null,a=null,o=""){return i?Pn.Append(e,t,new Dn(i),s,n,r,a,o):(Qt.Error("No engine available"),null)}static LoadAsync(e,t="",i=M.LastCreatedEngine,s=null,n=null,r=""){return new Promise(((a,o)=>{Pn.Load(e,t,i,(e=>{a(e)}),s,((e,t,i)=>{o(i||new Error(t))}),n,r)}))}static Append(e,t="",i=M.LastCreatedScene,s=null,n=null,r=null,a=null,o=""){if(!i)return ce.Error("No scene available to append to"),null;const l=Pn._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)};Pn.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1})));const u=(e,t)=>{const s=Pn._FormatErrorMessage(l,e,t);r?r(i,s,new Ie(s,Te,t)):ce.Error(s),c()},d=n?e=>{try{n(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,_=()=>{if(s)try{s(i)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return Pn._LoadData(l,i,((e,t)=>{if(e.load){if(!e.load(i,t,l.rootUrl,u))return;i.loadingPluginName=e.name,_()}else{e.loadAsync(i,t,l.rootUrl,d,l.name).then((()=>{i.loadingPluginName=e.name,_()})).catch((e=>{u(e.message,e)}))}}),d,u,c,a,o)}static AppendAsync(e,t="",i=M.LastCreatedScene,s=null,n=null,r=""){return new Promise(((a,o)=>{Pn.Append(e,t,i,(e=>{a(e)}),s,((e,t,i)=>{o(i||new Error(t))}),n,r)}))}static LoadAssetContainer(e,t="",i=M.LastCreatedScene,s=null,n=null,r=null,a=null,o=""){if(!i)return ce.Error("No scene available to load asset container to"),null;const l=Pn._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)},u=(e,t)=>{const s=Pn._FormatErrorMessage(l,e,t);r?r(i,s,new Ie(s,Te,t)):ce.Error(s),c()},d=n?e=>{try{n(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,_=e=>{if(s)try{s(e)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return Pn._LoadData(l,i,((e,t)=>{if(e.loadAssetContainer){const s=e.loadAssetContainer(i,t,l.rootUrl,u);if(!s)return;s.populateRootNodes(),i.loadingPluginName=e.name,_(s)}else if(e.loadAssetContainerAsync){e.loadAssetContainerAsync(i,t,l.rootUrl,d,l.name).then((t=>{t.populateRootNodes(),i.loadingPluginName=e.name,_(t)})).catch((e=>{u(e.message,e)}))}else u("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),d,u,c,a,o)}static LoadAssetContainerAsync(e,t="",i=M.LastCreatedScene,s=null,n=null){return new Promise(((r,a)=>{Pn.LoadAssetContainer(e,t,i,(e=>{r(e)}),s,((e,t,i)=>{a(i||new Error(t))}),n)}))}static ImportAnimations(e,t="",i=M.LastCreatedScene,s=!0,n=0,r=null,a=null,o=null,l=null,h=null){if(!i)return void ce.Error("No scene available to load animations to");if(s){for(const e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((e=>{e.dispose()}));i.getNodes().forEach((e=>{e.animations&&(e.animations=[])}))}else switch(n){case 0:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case 1:i.animationGroups.forEach((e=>{e.stop()}));break;case 2:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case 3:break;default:return void ce.Error("Unknown animation group loading mode value '"+n+"'")}const c=i.animatables.length;this.LoadAssetContainer(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(c),r),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),a&&a(i)}),o,l,h)}static ImportAnimationsAsync(e,t="",i=M.LastCreatedScene,s=!0,n=0,r=null,a=null,o=null,l=null,h=null){return new Promise(((a,l)=>{Pn.ImportAnimations(e,t,i,s,n,r,(e=>{a(e)}),o,((e,t,i)=>{l(i||new Error(t))}),h)}))}}Pn.NO_LOGGING=tt.SCENELOADER_NO_LOGGING,Pn.MINIMAL_LOGGING=tt.SCENELOADER_MINIMAL_LOGGING,Pn.SUMMARY_LOGGING=tt.SCENELOADER_SUMMARY_LOGGING,Pn.DETAILED_LOGGING=tt.SCENELOADER_DETAILED_LOGGING,Pn.OnPluginActivatedObservable=new g,Pn._RegisteredPlugins={},Pn._ShowingLoadingScreen=!1;class Nn{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=tt.TEXTURE_WRAP_ADDRESSMODE,this._wrapV=tt.TEXTURE_WRAP_ADDRESSMODE,this.wrapR=tt.TEXTURE_WRAP_ADDRESSMODE,this.anisotropicFilteringLevel=4,this.delayLoadState=tt.DELAYLOADSTATE_NONE,this._texture=null,this._engine=null,this._cachedSize=bs.Zero(),this._cachedBaseSize=bs.Zero(),this._initialSamplingMode=tt.TEXTURE_BILINEAR_SAMPLINGMODE,this._texture=Nn._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return this.delayLoadState===tt.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){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}class Ln extends Nn{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(tt.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(tt.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(tt.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(tt.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(tt.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(tt.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=Xt()),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(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=tt.TEXTURE_EXPLICIT_MODE,this.wrapR=tt.TEXTURE_WRAP_ADDRESSMODE,this.anisotropicFilteringLevel=Ln.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new g,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Ln._IsScene(e)?this._scene=e:this._engine=e:this._scene=M.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return G.IdentityReadOnly}getReflectionTextureMatrix(){return G.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,n,r){const a=this._getEngine();if(!a)return null;const o=a._getUseSRGBBuffer(!!n,t),l=a.getLoadedTexturesCache();for(let a=0;a<l.length;a++){const h=l[a];if(!(void 0!==n&&o!==h._useSRGBBuffer||void 0!==s&&s!==h.invertY||h.url!==e||h.generateMipMaps!==!t||i&&i!==h.samplingMode||void 0!==r&&r!==h.isCube))return h.incrementReferences(),h}return null}_rebuild(e=!1){}clone(){return null}get textureType(){return this._texture&&void 0!==this._texture.type?this._texture.type:tt.TEXTURETYPE_UNSIGNED_INT}get textureFormat(){return this._texture&&void 0!==this._texture.format?this._texture.format:tt.TEXTUREFORMAT_RGBA}_markAllSubMeshesAsTexturesDirty(){const e=this.getScene();e&&e.markAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag)}readPixels(e=0,t=0,i=null,s=!0,n=!1,r=0,a=0,o=Number.MAX_VALUE,l=Number.MAX_VALUE){if(!this._texture)return null;const h=this._getEngine();if(!h)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),l=Math.min(d,l);try{return this._texture.isCube?h._readTexturePixels(this._texture,o,l,e,t,i,s,n,r,a):h._readTexturePixels(this._texture,o,l,-1,t,i,s,n,r,a)}catch(e){return null}}_readPixelsSync(e=0,t=0,i=null,s=!0,n=!1){if(!this._texture)return null;const r=this.getSize();let a=r.width,o=r.height;const l=this._getEngine();if(!l)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?l._readTexturePixelsSync(this._texture,a,o,e,t,i,s,n):l._readTexturePixelsSync(this._texture,a,o,-1,t,i,s,n)}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=se.Serialize(this);return se.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let s=0;s<e.length;s++){const n=e[s];if(n.isReady())0==--i&&t();else{const e=n.onLoadObservable;e?e.addOnce((()=>{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}function Fn(e,t,i=!1){const s=t.width,n=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let s=e[t];s<0?s=0:s>1&&(s=1),i[t]=255*s}e=i}const r=document.createElement("canvas");r.width=s,r.height=n;const a=r.getContext("2d");if(!a)return null;const o=a.createImageData(s,n);if(o.data.set(e),a.putImageData(o,0,0),i){const e=document.createElement("canvas");e.width=s,e.height=n;const t=e.getContext("2d");return t?(t.translate(0,n),t.scale(1,-1),t.drawImage(r,0,0),e.toDataURL("image/png")):null}return r.toDataURL("image/png")}Ln.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,e([a()],Ln.prototype,"uniqueId",void 0),e([a()],Ln.prototype,"name",void 0),e([a()],Ln.prototype,"metadata",void 0),e([a("hasAlpha")],Ln.prototype,"_hasAlpha",void 0),e([a("getAlphaFromRGB")],Ln.prototype,"_getAlphaFromRGB",void 0),e([a()],Ln.prototype,"level",void 0),e([a("coordinatesIndex")],Ln.prototype,"_coordinatesIndex",void 0),e([a()],Ln.prototype,"optimizeUVAllocation",void 0),e([a("coordinatesMode")],Ln.prototype,"_coordinatesMode",void 0),e([a()],Ln.prototype,"wrapU",null),e([a()],Ln.prototype,"wrapV",null),e([a()],Ln.prototype,"wrapR",void 0),e([a()],Ln.prototype,"anisotropicFilteringLevel",void 0),e([a()],Ln.prototype,"isCube",null),e([a()],Ln.prototype,"is3D",null),e([a()],Ln.prototype,"is2DArray",null),e([a()],Ln.prototype,"gammaSpace",null),e([a()],Ln.prototype,"invertZ",void 0),e([a()],Ln.prototype,"lodLevelInAlpha",void 0),e([a()],Ln.prototype,"lodGenerationOffset",null),e([a()],Ln.prototype,"lodGenerationScale",null),e([a()],Ln.prototype,"linearSpecularLOD",null),e([o()],Ln.prototype,"irradianceTexture",null),e([a()],Ln.prototype,"isRenderTarget",void 0);class wn extends Ln{static _CreateVideoTexture(e,t,i,s=!1,n=!1,r=wn.TRILINEAR_SAMPLINGMODE,a={},o,l=tt.TEXTUREFORMAT_RGBA){throw W("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(e,t,i,s,n=wn.TRILINEAR_SAMPLINGMODE,r=null,a=null,o=null,l=!1,h,c,u,d,_){let f;super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=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 g,this._isBlocking=!0,this.name=e||"",this.url=e;let m=!1,p=null,E=!0;"object"==typeof i&&null!==i?(f=i.noMipmap??!1,s=i.invertY??!Si.UseOpenGLOrientationForUV,n=i.samplingMode??wn.TRILINEAR_SAMPLINGMODE,r=i.onLoad??null,a=i.onError??null,o=i.buffer??null,l=i.deleteBuffer??!1,h=i.format,c=i.mimeType,u=i.loaderOptions,d=i.creationFlags,m=i.useSRGBBuffer??!1,p=i.internalTexture??null,E=i.gammaSpace??E):f=!!i,this._gammaSpace=E,this._noMipmap=f,this._invertY=void 0===s?!Si.UseOpenGLOrientationForUV:s,this._initialSamplingMode=n,this._buffer=o,this._deleteBuffer=l,this._mimeType=c,this._loaderOptions=u,this._creationFlags=d,this._useSRGBBuffer=m,this._forcedExtension=_,h&&(this._format=h);const T=this.getScene(),A=this._getEngine();if(!A)return;A.onBeforeTextureInitObservable.notifyObservers(this);const R=()=>{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),r&&r(),!this.isBlocking&&T&&T.resetCachedMaterial()},v=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),wn.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!p)return this._delayedOnLoad=R,void(this._delayedOnError=v);if(this._texture=p??this._getFromCache(this.url,f,n,this._invertY,m,this.isCube),this._texture)if(this._texture.isReady)et.SetImmediate((()=>R()));else{const e=this._texture.onLoadedObservable.add(R);this._texture.onErrorObservable.add((t=>{v(t.message,t.exception),this._texture?.onLoadedObservable.remove(e)}))}else if(T&&T.useDelayedTextureLoading)this.delayLoadState=tt.DELAYLOADSTATE_NOTLOADED,this._delayedOnLoad=R,this._delayedOnError=v;else{try{this._texture=A.createTexture(this.url,f,this._invertY,T,n,R,v,this._buffer,void 0,this._format,this._forcedExtension,c,u,d,m)}catch(e){throw v("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this)))),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=s,this.delayLoadState=tt.DELAYLOADSTATE_NOTLOADED,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(this.delayLoadState!==tt.DELAYLOADSTATE_NOTLOADED)return;const e=this.getScene();e&&(this.delayLoadState=tt.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?et.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,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,i,s){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,B.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,s),s.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,s.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,s.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=G.Zero(),this._rowGenerationMatrix=new G,this._t0=B.Zero(),this._t1=B.Zero(),this._t2=B.Zero()),G.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(G.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,X.Matrix[0]),G.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,X.Matrix[1]),G.ScalingToRef(this._cachedUScale,this._cachedVScale,0,X.Matrix[2]),G.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,X.Matrix[3]),X.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(X.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(X.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(X.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),G.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 i=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&i!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this))),this._cachedTextureMatrix}getReflectionTextureMatrix(){const e=this.getScene();if(!e)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!==wn.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=G.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=G.Zero());const t=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 wn.PLANAR_MODE:G.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 wn.PROJECTION_MODE:{G.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:G.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this))),this._cachedReflectionTextureMatrix}clone(){const e={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 se.Clone((()=>new wn(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){const e=this.name;wn.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(wn._SerializeInternalTextureUniqueId);return t?((wn.SerializeBuffers||wn.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(t.base64String=this._buffer,t.name=t.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?t.base64String="data:image/png;base64,"+Se(this._buffer):(wn.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?function(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const n=e._readPixelsSync(t,i);return n?Fn(n,e.getSize(),s.invertY):null}(this):async function(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const n=await e.readPixels(t,i);return n?Fn(n,e.getSize(),s.invertY):null}(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,wn._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=this._texture?.uniqueId??void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const s=Vt.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&s.updateSamplingMode&&s._samplingMode&&s._samplingMode!==e.samplingMode&&s.updateSamplingMode(e.samplingMode),s}if(e.isCube&&!e.isRenderTarget)return wn._CubeTextureParser(e,t,i);const s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;let n;if(s){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){n=t;break}}const r=t=>{if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){const i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i<e.animations.length;i++){const s=e.animations[i],n=b("BABYLON.Animation");n&&t.animations.push(n.Parse(s))}s&&!n&&t?._texture?._setUniqueId(e.internalTextureUniqueId)};return se.Parse((()=>{let s=!0;if(e.noMipmap&&(s=!1),e.mirrorPlane){const i=wn._CreateMirror(e.name,e.renderTargetSize,t,s);return i._waitingRenderList=e.renderList,i.mirrorPlane=si.FromArray(e.mirrorPlane),r(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i<t.reflectionProbes.length;i++){const s=t.reflectionProbes[i];if(s.name===e.name)return s.cubeTexture}}else i=wn._CreateRenderTargetTexture(e.name,e.renderTargetSize,t,s,e._creationFlags??0),i._waitingRenderList=e.renderList;return r(i),i}if(e.isVideo){const n=wn._CreateVideoTexture(i+(e.url||e.name),i+(e.src||e.url),t,s,e.invertY,e.samplingMode,e.settings||{});return r(n),n}{let a;if(e.base64String&&!n)a=wn.CreateFromBase64String(e.base64String,e.base64String,t,!s,e.invertY,e.samplingMode,(()=>{r(a)}),e._creationFlags??0,e._useSRGBBuffer??!1),a.name=e.name;else{let o;o=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||wn.UseSerializedUrlIfAny)&&(o=e.url);const l={noMipmap:!s,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{r(a)},internalTexture:n};a=new wn(o,t,l)}return a}}),e,t)}static CreateFromBase64String(e,t,i,s,n,r=wn.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=tt.TEXTUREFORMAT_RGBA,h,c){return new wn("data:"+t,i,s,n,r,a,o,e,!1,l,void 0,void 0,h,c)}static LoadFromDataString(e,t,i,s=!1,n,r=!0,a=wn.TRILINEAR_SAMPLINGMODE,o=null,l=null,h=tt.TEXTUREFORMAT_RGBA,c,u){return"data:"!==e.substr(0,5)&&(e="data:"+e),new wn(e,i,n,r,a,o,l,t,s,h,void 0,void 0,c,u)}}wn.SerializeBuffers=!0,wn.ForceSerializeBuffers=!1,wn.OnTextureLoadErrorObservable=new g,wn._SerializeInternalTextureUniqueId=!1,wn._CubeTextureParser=(e,t,i)=>{throw W("CubeTexture")},wn._CreateMirror=(e,t,i,s)=>{throw W("MirrorTexture")},wn._CreateRenderTargetTexture=(e,t,i,s,n)=>{throw W("RenderTargetTexture")},wn.NEAREST_SAMPLINGMODE=tt.TEXTURE_NEAREST_SAMPLINGMODE,wn.NEAREST_NEAREST_MIPLINEAR=tt.TEXTURE_NEAREST_NEAREST_MIPLINEAR,wn.BILINEAR_SAMPLINGMODE=tt.TEXTURE_BILINEAR_SAMPLINGMODE,wn.LINEAR_LINEAR_MIPNEAREST=tt.TEXTURE_LINEAR_LINEAR_MIPNEAREST,wn.TRILINEAR_SAMPLINGMODE=tt.TEXTURE_TRILINEAR_SAMPLINGMODE,wn.LINEAR_LINEAR_MIPLINEAR=tt.TEXTURE_LINEAR_LINEAR_MIPLINEAR,wn.NEAREST_NEAREST_MIPNEAREST=tt.TEXTURE_NEAREST_NEAREST_MIPNEAREST,wn.NEAREST_LINEAR_MIPNEAREST=tt.TEXTURE_NEAREST_LINEAR_MIPNEAREST,wn.NEAREST_LINEAR_MIPLINEAR=tt.TEXTURE_NEAREST_LINEAR_MIPLINEAR,wn.NEAREST_LINEAR=tt.TEXTURE_NEAREST_LINEAR,wn.NEAREST_NEAREST=tt.TEXTURE_NEAREST_NEAREST,wn.LINEAR_NEAREST_MIPNEAREST=tt.TEXTURE_LINEAR_NEAREST_MIPNEAREST,wn.LINEAR_NEAREST_MIPLINEAR=tt.TEXTURE_LINEAR_NEAREST_MIPLINEAR,wn.LINEAR_LINEAR=tt.TEXTURE_LINEAR_LINEAR,wn.LINEAR_NEAREST=tt.TEXTURE_LINEAR_NEAREST,wn.EXPLICIT_MODE=tt.TEXTURE_EXPLICIT_MODE,wn.SPHERICAL_MODE=tt.TEXTURE_SPHERICAL_MODE,wn.PLANAR_MODE=tt.TEXTURE_PLANAR_MODE,wn.CUBIC_MODE=tt.TEXTURE_CUBIC_MODE,wn.PROJECTION_MODE=tt.TEXTURE_PROJECTION_MODE,wn.SKYBOX_MODE=tt.TEXTURE_SKYBOX_MODE,wn.INVCUBIC_MODE=tt.TEXTURE_INVCUBIC_MODE,wn.EQUIRECTANGULAR_MODE=tt.TEXTURE_EQUIRECTANGULAR_MODE,wn.FIXED_EQUIRECTANGULAR_MODE=tt.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,wn.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=tt.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,wn.CLAMP_ADDRESSMODE=tt.TEXTURE_CLAMP_ADDRESSMODE,wn.WRAP_ADDRESSMODE=tt.TEXTURE_WRAP_ADDRESSMODE,wn.MIRROR_ADDRESSMODE=tt.TEXTURE_MIRROR_ADDRESSMODE,wn.UseSerializedUrlIfAny=!1,e([a()],wn.prototype,"url",void 0),e([a()],wn.prototype,"uOffset",void 0),e([a()],wn.prototype,"vOffset",void 0),e([a()],wn.prototype,"uScale",void 0),e([a()],wn.prototype,"vScale",void 0),e([a()],wn.prototype,"uAng",void 0),e([a()],wn.prototype,"vAng",void 0),e([a()],wn.prototype,"wAng",void 0),e([a()],wn.prototype,"uRotationCenter",void 0),e([a()],wn.prototype,"vRotationCenter",void 0),e([a()],wn.prototype,"wRotationCenter",void 0),e([a()],wn.prototype,"homogeneousRotationInUVTransform",void 0),e([a()],wn.prototype,"isBlocking",null),C("BABYLON.Texture",wn),se._TextureParser=wn.Parse;it.ShadersStore.postprocessVertexShader="attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Bn{get depthStencilTexture(){return this._depthStencilTexture}get depthStencilTextureWithStencil(){return this._depthStencilTextureWithStencil}get isCube(){return this._isCube}get isMulti(){return this._isMulti}get is2DArray(){return this.layers>0}get is3D(){return this.depth>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){return this._textures?.[0]??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,n){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=s,this._depthStencilTexture=null,this.label=n}setTextures(e){Array.isArray(e)?this._textures=e:this._textures=e?[e]:null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,n=tt.TEXTUREFORMAT_DEPTH32_FLOAT,r){return this._depthStencilTexture?.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=r,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:s,depthTextureFormat:n,label:r},this),this._depthStencilTexture}_shareDepth(e){this.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){let e=null;if(this._isMulti){const t=this.textures;if(t&&t.length>0){let i=!1,s=t.length,n=-1;const r=t[t.length-1]._source;14!==r&&12!==r||(i=!0,n=t[t.length-1].format,s--);const a=[],o=[],l=[],h=[],c=[],u=[],d=[],_={};for(let e=0;e<s;++e){const i=t[e];a.push(i.samplingMode),o.push(i.type),l.push(i.format);void 0!==_[i.uniqueId]?(h.push(-1),d.push(0)):(_[i.uniqueId]=e,i.is2DArray?(h.push(tt.TEXTURE_2D_ARRAY),d.push(i.depth)):i.isCube?(h.push(tt.TEXTURE_CUBE_MAP),d.push(0)):i.is3D?(h.push(tt.TEXTURE_3D),d.push(i.depth)):(h.push(tt.TEXTURE_2D),d.push(0))),this._faceIndices&&c.push(this._faceIndices[e]??0),this._layerIndices&&u.push(this._layerIndices[e]??0)}const f={samplingModes:a,generateMipMaps:t[0].generateMipMaps,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:this._generateStencilBuffer,generateDepthTexture:i,depthTextureFormat:n,types:o,formats:l,textureCount:s,targetTypes:h,faceIndex:c,layerIndex:u,layerCounts:d,label:this.label},m={width:this.width,height:this.height,depth:this.depth};e=this._engine.createMultipleRenderTarget(m,f);for(let i=0;i<s;++i){if(-1!==h[i])continue;const s=_[t[i].uniqueId];e.setTexture(e.textures[s],i)}}}else{const t={};if(t.generateDepthBuffer=this._generateDepthBuffer,t.generateMipMaps=this.texture?.generateMipMaps??!1,t.generateStencilBuffer=this._generateStencilBuffer,t.samplingMode=this.texture?.samplingMode,t.type=this.texture?.type,t.format=this.texture?.format,t.noColorAttachment=!this._textures,t.label=this.label,this.isCube)e=this._engine.createRenderTargetCubeTexture(this.width,t);else{const i={width:this.width,height:this.height,layers:this.is2DArray||this.is3D?this.texture?.depth:void 0};e=this._engine.createRenderTargetTexture(i,t)}e.texture&&(e.texture.isReady=!0)}return e}_swapRenderTargetWrapper(e){if(this._textures&&e._textures)for(let t=0;t<this._textures.length;++t)this._textures[t]._swapAndDie(e._textures[t],!1),e._textures[t].isReady=!0;this._depthStencilTexture&&e._depthStencilTexture&&(this._depthStencilTexture._swapAndDie(e._depthStencilTexture),e._depthStencilTexture.isReady=!0),this._textures=null,this._depthStencilTexture=null}_rebuild(){const e=this._cloneRenderTargetWrapper();if(e){if(this._depthStencilTexture){const t=this._depthStencilTexture.samplingMode,i=this._depthStencilTexture.format,s=t===tt.TEXTURE_BILINEAR_SAMPLINGMODE||t===tt.TEXTURE_TRILINEAR_SAMPLINGMODE||t===tt.TEXTURE_LINEAR_LINEAR_MIPNEAREST;e.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction,s,this._depthStencilTextureWithStencil,this._depthStencilTexture.samples,i,this._depthStencilTextureLabel)}this.samples>1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e<this._textures?.length;++e)this._textures[e].dispose();this._textures=null}dispose(e=!1){e||(this._depthStencilTexture?.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class Un extends Bn{constructor(e,t,i,s,n){super(e,t,i,s),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=n}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=super._cloneRenderTargetWrapper(),e}_swapRenderTargetWrapper(e){super._swapRenderTargetWrapper(e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,n=tt.TEXTUREFORMAT_DEPTH32_FLOAT,r){if(this._depthStencilBuffer){const e=this._engine,t=e._currentFramebuffer,i=this._context;e._bindUnboundFramebuffer(this._framebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,null),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,null),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.STENCIL_ATTACHMENT,i.RENDERBUFFER,null),e._bindUnboundFramebuffer(t),i.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null}return super.createDepthStencilTexture(e,t,i,s,n,r)}shareDepth(e){super.shareDepth(e);const t=this._context,i=this._depthStencilBuffer,s=e._MSAAFramebuffer||e._framebuffer,n=this._engine;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;const r=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;n._bindUnboundFramebuffer(s),t.framebufferRenderbuffer(t.FRAMEBUFFER,r,t.RENDERBUFFER,i),n._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,s=0){if(!e._hardwareTexture)return;const n=this._framebuffer,r=this._engine,a=r._currentFramebuffer;if(r._bindUnboundFramebuffer(n),r.webGLVersion>1){const n=this._context,r=n["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??this.layerIndices?.[t]??0,n.framebufferTextureLayer(n.FRAMEBUFFER,r,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=i??this.faceIndices?.[t]??0,n.framebufferTexture2D(n.FRAMEBUFFER,r,n.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):n.framebufferTexture2D(n.FRAMEBUFFER,r,n.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const n=this._context,r=n["COLOR_ATTACHMENT"+t+"_WEBGL"],a=void 0!==i?n.TEXTURE_CUBE_MAP_POSITIVE_X+i:n.TEXTURE_2D;n.framebufferTexture2D(n.FRAMEBUFFER,r,a,e._hardwareTexture.underlyingResource,s)}r._bindUnboundFramebuffer(a)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=this._attachments?.length??this.textures.length;for(let e=0;e<i;e++){const t=this.textures[e];t&&(t.is2DArray||t.is3D?this._bindTextureRenderTarget(t,e,this.layerIndices[e]):t.isCube?this._bindTextureRenderTarget(t,e,this.faceIndices[e]):this._bindTextureRenderTarget(t,e))}}setLayerAndFaceIndex(e=0,t,i){if(super.setLayerAndFaceIndex(e,t,i),!this.textures||!this.layerIndices||!this.faceIndices)return;const s=this.textures[e];s.is2DArray||s.is3D?this._bindTextureRenderTarget(this.textures[e],e,this.layerIndices[e]):s.isCube&&this._bindTextureRenderTarget(this.textures[e],e,this.faceIndices[e])}dispose(e=this._disposeOnlyFramebuffers){const t=this._context;e||(this._colorTextureArray&&(this._context.deleteTexture(this._colorTextureArray),this._colorTextureArray=null),this._depthStencilTextureArray&&(this._context.deleteTexture(this._depthStencilTextureArray),this._depthStencilTextureArray=null)),this._framebuffer&&(t.deleteFramebuffer(this._framebuffer),this._framebuffer=null),this._depthStencilBuffer&&(t.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null),this._MSAAFramebuffer&&(t.deleteFramebuffer(this._MSAAFramebuffer),this._MSAAFramebuffer=null),super.dispose(e)}}Pi.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const s=new Un(e,t,i,this,this._gl);return this._renderTargetWrapperCache.push(s),s},Pi.prototype.createRenderTargetTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e);let s,n,r=!0,a=!1,o=!1,l=1;void 0!==t&&"object"==typeof t&&(r=t.generateDepthBuffer??!0,a=!!t.generateStencilBuffer,o=!!t.noColorAttachment,s=t.colorAttachment,l=t.samples??1,n=t.label);const h=s||(o?null:this._createInternalTexture(e,t,!0,5)),c=e.width||e,u=e.height||e,d=this._currentFramebuffer,_=this._gl,f=_.createFramebuffer();return this._bindUnboundFramebuffer(f),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(a,r,c,u),!h||h.is2DArray||h.is3D||_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_2D,h._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(d),i.label=n??"RenderTargetWrapper",i._framebuffer=f,i._generateDepthBuffer=r,i._generateStencilBuffer=a,i.setTextures(h),this.updateRenderTargetTextureSampleCount(i,l),i},Pi.prototype._createDepthStencilTexture=function(e,t){const i=this._gl,s=e.layers||0,n=e.depth||0;let r=i.TEXTURE_2D;0!==s?r=i.TEXTURE_2D_ARRAY:0!==n&&(r=i.TEXTURE_3D);const a=new vt(this,12);if(a.label=t.label,!this._caps.depthTextureExtension)return ce.Error("Depth texture is not supported by your browser or hardware."),a;const o={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t};if(this._bindTextureDirectly(r,a,!0),this._setupDepthStencilTexture(a,e,o.generateStencil,0!==o.comparisonFunction&&o.bilinearFiltering,o.comparisonFunction,o.samples),void 0!==o.depthTextureFormat){if(o.depthTextureFormat!==tt.TEXTUREFORMAT_DEPTH16&&o.depthTextureFormat!==tt.TEXTUREFORMAT_DEPTH24&&o.depthTextureFormat!==tt.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8&&o.depthTextureFormat!==tt.TEXTUREFORMAT_DEPTH24_STENCIL8&&o.depthTextureFormat!==tt.TEXTUREFORMAT_DEPTH32_FLOAT&&o.depthTextureFormat!==tt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8)return ce.Error("Depth texture format is not supported."),a;a.format=o.depthTextureFormat}else a.format=o.generateStencil?tt.TEXTUREFORMAT_DEPTH24_STENCIL8:tt.TEXTUREFORMAT_DEPTH24;const l=a.format===tt.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||a.format===tt.TEXTUREFORMAT_DEPTH24_STENCIL8||a.format===tt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8;let h=i.UNSIGNED_INT;a.format===tt.TEXTUREFORMAT_DEPTH16?h=i.UNSIGNED_SHORT:a.format===tt.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||a.format===tt.TEXTUREFORMAT_DEPTH24_STENCIL8?h=i.UNSIGNED_INT_24_8:a.format===tt.TEXTUREFORMAT_DEPTH32_FLOAT?h=i.FLOAT:a.format===tt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8&&(h=i.FLOAT_32_UNSIGNED_INT_24_8_REV);const c=l?i.DEPTH_STENCIL:i.DEPTH_COMPONENT;let u=c;return this.webGLVersion>1&&(a.format===tt.TEXTUREFORMAT_DEPTH16?u=i.DEPTH_COMPONENT16:a.format===tt.TEXTUREFORMAT_DEPTH24?u=i.DEPTH_COMPONENT24:a.format===tt.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||a.format===tt.TEXTUREFORMAT_DEPTH24_STENCIL8?u=i.DEPTH24_STENCIL8:a.format===tt.TEXTUREFORMAT_DEPTH32_FLOAT?u=i.DEPTH_COMPONENT32F:a.format===tt.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8&&(u=i.DEPTH32F_STENCIL8)),a.is2DArray?i.texImage3D(r,0,u,a.width,a.height,s,0,c,h,null):a.is3D?i.texImage3D(r,0,u,a.width,a.height,n,0,c,h,null):i.texImage2D(r,0,u,a.width,a.height,0,c,h,null),this._bindTextureDirectly(r,null),this._internalTexturesCache.push(a),a},Pi.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)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 s=e.texture._hardwareTexture;if(s.releaseMSAARenderBuffers(),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(e._MSAAFramebuffer);const r=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),i.COLOR_ATTACHMENT0,!1);if(!r)throw new Error("Unable to create multi sampled framebuffer");s.addMSAARenderBuffer(r)}else this._bindUnboundFramebuffer(e._framebuffer);return e.texture.samples=t,e._samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t),this._bindUnboundFramebuffer(null),t},Pi.prototype._setupDepthStencilTexture=function(e,t,i,s,n,r=1){const a=t.width||t,o=t.height||t,l=t.layers||0,h=t.depth||0;e.baseWidth=a,e.baseHeight=o,e.width=a,e.height=o,e.is2DArray=l>0,e.depth=l||h,e.isReady=!0,e.samples=r,e.generateMipMaps=!1,e.samplingMode=s?tt.TEXTURE_BILINEAR_SAMPLINGMODE:tt.TEXTURE_NEAREST_SAMPLINGMODE,e.type=tt.TEXTURETYPE_UNSIGNED_INT,e._comparisonFunction=n;const c=this._gl,u=this._getTextureTarget(e),d=this._getSamplingParameters(e.samplingMode,!1);c.texParameteri(u,c.TEXTURE_MAG_FILTER,d.mag),c.texParameteri(u,c.TEXTURE_MIN_FILTER,d.min),c.texParameteri(u,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(u,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===n?(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,tt.LEQUAL),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,n),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))},St.prototype.setTextureFromPostProcess=function(e,t,i){let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,s?.texture??null,i)},St.prototype.setTextureFromPostProcessOutput=function(e,t,i){this._bindTexture(e,t?._outputTexture?.texture??null,i)},mt.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)},mt.prototype.setTextureFromPostProcessOutput=function(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)};class kn{static RegisterShaderCodeProcessing(e,t){t?kn._CustomShaderCodeProcessing[e??""]=t:delete kn._CustomShaderCodeProcessing[e??""]}static _GetShaderCodeProcessing(e){return kn._CustomShaderCodeProcessing[e]??kn._CustomShaderCodeProcessing[""]}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)}))}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(e,t,i,s,n,r,a=tt.TEXTURE_NEAREST_SAMPLINGMODE,o,l,h=null,c=tt.TEXTURETYPE_UNSIGNED_INT,u="postprocess",d,_=!1,f=tt.TEXTUREFORMAT_RGBA,m=0){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=tt.ALPHA_DISABLE,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=tt.SCALEMODE_FLOOR,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new ei(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new w(1,1),this._texelSize=w.Zero(),this.onActivateObservable=new g,this.onSizeChangedObservable=new g,this.onApplyObservable=new g,this.onBeforeRenderObservable=new g,this.onAfterRenderObservable=new g,this.name=e;let p=1,E=null;if(i&&!Array.isArray(i)){const e=i;i=e.uniforms??null,s=e.samplers??null,p=e.size??1,r=e.camera??null,a=e.samplingMode??tt.TEXTURE_NEAREST_SAMPLINGMODE,o=e.engine,l=e.reusable,h=e.defines??null,c=e.textureType??tt.TEXTURETYPE_UNSIGNED_INT,u=e.vertexUrl??"postprocess",d=e.indexParameters,_=e.blockCompilation??!1,f=e.textureFormat??tt.TEXTUREFORMAT_RGBA,m=e.shaderLanguage??0,E=e.uniformBuffers??null}else n&&(p="number"==typeof n?n:{width:n.width,height:n.height});null!=r?(this._camera=r,this._scene=r.getScene(),r.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):o&&(this._engine=o,this._engine.postProcesses.push(this)),this._options=p,this.renderTargetSamplingMode=a||tt.TEXTURE_NEAREST_SAMPLINGMODE,this._reusable=l||!1,this._textureType=c,this._textureFormat=f,this._shaderLanguage=m,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=u,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=E||[],this._indexParameters=d,this._drawWrapper=new Ti(this._engine),_||this.updateEffect(h)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new ei(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,n,r,a,o){const l=kn._GetShaderCodeProcessing(this.name);if(l?.defineCustomBindings){const s=t?.slice()??[];s.push(...this._parameters);const n=i?.slice()??[];n.push(...this._samplers),e=l.defineCustomBindings(this.name,e,s,n),t=s,i=n}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:a??this._vertexUrl,fragment:o??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:n??null,onError:r??null,indexParameters:s||this._indexParameters,processCodeAfterIncludes:l?.processCodeAfterIncludes?(e,t)=>l.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:l?.processFinalCode?(e,t)=>l.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s<this._textureCache.length;s++)if(this._textureCache[s].texture.width===e.width&&this._textureCache[s].texture.height===e.height&&this._textureCache[s].postProcessChannel===i&&this._textureCache[s].texture._generateDepthBuffer===t.generateDepthBuffer&&this._textureCache[s].texture.samples===t.samples)return this._textureCache[s].texture;const s=this._engine.createRenderTargetTexture(e,t);return this._textureCache.push({texture:s,postProcessChannel:i,lastUsedRenderId:-1}),s}_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 i=0;i<this._textures.length;i++)if(this._textures.data[i]===this._textureCache[t].texture){e=!0;break}e||(this._textureCache[t].texture.dispose(),this._textureCache.splice(t,1))}}resize(e,t,i=null,s=!1,n=!1){this._textures.length>0&&this._textures.reset(),this.width=e,this.height=t;let r=null;if(i)for(let e=0;e<i._postProcesses.length;e++)if(null!==i._postProcesses[e]){r=i._postProcesses[e];break}const a={width:this.width,height:this.height},o={generateMipMaps:s,generateDepthBuffer:n||r===this,generateStencilBuffer:(n||r===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 i=0;i<this._textureCache.length;i++)if(this._textureCache[i].texture===e){t=this._textureCache[i];break}t&&(t.lastUsedRenderId=this._renderId)}return e}activate(e,t=null,i){const s=(e=e||this._camera).getScene(),n=s.getEngine(),r=n.getCaps().maxTextureSize,a=(t?t.width:this._engine.getRenderWidth(!0))*this._options|0,o=(t?t.height:this._engine.getRenderHeight(!0))*this._options|0;let l=this._options.width||a,h=this._options.height||o;const c=this.renderTargetSamplingMode!==tt.TEXTURE_NEAREST_LINEAR&&this.renderTargetSamplingMode!==tt.TEXTURE_NEAREST_NEAREST&&this.renderTargetSamplingMode!==tt.TEXTURE_LINEAR_LINEAR;let u=null;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){const e=n.currentViewport;e&&(l*=e.width,h*=e.height)}(c||this.alwaysForcePOT)&&(this._options.width||(l=n.needPOTTextures?qt(l,r,this.scaleMode):l),this._options.height||(h=n.needPOTTextures?qt(h,r,this.scaleMode):h)),this.width===l&&this.height===h&&(u=this._getTarget())||this.resize(l,h,e,c,i),this._textures.forEach((e=>{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}return u||(u=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(a/l,o/h),this._engine.bindFramebuffer(u,0,a,o,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(u,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(this.alphaMode===tt.ALPHA_DISABLE||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),u}get isSupported(){return this._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._drawWrapper.effect?.isReady()??!1}apply(){if(!this._drawWrapper.effect?.isReady())return null;let e;return this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),kn._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect),this._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._disposeTextures(),this._scene&&(t=this._scene.postProcesses.indexOf(this),-1!==t&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),-1!==t&&this._engine.postProcesses.splice(t,1),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()}}serialize(){const e=se.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.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=kn.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const s=b(e.customType);if(!s||!s._Parse)return null;const n=t?t.getCameraById(e.cameraId):null;return s._Parse(e,n,t,i)}static _Parse(e,t,i,s){return se.Parse((()=>new kn(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat)),e,i,s)}}kn._CustomShaderCodeProcessing={},e([a()],kn.prototype,"uniqueId",void 0),e([a()],kn.prototype,"name",void 0),e([a()],kn.prototype,"width",void 0),e([a()],kn.prototype,"height",void 0),e([a()],kn.prototype,"renderTargetSamplingMode",void 0),e([d()],kn.prototype,"clearColor",void 0),e([a()],kn.prototype,"autoClear",void 0),e([a()],kn.prototype,"forceAutoClearInAlphaMode",void 0),e([a()],kn.prototype,"alphaMode",void 0),e([a()],kn.prototype,"alphaConstants",void 0),e([a()],kn.prototype,"enablePixelPerfectMode",void 0),e([a()],kn.prototype,"forceFullscreenViewport",void 0),e([a()],kn.prototype,"scaleMode",void 0),e([a()],kn.prototype,"alwaysForcePOT",void 0),e([a("samples")],kn.prototype,"_samples",void 0),e([a()],kn.prototype,"adaptScaleToCurrentViewport",void 0),C("BABYLON.PostProcess",kn);it.IncludesShadersStore.helperFunctions="const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; \nconst float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\n#define absEps(x) abs(x)+Epsilon\n#define maxEps(x) max(x,Epsilon)\n#define saturateEps(x) clamp(x,Epsilon,1.0)\nmat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nmat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;}\n#if USE_EXACT_SRGB_CONVERSIONS\nvec3 toLinearSpaceExact(vec3 color)\n{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));\n#else\nreturn\nvec3(\ncolor.r<=0.04045 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.04045 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.04045 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\nvec3 toGammaSpaceExact(vec3 color)\n{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));\n#else\nreturn\nvec3(\ncolor.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\n#endif\nfloat toLinearSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nvec3 toLinearSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nvec4 toLinearSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfloat toGammaSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,GammaEncodePowerApprox);\n#endif\n}\nvec3 toGammaSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nvec4 toGammaSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfloat square(float value)\n{return value*value;}\nvec3 square(vec3 value)\n{return value*value;}\nfloat pow5(float value) {float sq=value*value;return sq*sq*value;}\nfloat getLuminance(vec3 color)\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfloat getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfloat dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;}\nconst float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); }\nvec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;}\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";it.ShadersStore.rgbdDecodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include<helperFunctions>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}",Pi.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:tt.TEXTURETYPE_UNSIGNED_INT,samplingMode:tt.TEXTURE_TRILINEAR_SAMPLINGMODE,format:tt.TEXTUREFORMAT_RGBA,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,(s.type!==tt.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(s.type!==tt.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(s.samplingMode=tt.TEXTURE_NEAREST_SAMPLINGMODE);const n=this._gl,r=new vt(this,5);this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,r,!0);const a=this._getSamplingParameters(s.samplingMode,s.generateMipMaps);s.type!==tt.TEXTURETYPE_FLOAT||this._caps.textureFloat||(s.type=tt.TEXTURETYPE_UNSIGNED_INT,ce.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MIN_FILTER,a.min),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE);for(let t=0;t<6;t++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(s.type,s.format),e,e,0,this._getInternalFormat(s.format),this._getWebGLTextureType(s.type),null);const o=n.createFramebuffer();return this._bindUnboundFramebuffer(o),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(s.generateStencilBuffer,s.generateDepthBuffer,e,e),s.generateMipMaps&&n.generateMipmap(n.TEXTURE_CUBE_MAP),this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=o,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer,r.width=e,r.height=e,r.isReady=!0,r.isCube=!0,r.samples=1,r.generateMipMaps=s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,r.format=s.format,this._internalTexturesCache.push(r),i.setTextures(r),i},Pi.prototype.setDepthStencilTexture=function(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,s):this._setTexture(e,null,void 0,void 0,s))};const Gn={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class Vn{constructor(e,t=Gn){this._fullscreenViewport=new ii(0,0,1,1);const i=t.positions??Gn.positions,s=t.indices??Gn.indices;this.engine=e,this._vertexBuffers={[li.PositionKind]:new li(e,i,li.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(s);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){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,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(tt.MATERIAL_TriangleFillMode,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){const e=this._vertexBuffers[li.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[li.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class Xn{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new g;const i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add((()=>{this.effect.setFloat2("scale",1,1)})));const s=e.defines?e.defines.join("\n"):"";this._drawWrapper=new Ti(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],i,e.samplerNames,s,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new mt(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,s,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add((()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})))}dispose(e=!0){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),e&&this.effect.dispose()}}const Hn="passPixelShader",zn="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";it.ShadersStore[Hn]=zn;const Wn={name:Hn,shader:zn};class Yn{static _CreateDumpRenderer(){if(!Yn._DumpToolsEngine){let e,t=null;const i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new Pi(e,!1,i)}catch(s){e=document.createElement("canvas"),t=new Pi(e,!1,i)}M.Instances.pop(),M.OnEnginesDisposedObservable.add((e=>{t&&e!==t&&!t.isDisposed&&0===M.Instances.length&&Yn.Dispose()})),t.getCaps().parallelShaderCompile=void 0;const s=new Vn(t),n=new Xn({engine:t,name:Wn.name,fragmentShader:Wn.shader,samplerNames:["textureSampler"]});Yn._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:n}}return Yn._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,n="image/png",r,a){const o=await i.readPixels(0,0,e,t),l=new Uint8Array(o.buffer);Yn.DumpData(e,t,l,s,n,r,!0,void 0,a)}static DumpDataAsync(e,t,i,s="image/png",n,r=!1,a=!1,o){return new Promise((l=>{Yn.DumpData(e,t,i,(e=>l(e)),s,n,r,a,o)}))}static DumpData(e,t,i,s,n="image/png",r,a=!1,o=!1,l){const h=Yn._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){const e=new Uint8Array(i.length);let t=i.length;for(;t--;){const s=i[t];e[t]=Math.round(255*q.Clamp(s))}i=e}const c=h.engine.createRawTexture(i,e,t,tt.TEXTUREFORMAT_RGBA,!1,!a,tt.TEXTURE_NEAREST_NEAREST);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",c),h.renderer.draw(),o?Qt.ToBlob(h.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;s&&s(t)},t.readAsArrayBuffer(e)}),n,l):Qt.EncodeScreenshotCanvasData(h.canvas,s,n,r,l),c.dispose()}static Dispose(){Yn._DumpToolsEngine&&(Yn._DumpToolsEngine.wrapper.dispose(),Yn._DumpToolsEngine.renderer.dispose(),Yn._DumpToolsEngine.engine.dispose()),Yn._DumpToolsEngine=null}}Qt.DumpData=Yn.DumpData,Qt.DumpDataAsync=Yn.DumpDataAsync,Qt.DumpFramebuffer=Yn.DumpFramebuffer,mt.prototype.setDepthStencilTexture=function(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)};class Kn extends wn{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=I(e,this._renderListHasChanged)),this._renderList=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)}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)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;i=Array.isArray(e)?e:[e];for(let e=0;e<i.length;++e)for(let s=0;s<this._renderPassIds.length;++s)i[e].setMaterialForRenderPass(this._renderPassIds[s],void 0!==t?Array.isArray(t)?t[s]:t:void 0)}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(tt.MATERIAL_TextureDirtyFlag)}get boundingBoxSize(){return this._boundingBoxSize}get depthStencilTexture(){return this._renderTarget?._depthStencilTexture??null}constructor(e,t,i,s=!1,n=!0,r=tt.TEXTURETYPE_UNSIGNED_INT,a=!1,o=wn.TRILINEAR_SAMPLINGMODE,l=!0,h=!1,c=!1,u=tt.TEXTUREFORMAT_RGBA,d=!1,_,f,m=!1,p=!1){let E,T=!0;if("object"==typeof s){const e=s;s=!!e.generateMipMaps,n=e.doNotChangeAspectRatio??!0,r=e.type??tt.TEXTURETYPE_UNSIGNED_BYTE,a=!!e.isCube,o=e.samplingMode??wn.TRILINEAR_SAMPLINGMODE,l=e.generateDepthBuffer??!0,h=!!e.generateStencilBuffer,c=!!e.isMulti,u=e.format??tt.TEXTUREFORMAT_RGBA,d=!!e.delayAllocation,_=e.samples,f=e.creationFlags,m=!!e.noColorAttachment,p=!!e.useSRGBBuffer,E=e.colorAttachment,T=e.gammaSpace??T}if(super(null,i,!s,void 0,o,void 0,void 0,void 0,void 0,u),this._unObserveRenderList=null,this._renderListHasChanged=(e,t)=>{const i=this._renderList?this._renderList.length:0;(0===t&&i>0||0===i)&&this.getScene()?.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new g,this.onAfterUnbindObservable=new g,this.onBeforeRenderObservable=new g,this.onAfterRenderObservable=new g,this.onClearObservable=new g,this.onResizeObservable=new g,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=B.Zero(),!(i=this.getScene()))return;const A=this.getScene().getEngine();this._gammaSpace=T,this._coordinatesMode=wn.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=a,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=A.onResizeObservable.add((()=>{})),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=n,this._renderingManager=new hn(i),this._renderingManager._useSceneAutoClearSetup=!0,c||(this._renderTargetOptions={generateMipMaps:s,type:r,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:_,creationFlags:f,noColorAttachment:m,useSRGBBuffer:p,colorAttachment:E,label:this.name},this.samplingMode===wn.NEAREST_SAMPLINGMODE&&(this.wrapU=wn.CLAMP_ADDRESSMODE,this.wrapV=wn.CLAMP_ADDRESSMODE),d||(a?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=wn.INVCUBIC_MODE,this._textureMatrix=G.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==_&&(this.samples=_)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,n=tt.TEXTUREFORMAT_DEPTH32_FLOAT,r){this._renderTarget?.createDepthStencilTexture(e,t,i,s,n,r)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t<this._renderPassIds.length;++t)e.releaseRenderPassId(this._renderPassIds[t])}this._renderPassIds=[]}_createRenderPassId(){this._releaseRenderPassId();const e=this._scene.getEngine(),t=this._isCubeData?6:this.getRenderLayers()||1;for(let i=0;i<t;++i)this._renderPassIds[i]=e.createRenderPassId(`RenderTargetTexture - ${this.name}#${i}`)}_processSizeParameter(e,t=!0){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;t&&this._createRenderPassId()}get samples(){return this._renderTarget?.samples??this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}resetRefreshCounter(){this._currentRefreshId=-1}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}addPostProcess(e){if(!this._postProcessManager){const e=this.getScene();if(!e)return;this._postProcessManager=new an(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))}_shouldRender(){return-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}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 i=this.getScene();i&&(this._processSizeParameter(e,!1),this._renderTarget=t?i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):i.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(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){const s=this.getScene();if(!s)return i;const n=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let e=0;e<this._waitingRenderList.length;e++){const t=this._waitingRenderList[e],i=s.getMeshById(t);i&&this.renderList.push(i)}}this._waitingRenderList=void 0}if(this.renderListPredicate){this.renderList?this.renderList.length=0:this.renderList=[];const e=this.getScene();if(!e)return i;const t=e.meshes;for(let e=0;e<t.length;e++){const i=t[e];this.renderListPredicate(i)&&this.renderList.push(i)}}const r=n.currentRenderPassId;this.onBeforeBindObservable.notifyObservers(this);const a=this.activeCamera??s.activeCamera,o=s.activeCamera;a&&(a!==s.activeCamera&&(s.setTransformMatrix(a.getViewMatrix(),a.getProjectionMatrix(!0)),s.activeCamera=a),n.setViewport(a.rigParent?a.rigParent.viewport:a.viewport,this.getRenderWidth(),this.getRenderHeight())),this._defaultRenderListPrepared=!1;let l=i;if(i){s.getViewMatrix()||s.updateTransformMatrix();const e=this.is2DArray||this.is3D?this.getRenderLayers():this.isCube?6:1;for(let t=0;t<e&&l;t++){let e=null;const r=this.renderList?this.renderList:s.getActiveMeshes().data,a=this.renderList?this.renderList.length:s.getActiveMeshes().length;n.currentRenderPassId=this._renderPassIds[t],this.onBeforeRenderObservable.notifyObservers(t),this.getCustomRenderList&&(e=this.getCustomRenderList(t,r,a)),e||(e=r),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0);for(let t=0;t<e.length&&l;++t){const s=e[t];if(s.isEnabled()&&!s.isBlocked&&s.isVisible&&s.subMeshes)if(this.customIsReadyFunction){if(!this.customIsReadyFunction(s,this.refreshRate,i)){l=!1;continue}}else if(!s.isReady(!0)){l=!1;continue}}this.onAfterRenderObservable.notifyObservers(t),(this.is2DArray||this.is3D||this.isCube)&&(s.incrementRenderId(),s.resetCachedMaterial())}}else if(!this.is2DArray&&!this.is3D||this.isMulti)if(this.isCube&&!this.isMulti)for(let i=0;i<6;i++)this._renderToTarget(i,e,t,void 0,a),s.incrementRenderId(),s.resetCachedMaterial();else this._renderToTarget(0,e,t,void 0,a);else for(let i=0;i<this.getRenderLayers();i++)this._renderToTarget(0,e,t,i,a),s.incrementRenderId(),s.resetCachedMaterial();return this.onAfterUnbindObservable.notifyObservers(this),n.currentRenderPassId=r,o&&(s.activeCamera=o,this.activeCamera&&this.activeCamera!==s.activeCamera&&s.setTransformMatrix(s.activeCamera.getViewMatrix(),s.activeCamera.getProjectionMatrix(!0)),n.setViewport(s.activeCamera.viewport)),s.resetCachedMaterial(),l}_bestReflectionRenderTargetDimension(e,t){const i=e*t,s=Wt(i+16384/(128+i));return Math.min(Kt(e),s)}_prepareRenderingManager(e,t,i,s){const n=this.getScene();if(!n)return;this._renderingManager.reset();const r=n.getRenderId();for(let a=0;a<t;a++){const t=e[a];if(t&&!t.isBlocked){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(t,this.refreshRate,!1)){this.resetRefreshCounter();continue}}else if(!t.isReady(0===this.refreshRate)){this.resetRefreshCounter();continue}if(!t._internalAbstractMeshDataInfo._currentLODIsUpToDate&&n.activeCamera&&(t._internalAbstractMeshDataInfo._currentLOD=n.customLODSelector?n.customLODSelector(t,this.activeCamera||n.activeCamera):t.getLOD(this.activeCamera||n.activeCamera),t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0),!t._internalAbstractMeshDataInfo._currentLOD)continue;let e,a=t._internalAbstractMeshDataInfo._currentLOD;if(a._preActivateForIntermediateRendering(r),e=!(!s||!i)&&!(t.layerMask&i.layerMask),t.isEnabled()&&t.isVisible&&t.subMeshes&&!e){if(a!==t&&a._activate(r,!0),t._activate(r,!0)&&t.subMeshes.length){t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(a=t):a._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!1,a._internalAbstractMeshDataInfo._isActiveIntermediate=!0;for(let e=0;e<a.subMeshes.length;e++){const t=a.subMeshes[e];this._renderingManager.dispatch(t,a)}}t._postActivate()}}}for(let e=0;e<n.particleSystems.length;e++){const t=n.particleSystems[e],i=t.emitter;t.isStarted()&&i&&(!i.position||i.isEnabled())&&this._renderingManager.dispatchParticles(t)}}_bindFrameBuffer(e=0,t=0){const i=this.getScene();if(!i)return;const s=i.getEngine();this._renderTarget&&s.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,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):s&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,n=null){const r=this.getScene();if(!r)return;const a=r.getEngine();a._debugPushGroup?.(`render to face #${e} layer #${s}`,1),this._prepareFrame(r,e,s,t),this.is2DArray||this.is3D?(a.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(a.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e));if(a.snapshotRendering&&a.snapshotRenderingMode===tt.SNAPSHOTRENDERING_FAST)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):this.skipInitialClear||a.clear(this.clearColor||r.clearColor,!0,!0,!0);else{let o=null;const l=this.renderList?this.renderList:r.getActiveMeshes().data,h=this.renderList?this.renderList.length:r.getActiveMeshes().length;this.getCustomRenderList&&(o=this.getCustomRenderList(this.is2DArray||this.is3D?s:e,l,h)),o?this._prepareRenderingManager(o,o.length,n,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(l,h,n,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),o=l);for(const t of r._beforeRenderTargetClearStage)t.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):this.skipInitialClear||a.clear(this.clearColor||r.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||r.updateTransformMatrix(!0);for(const t of r._beforeRenderTargetDrawStage)t.action(this,e,s);this._renderingManager.render(this.customRenderFunction,o,this.renderParticles,this.renderSprites);for(const t of r._afterRenderTargetDrawStage)t.action(this,e,s);const c=this._texture?.generateMipMaps??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&r.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const t of r._afterRenderTargetPostProcessStage)t.action(this,e,s);this._texture&&(this._texture.generateMipMaps=c),this._doNotChangeAspectRatio||r.updateTransformMatrix(!0),i&&Yn.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),a)}this._unbindFrameBuffer(a,e),this._texture&&this.isCube&&5===e&&a.generateMipMapsForCubemap(this._texture,!0),a._debugPopGroup?.(1)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new Kn(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.onAfterRenderObservable.clear(),this.onAfterUnbindObservable.clear(),this.onBeforeBindObservable.clear(),this.onBeforeRenderObservable.clear(),this._postProcessManager&&(this._postProcessManager.dispose(),this._postProcessManager=null),this._prePassRenderTarget&&this._prePassRenderTarget.dispose(),this._releaseRenderPassId(),this.clearPostProcesses(!0),this._resizeObserver&&(this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.renderList=null;const e=this.getScene();if(!e)return;let t=e.customRenderTargets.indexOf(this);t>=0&&e.customRenderTargets.splice(t,1);for(const i of e.cameras)t=i.customRenderTargets.indexOf(this),t>=0&&i.customRenderTargets.splice(t,1);this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===Kn.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=Kn.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}Kn.REFRESHRATE_RENDER_ONCE=0,Kn.REFRESHRATE_RENDER_ONEVERYFRAME=1,Kn.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,wn._CreateRenderTargetTexture=(e,t,i,s,n)=>new Kn(e,t,i,s);it.ShadersStore.passCubePixelShader="varying vec2 vUV;uniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";class qn extends kn{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,n,r,a=tt.TEXTURETYPE_UNSIGNED_INT,o=!1){super(e,"pass",null,null,t,i,s,n,r,void 0,a,void 0,null,o)}static _Parse(e,t,i,s){return se.Parse((()=>new qn(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,s)}}C("BABYLON.PassPostProcess",qn),St._RescalePostProcessFactory=e=>new qn("rescale",1,null,tt.TEXTURE_BILINEAR_SAMPLINGMODE,e,!1,tt.TEXTURETYPE_UNSIGNED_INT);it.ShadersStore.lodPixelShader="#extension GL_EXT_shader_texture_lod : enable\nprecision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform sampler2D textureSampler;uniform float lod;uniform vec2 texSize;uniform bool gamma;void main(void)\n{gl_FragColor=textureLod(textureSampler,vUV,lod);if (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";let Qn,jn;function Zn(e){Qn||(Qn=new Float32Array(1),jn=new Int32Array(Qn.buffer)),Qn[0]=e;const t=jn[0];let i=t>>16&32768,s=t>>12&2047;const n=t>>23&255;return n<103?i:n>142?(i|=31744,i|=(255==n?0:1)&&8388607&t,i):n<113?(s|=2048,i|=(s>>114-n)+(s>>113-n&1),i):(i|=n-112<<10|s>>1,i+=1&s,i)}function $n(e){const t=(32768&e)>>15,i=(31744&e)>>10,s=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(s/Math.pow(2,10)):31==i?s?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+s/Math.pow(2,10))}it.ShadersStore.lodCubePixelShader="precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform bool gamma;void main(void)\n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod);\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod);\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod);\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod);\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod);\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod);\n#endif\nif (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";class Jn{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),s=i.getCaps(),n=t.isReady;let r=!1;s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?(r=!0,t.type=tt.TEXTURETYPE_HALF_FLOAT):s.textureFloatRender&&s.textureFloatLinearFiltering&&(r=!0,t.type=tt.TEXTURETYPE_FLOAT),r&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const a=()=>{const s=new kn("rgbdDecode","rgbdDecode",null,null,1,null,tt.TEXTURE_TRILINEAR_SAMPLINGMODE,i,!1,void 0,t.type,void 0,null,!1);s.externalTextureSamplerBinding=!0;const n=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:tt.TEXTUREFORMAT_RGBA});s.getEffect().executeWhenCompiled((()=>{s.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([s],n,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),s&&s.dispose(),n._swapAndDie(t),t.isReady=!0}))};r&&(n?a():e.onLoadObservable.addOnce(a))}static EncodeTextureToRGBD(e,t,i=tt.TEXTURETYPE_UNSIGNED_BYTE){return function(e,t,i,s,n,r,a,o){const l=t.getEngine();return t.isReady=!1,n=n??t.samplingMode,s=s??t.type,r=r??t.format,a=a??t.width,o=o??t.height,-1===s&&(s=tt.TEXTURETYPE_UNSIGNED_BYTE),new Promise((h=>{const c=new kn("postprocess",e,null,null,1,null,n,l,!1,void 0,s,void 0,null,!1,r);c.externalTextureSamplerBinding=!0;const u=l.createRenderTargetTexture({width:a,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:n,type:s,format:r});c.getEffect().executeWhenCompiled((()=>{c.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([c],u,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),c&&c.dispose(),u._swapAndDie(t),t.type=s,t.format=tt.TEXTUREFORMAT_RGBA,t.isReady=!0,h(t)}))}))}("rgbdEncode",e,t,i,tt.TEXTURE_NEAREST_SAMPLINGMODE,tt.TEXTUREFORMAT_RGBA)}}let er=0;const tr=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const s=wn.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+er++,e,!0,!1,wn.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const n=e.getEngine().getLoadedTexturesCache(),r=n.indexOf(s.getInternalTexture());-1!==r&&n.splice(r,1),s.isRGBD=!0,s.wrapU=wn.CLAMP_ADDRESSMODE,s.wrapV=wn.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=s,e.useDelayedTextureLoading=t,Jn.ExpandRGBDTexture(s);const a=e.getEngine().onContextRestoredObservable.add((()=>{s.isRGBD=!0;const t=e.onBeforeRenderObservable.add((()=>{s.isReady()&&(e.onBeforeRenderObservable.remove(t),Jn.ExpandRGBDTexture(s))}))}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(a)}))}return e.environmentBRDFTexture};class ir{constructor(e){if(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=!1,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 i=this._keys[t];if(this[i]!==e[i])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 i=this._keys[t];e[i]=this[i]}}reset(){this._keys.forEach((e=>this._setDefaultValue(e)))}_setDefaultValue(e){const t=this._externalProperties?.[e]?.type??typeof this[e],i=this._externalProperties?.[e]?.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!1}}toString(){let e="";for(let t=0;t<this._keys.length;t++){const i=this._keys[t],s=this[i];switch(typeof s){case"number":case"string":e+="#define "+i+" "+s+"\n";break;default:s&&(e+="#define "+i+"\n")}}return e}}const sr=new RegExp("^([gimus]+)!");class nr{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let t=0;t<this._plugins.length;++t)if(this._plugins[t].name===e.name)return!1;if(this._material._uniformBufferLayoutBuilt)throw`The plugin "${e.name}" can't be added to the material "${this._material.name}" because this material has already been used for rendering! Please add plugins to materials before any rendering with this material occurs.`;const t=e.getClassName();nr._MaterialPluginClassToMainDefine[t]||(nr._MaterialPluginClassToMainDefine[t]="MATERIALPLUGIN_"+ ++nr._MaterialPluginCounter),this._material._callbackPluginEventGeneric=(e,t)=>this._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort(((e,t)=>e.priority-t.priority)),this._codeInjectionPoints={};const i={};i[nr._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const e of this._plugins)e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t<this._plugins.length;++t)if(this._plugins[t].name===e)return this._plugins[t];return null}_handlePluginEventIsReadyForSubMesh(e){let t=!0;for(const i of this._activePlugins)t=t&&i.isReadyForSubMesh(e.defines,this._scene,this._engine,e.subMesh);e.isReadyForSubMesh=t}_handlePluginEventPrepareDefinesBeforeAttributes(e){for(const t of this._activePlugins)t.prepareDefinesBeforeAttributes(e.defines,this._scene,e.mesh)}_handlePluginEventPrepareDefines(e){for(const t of this._activePlugins)t.prepareDefines(e.defines,this._scene,e.mesh)}_handlePluginEventHardBindForSubMesh(e){for(const t of this._activePluginsForExtraEvents)t.hardBindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventBindForSubMesh(e){for(const t of this._activePlugins)t.bindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventHasRenderTargetTextures(e){let t=!1;for(const e of this._activePluginsForExtraEvents)if(t=e.hasRenderTargetTextures(),t)break;e.hasRenderTargetTextures=t}_handlePluginEventFillRenderTargetTextures(e){for(const t of this._activePluginsForExtraEvents)t.fillRenderTargetTextures(e.renderTargets)}_handlePluginEvent(e,t){switch(e){case 512:{const e=t;for(const t of this._activePlugins)t.getActiveTextures(e.activeTextures);break}case 256:{const e=t;for(const t of this._activePlugins)t.getAnimatables(e.animatables);break}case 1024:{const e=t;let i=!1;for(const t of this._activePlugins)if(i=t.hasTexture(e.texture),i)break;e.hasTexture=i;break}case 2:{const e=t;for(const t of this._plugins)t.dispose(e.forceDisposeTextures);break}case 4:t.defineNames=this._defineNamesFromPlugins;break;case 128:{const e=t;for(const t of this._activePlugins)e.fallbackRank=t.addFallbacks(e.defines,e.fallbacks,e.fallbackRank),t.getAttributes(e.attributes,this._scene,e.mesh);this._uniformList.length>0&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e,e.customCode);break}case 8:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const t of this._plugins){const i=t.getUniforms();if(i){if(i.ubo)for(const t of i.ubo){if(t.size&&t.type){const i=t.arraySize??0;e.ubo.addUniform(t.name,t.size,i),this._uboDeclaration+=`${t.type} ${t.name}${i>0?`[${i}]`:""};\n`}this._uniformList.push(t.name)}i.vertex&&(this._vertexDeclaration+=i.vertex+"\n"),i.fragment&&(this._fragmentDeclaration+=i.fragment+"\n")}t.getSamplers(this._samplerList),t.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,s)=>{t&&(s=t(i,s)),this._uboDeclaration&&(s=s.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(s=s.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(s=s.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const n=this._codeInjectionPoints?.[i];if(!n)return s;let r=null;for(let t in n){let n="";for(const s of this._activePlugins){let a=s.getCustomCode(i)?.[t];if(a){if(s.resolveIncludes){if(null===r){const t=0;r={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:it.GetShadersRepository(t),includesShadersStore:it.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}r.isFragment="fragment"===i,$e(a,r,(e=>a=e))}n+=a+"\n"}}if(n.length>0)if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{const i=sr.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}e.indexOf("g")<0&&(e+="g");const i=s,r=new RegExp(t,e);let a=r.exec(i);for(;null!==a;){let e=n;for(let t=0;t<a.length;++t)e=e.replace("$"+t,a[t]);s=s.replace(a[0],e),a=r.exec(i)}}else{const e="#define "+t;s=s.replace(e,"\n"+n+"\n"+e)}}return s}}}nr._MaterialPluginClassToMainDefine={},nr._MaterialPluginCounter=0,M.OnEnginesDisposedObservable.add((()=>{rr.length=0,ls.OnEventObservable.remove(ar),ar=null}));const rr=[];let ar=null;class or{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,s,n=!0,r=!1,a=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=a,e.pluginManager||(e.pluginManager=new nr(e),e.onDisposeObservable.add((()=>{e.pluginManager=void 0}))),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,n&&this._pluginManager._addPlugin(this),r&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[tt.MATERIAL_AllDirtyFlag]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,s){return!0}hardBindForSubMesh(e,t,i,s){}bindForSubMesh(e,t,i,s){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;const i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){se.Clone((()=>e),this)}serialize(){return se.Serialize(this)}parse(e,t,i){se.Parse((()=>this),e,t,i)}}e([a()],or.prototype,"name",void 0),e([a()],or.prototype,"priority",void 0),e([a()],or.prototype,"resolveIncludes",void 0),e([a()],or.prototype,"registerForExtraEvents",void 0),C("BABYLON.MaterialPluginBase",or);class lr extends ir{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1}}class hr extends or{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new lr,t),this._useEnergyConservation=hr.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=hr.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=hr.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=hr.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=hr.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=hr.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=hr.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=hr.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[tt.MATERIAL_MiscDirtyFlag],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation}getClassName(){return"PBRBRDFConfiguration"}}hr.DEFAULT_USE_ENERGY_CONSERVATION=!0,hr.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,hr.DEFAULT_USE_SPHERICAL_HARMONICS=!0,hr.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,e([a(),r("_markAllSubMeshesAsMiscDirty")],hr.prototype,"useEnergyConservation",void 0),e([a(),r("_markAllSubMeshesAsMiscDirty")],hr.prototype,"useSmithVisibilityHeightCorrelated",void 0),e([a(),r("_markAllSubMeshesAsMiscDirty")],hr.prototype,"useSphericalHarmonics",void 0),e([a(),r("_markAllSubMeshesAsMiscDirty")],hr.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);class cr{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,s,n){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(tt.PREPASS_VELOCITY_TEXTURE_TYPE)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=s.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const n=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=n.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==n.frameId&&(this._lastUpdateFrameId=n.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=s.clone()}}}class ur extends ls{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new G,this._storeEffectOnSubMeshes=i}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,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,s=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,s)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}class dr{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_FresnelDirtyFlag))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get TranslucencyIntensityTextureEnabled(){return this._TranslucencyIntensityTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get TranslucencyColorTextureEnabled(){return this._TranslucencyColorTextureEnabled}static set TranslucencyColorTextureEnabled(e){this._TranslucencyColorTextureEnabled!==e&&(this._TranslucencyColorTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,Ui.MarkAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag))}}dr._DiffuseTextureEnabled=!0,dr._DetailTextureEnabled=!0,dr._DecalMapEnabled=!0,dr._AmbientTextureEnabled=!0,dr._OpacityTextureEnabled=!0,dr._ReflectionTextureEnabled=!0,dr._EmissiveTextureEnabled=!0,dr._SpecularTextureEnabled=!0,dr._BumpTextureEnabled=!0,dr._LightmapTextureEnabled=!0,dr._RefractionTextureEnabled=!0,dr._ColorGradingTextureEnabled=!0,dr._FresnelEnabled=!0,dr._ClearCoatTextureEnabled=!0,dr._ClearCoatBumpTextureEnabled=!0,dr._ClearCoatTintTextureEnabled=!0,dr._SheenTextureEnabled=!0,dr._AnisotropicTextureEnabled=!0,dr._ThicknessTextureEnabled=!0,dr._RefractionIntensityTextureEnabled=!0,dr._TranslucencyIntensityTextureEnabled=!0,dr._TranslucencyColorTextureEnabled=!0,dr._IridescenceTextureEnabled=!0;const _r=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],fr=[()=>1,e=>e.y,e=>e.z,e=>e.x,e=>e.x*e.y,e=>e.y*e.z,e=>3*e.z*e.z-1,e=>e.x*e.z,e=>e.x*e.x-e.y*e.y],mr=(e,t)=>_r[e]*fr[e](t),pr=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4];class gr{constructor(){this.preScaled=!1,this.l00=B.Zero(),this.l1_1=B.Zero(),this.l10=B.Zero(),this.l11=B.Zero(),this.l2_2=B.Zero(),this.l2_1=B.Zero(),this.l20=B.Zero(),this.l21=B.Zero(),this.l22=B.Zero()}addLight(e,t,i){X.Vector3[0].set(t.r,t.g,t.b);const s=X.Vector3[0],n=X.Vector3[1];s.scaleToRef(i,n),n.scaleToRef(mr(0,e),X.Vector3[2]),this.l00.addInPlace(X.Vector3[2]),n.scaleToRef(mr(1,e),X.Vector3[2]),this.l1_1.addInPlace(X.Vector3[2]),n.scaleToRef(mr(2,e),X.Vector3[2]),this.l10.addInPlace(X.Vector3[2]),n.scaleToRef(mr(3,e),X.Vector3[2]),this.l11.addInPlace(X.Vector3[2]),n.scaleToRef(mr(4,e),X.Vector3[2]),this.l2_2.addInPlace(X.Vector3[2]),n.scaleToRef(mr(5,e),X.Vector3[2]),this.l2_1.addInPlace(X.Vector3[2]),n.scaleToRef(mr(6,e),X.Vector3[2]),this.l20.addInPlace(X.Vector3[2]),n.scaleToRef(mr(7,e),X.Vector3[2]),this.l21.addInPlace(X.Vector3[2]),n.scaleToRef(mr(8,e),X.Vector3[2]),this.l22.addInPlace(X.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(pr[0]),this.l1_1.scaleInPlace(pr[1]),this.l10.scaleInPlace(pr[2]),this.l11.scaleInPlace(pr[3]),this.l2_2.scaleInPlace(pr[4]),this.l2_1.scaleInPlace(pr[5]),this.l20.scaleInPlace(pr[6]),this.l21.scaleInPlace(pr[7]),this.l22.scaleInPlace(pr[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(_r[0]),this.l1_1.scaleInPlace(_r[1]),this.l10.scaleInPlace(_r[2]),this.l11.scaleInPlace(_r[3]),this.l2_2.scaleInPlace(_r[4]),this.l2_1.scaleInPlace(_r[5]),this.l20.scaleInPlace(_r[6]),this.l21.scaleInPlace(_r[7]),this.l22.scaleInPlace(_r[8])}updateFromArray(e){return B.FromArrayToRef(e[0],0,this.l00),B.FromArrayToRef(e[1],0,this.l1_1),B.FromArrayToRef(e[2],0,this.l10),B.FromArrayToRef(e[3],0,this.l11),B.FromArrayToRef(e[4],0,this.l2_2),B.FromArrayToRef(e[5],0,this.l2_1),B.FromArrayToRef(e[6],0,this.l20),B.FromArrayToRef(e[7],0,this.l21),B.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return B.FromFloatsToRef(e[0],e[1],e[2],this.l00),B.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),B.FromFloatsToRef(e[6],e[7],e[8],this.l10),B.FromFloatsToRef(e[9],e[10],e[11],this.l11),B.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),B.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),B.FromFloatsToRef(e[18],e[19],e[20],this.l20),B.FromFloatsToRef(e[21],e[22],e[23],this.l21),B.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new gr).updateFromArray(e)}static FromPolynomial(e){const t=new gr;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}}class Er{constructor(){this.x=B.Zero(),this.y=B.Zero(),this.z=B.Zero(),this.xx=B.Zero(),this.yy=B.Zero(),this.zz=B.Zero(),this.xy=B.Zero(),this.yz=B.Zero(),this.zx=B.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=gr.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){X.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=X.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),X.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),X.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(X.Vector3[0]).addInPlace(X.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(X.Vector3[0]).subtractInPlace(X.Vector3[1]),this.zz.copyFrom(e.l00),X.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(X.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return(new Er).updateFromHarmonics(e)}static FromArray(e){const t=new Er;return B.FromArrayToRef(e[0],0,t.x),B.FromArrayToRef(e[1],0,t.y),B.FromArrayToRef(e[2],0,t.z),B.FromArrayToRef(e[3],0,t.xx),B.FromArrayToRef(e[4],0,t.yy),B.FromArrayToRef(e[5],0,t.zz),B.FromArrayToRef(e[6],0,t.yz),B.FromArrayToRef(e[7],0,t.zx),B.FromArrayToRef(e[8],0,t.xy),t}}class Tr{constructor(e,t,i,s){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=s}}class Ar{static ConvertCubeMapTextureToSphericalPolynomial(e){if(!e.isCube)return null;e.getScene()?.getEngine().flushFramebuffer();const t=e.getSize().width,i=e.readPixels(0,void 0,void 0,!1),s=e.readPixels(1,void 0,void 0,!1);let n,r;e.isRenderTarget?(n=e.readPixels(3,void 0,void 0,!1),r=e.readPixels(2,void 0,void 0,!1)):(n=e.readPixels(2,void 0,void 0,!1),r=e.readPixels(3,void 0,void 0,!1));const a=e.readPixels(4,void 0,void 0,!1),o=e.readPixels(5,void 0,void 0,!1),l=e.gammaSpace,h=tt.TEXTUREFORMAT_RGBA;let c=tt.TEXTURETYPE_UNSIGNED_INT;return e.textureType!=tt.TEXTURETYPE_FLOAT&&e.textureType!=tt.TEXTURETYPE_HALF_FLOAT||(c=tt.TEXTURETYPE_FLOAT),new Promise((e=>{Promise.all([s,i,n,r,a,o]).then((([i,s,n,r,a,o])=>{const u={size:t,right:s,left:i,up:n,down:r,front:a,back:o,format:h,type:c,gammaSpace:l};e(this.ConvertCubeMapToSphericalPolynomial(u))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new gr;let i=0;const s=2/e.size,n=s,r=.5*s,a=r-1;for(let o=0;o<6;o++){const l=this._FileFaces[o],h=e[l.name];let c=a;const u=e.format===tt.TEXTUREFORMAT_RGBA?4:3;for(let o=0;o<e.size;o++){let d=a;for(let n=0;n<e.size;n++){const a=l.worldAxisForFileX.scale(d).add(l.worldAxisForFileY.scale(c)).add(l.worldAxisForNormal);a.normalize();const _=this._AreaElement(d-r,c-r)-this._AreaElement(d-r,c+r)-this._AreaElement(d+r,c-r)+this._AreaElement(d+r,c+r);let f=h[o*e.size*u+n*u+0],m=h[o*e.size*u+n*u+1],p=h[o*e.size*u+n*u+2];isNaN(f)&&(f=0),isNaN(m)&&(m=0),isNaN(p)&&(p=0),e.type===tt.TEXTURETYPE_UNSIGNED_INT&&(f/=255,m/=255,p/=255),e.gammaSpace&&(f=Math.pow(q.Clamp(f),T),m=Math.pow(q.Clamp(m),T),p=Math.pow(q.Clamp(p),T));const g=this.MAX_HDRI_VALUE;if(this.PRESERVE_CLAMPED_COLORS){const e=Math.max(f,m,p);if(e>g){const t=g/e;f*=t,m*=t,p*=t}}else f=q.Clamp(f,0,g),m=q.Clamp(m,0,g),p=q.Clamp(p,0,g);const E=new J(f,m,p);t.addLight(a,E,_),i+=_,d+=s}c+=n}}const o=6*(4*Math.PI)/6/i;return t.scaleInPlace(o),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),Er.FromHarmonics(t)}}Ar._FileFaces=[new Tr("right",new B(1,0,0),new B(0,0,-1),new B(0,-1,0)),new Tr("left",new B(-1,0,0),new B(0,0,1),new B(0,-1,0)),new Tr("up",new B(0,1,0),new B(1,0,0),new B(0,0,1)),new Tr("down",new B(0,-1,0),new B(1,0,0),new B(0,0,-1)),new Tr("front",new B(0,0,1),new B(1,0,0),new B(0,-1,0)),new Tr("back",new B(0,0,-1),new B(-1,0,0),new B(0,-1,0))],Ar.MAX_HDRI_VALUE=4096,Ar.PRESERVE_CLAMPED_COLORS=!1,Ln.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(Ln.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=Ar.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then((e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))),null}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});it.IncludesShadersStore.prePassDeclaration="#ifdef PREPASS\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;\n#ifdef PREPASS_DEPTH\nvarying highp vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nvarying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;\n#endif\n#endif\n";it.IncludesShadersStore.oitDeclaration="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out vec2 depth; \nlayout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor;\n#define MAX_DEPTH 99999.0\nhighp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler;\n#endif\n";it.IncludesShadersStore.decalFragmentDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;\n#endif\n";it.IncludesShadersStore.pbrFragmentDeclaration="uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor;\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REALTIME_FILTERING\nuniform vec2 vReflectionFilteringInfo;\n#endif\nuniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams;\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#endif\n#ifdef IRIDESCENCE\nuniform vec4 vIridescenceParams;\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\nuniform vec4 vSheenColor;\n#ifdef SHEEN_ROUGHNESS\nuniform float vSheenRoughness;\n#endif\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;\n#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\n#endif\n#ifdef SS_DISPERSION\nuniform float dispersion;\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;\n#endif\nuniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;uniform vec4 vTranslucencyColor;\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nuniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;\n#endif\n#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\n#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include<decalFragmentDeclaration>\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;\n#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";it.IncludesShadersStore.sceneUboDeclaration="layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nmat4 view;mat4 projection;vec4 vEyePosition;};\n";it.IncludesShadersStore.meshUboDeclaration="#ifdef WEBGL2\nuniform mat4 world;uniform float visibility;\n#else\nlayout(std140,column_major) uniform;uniform Mesh\n{mat4 world;float visibility;};\n#endif\n#define WORLD_UBO\n";it.IncludesShadersStore.pbrUboDeclaration="layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include<sceneUboDeclaration>\n#include<meshUboDeclaration>\n";it.IncludesShadersStore.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n";it.IncludesShadersStore.pbrFragmentExtraDeclaration="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include<mainUVVaryingDeclaration>[1..7]\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n";it.IncludesShadersStore.lightFragmentDeclaration="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};\n#else\nuniform highp sampler2DArray shadowTexture{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowTexture{X};\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowTexture{X};\n#else\nuniform sampler2D shadowTexture{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};\n#endif\n#endif\n";it.IncludesShadersStore.lightUboDeclaration="#ifdef LIGHT{X}\nuniform Light{X}\n{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;vec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;vec2 depthValues;} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};\n#else\nuniform highp sampler2DArray shadowTexture{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowTexture{X}; \n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowTexture{X};\n#else\nuniform sampler2D shadowTexture{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";it.IncludesShadersStore.samplerFragmentDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\nuniform sampler2D _SAMPLERNAME_Sampler;\n#endif\n";it.IncludesShadersStore.samplerFragmentAlternateDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n#endif\n";it.IncludesShadersStore.pbrFragmentSamplersDeclaration="#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform sampler2D sheenRoughnessSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh;\n#endif\n#endif\n#endif\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)\n#endif\n";it.IncludesShadersStore.imageProcessingDeclaration="#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#if defined(VIGNETTE) || defined(DITHER)\nuniform vec2 vInverseScreenSize;\n#endif\n#ifdef VIGNETTE\nuniform vec4 vignetteSettings1;uniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;uniform vec4 vCameraColorCurveNeutral;uniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef DITHER\nuniform float ditherIntensity;\n#endif\n";it.IncludesShadersStore.clipPlaneFragmentDeclaration="#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nvarying float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nvarying float fClipDistance6;\n#endif\n";it.IncludesShadersStore.logDepthDeclaration="#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;varying float vFragmentDepth;\n#endif\n";it.IncludesShadersStore.fogFragmentDeclaration="#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor()\n{float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x)\n{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}\nelse if (FOGMODE_EXP==vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}\nelse if (FOGMODE_EXP2==vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}\nreturn clamp(fogCoeff,0.0,1.0);}\n#endif\n";it.IncludesShadersStore.subSurfaceScatteringFunctions="bool testLightingForSSS(float diffusionProfile)\n{return diffusionProfile<1.;}";it.IncludesShadersStore.importanceSampling="vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { \nfloat phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}";it.IncludesShadersStore.pbrHelperFunctions="#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{return square(roughness)+MINIMUMVARIANCE;}\nfloat fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}\n#else\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}\n#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);}\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);return clearCoatAbsorption;}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;}\n#endif\n";it.IncludesShadersStore.imageProcessingFunctions="#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n/** \n* Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL.\n* sampler3dSetting.x=textureOffset (0.5/textureSize).\n* sampler3dSetting.y=textureSize.\n*/\n#define inline\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{float sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);float sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;sliceUV.x+=sliceInteger*sliceSize;sliceUV=saturate(sliceUV);vec4 slice0Color=texture2D(colorTransform,sliceUV);sliceUV.x+=sliceSize;sliceUV=saturate(sliceUV);vec4 slice1Color=texture2D(colorTransform,sliceUV);vec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;}\n#endif\n#if TONEMAPPING==3\nconst float PBRNeutralStartCompression=0.8-0.04;const float PBRNeutralDesaturation=0.15;vec3 PBRNeutralToneMapping( vec3 color ) {float x=min(color.r,min(color.g,color.b));float offset=x<0.08 ? x-6.25*x*x : 0.04;color-=offset;float peak=max(color.r,max(color.g,color.b));if (peak<PBRNeutralStartCompression) return color;float d=1.-PBRNeutralStartCompression;float newPeak=1.-d*d/(peak+d-PBRNeutralStartCompression);color*=newPeak/peak;float g=1.-1./(PBRNeutralDesaturation*(peak-newPeak)+1.);return mix(color,newPeak*vec3(1,1,1),g);}\n#endif\n#if TONEMAPPING==2\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);const mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108, 1.10813,-0.07276),\nvec3(-0.07367,-0.00605, 1.07602)\n);vec3 RRTAndODTFit(vec3 v)\n{vec3 a=v*(v+0.0245786)-0.000090537;vec3 b=v*(0.983729*v+0.4329510)+0.238081;return a/b;}\nvec3 ACESFitted(vec3 color)\n{color=ACESInputMat*color;color=RRTAndODTFit(color);color=ACESOutputMat*color;color=saturate(color);return color;}\n#endif\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS\nvec4 applyImageProcessing(vec4 result) {\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;vec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);float vignetteTerm=dot(vignetteXY1,vignetteXY1);float vignette=pow(vignetteTerm,vignetteSettings2.w);vec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);result.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#if TONEMAPPING==3\nresult.rgb=PBRNeutralToneMapping(result.rgb);\n#elif TONEMAPPING==2\nresult.rgb=ACESFitted(result.rgb);\n#elif TONEMAPPING==1\nconst float tonemappingCalibration=1.590579;result.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\nresult.rgb=toGammaSpace(result.rgb);result.rgb=saturate(result.rgb);\n#ifdef CONTRAST\nvec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);if (contrast<1.0) {result.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);} else {result.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);}\n#endif\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\nfloat luma=getLuminance(result.rgb);vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));vec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;result.rgb*=colorCurve.rgb;result.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\n#ifdef DITHER\nfloat rand=getRand(gl_FragCoord.xy*vInverseScreenSize);float dither=mix(-ditherIntensity,ditherIntensity,rand);result.rgb=saturate(result.rgb+vec3(dither));\n#endif\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND\nreturn result;}";it.IncludesShadersStore.shadowsFragmentFunctions="#ifdef SHADOWS\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\n#define inline\nfloat computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nreturn depth>shadow ? darkness : 1.0;}\n#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);}\n#define inline\nfloat computeShadowWithESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;}\n#define inline\nfloat computeShadowWithCloseESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;}\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define inline\nfloat computeShadowCSM(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);vec3 uvLayer=vec3(uv.x,uv.y,layer);float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uvLayer));\n#else\nfloat shadow=texture2D(shadowSampler,uvLayer).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}\n#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}}\n#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;\n#else\nif (TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#ifdef IS_NDC_HALF_ZRANGE\n#define ZINCLIP clipSpace.z\n#else\n#define ZINCLIP uvDepth.z\n#endif\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define GREATEST_LESS_THAN_ONE 0.99999994\n#define DISABLE_UNIFORMITY_ANALYSIS\n#define inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.)\n);const vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n#define inline\nfloat computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=texture2D(depthSampler,vec3(uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer)).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);vec4 filterRadius=vec4(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec4 offset=vec4(poissonSamplers[i],0.);offset=vec4(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);shadow+=texture2D(shadowSampler,uvDepthLayer+offset*filterRadius);}\nshadow/=float(pcfTapCount);shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));shadow=mix(darkness,1.,shadow);if (numBlocker<1.0) {return 1.0;}\nelse\n{return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=TEXTUREFUNC(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy),0.).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}}\nif (numBlocker<1.0) {return 1.0;}\nelse\n{float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);float filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec3 offset=poissonSamplers[i];offset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);shadow+=TEXTUREFUNC(shadowSampler,uvDepth+offset*filterRadius,0.);}\nshadow/=float(pcfTapCount);shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}}\n#define inline\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);}\n#define inline\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);}\n#define inline\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);}\n#define inline\nfloat computeShadowWithCSMPCSS16(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#define inline\nfloat computeShadowWithCSMPCSS32(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#define inline\nfloat computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#endif\n#endif\n";it.IncludesShadersStore.harmonicsFunctions="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nvec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00\n+ vSphericalL1_1*(normal.y)\n+ vSphericalL10*(normal.z)\n+ vSphericalL11*(normal.x)\n+ vSphericalL2_2*(normal.y*normal.x)\n+ vSphericalL2_1*(normal.y*normal.z)\n+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+ vSphericalL21*(normal.z*normal.x)\n+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}\n#else\nvec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;}\n#endif\n#endif\n";it.IncludesShadersStore.pbrDirectLightingSetupFunctions="struct preLightingInfo\n{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness;\n#ifdef IRIDESCENCE\nfloat iridescenceIntensity;\n#endif\n};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N,vec3 posW) {preLightingInfo result;result.lightOffset=lightData.xyz-posW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;}";it.IncludesShadersStore.pbrDirectLightingFalloffFunctions="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{return max(0.,1.0-length(lightOffset)/range);}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{return 1.0/maxEps(lightDistanceSquared);}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)\n{falloff=max(0.,pow(cosAngle,exponent));}\nreturn falloff;}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}";it.IncludesShadersStore.pbrBRDFFunctions="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;\n#endif\nreturn reflectance;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfloat getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)\n{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\n/**\n* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.\n* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table\n*/\nvec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}\n#endif\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\n#ifdef CLEARCOAT\nvec3 getR0RemappedForClearCoat(vec3 f0) {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturate(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t);\n#endif\n}\n#endif\n#ifdef IRIDESCENCE\nconst mat3 XYZ_TO_REC709=mat3(\n3.2404542,-0.9692660, 0.0556434,\n-1.5371385, 1.8760108,-0.2040259,\n-0.4985314, 0.0415560, 1.0572252\n);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}\nvec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));}\nfloat getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));}\nvec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;}\nvec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}\nfloat cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR<outsideIOR) phi12=PI;float phi21=PI-phi12;vec3 baseIOR=getIORTfromAirToSurfaceR0(clamp(baseF0,0.0,0.9999)); \nvec3 R1=getR0fromIORs(baseIOR,iridescenceIOR);vec3 R23=fresnelSchlickGGX(cosTheta2,R1,vec3(1.));vec3 phi23=vec3(0.0);if (baseIOR[0]<iridescenceIOR) phi23[0]=PI;if (baseIOR[1]<iridescenceIOR) phi23[1]=PI;if (baseIOR[2]<iridescenceIOR) phi23[2]=PI;float opd=2.0*iridescenceIOR*thinFilmThickness*cosTheta2;vec3 phi=vec3(phi21)+phi23;vec3 R123=clamp(R12*R23,1e-5,0.9999);vec3 r123=sqrt(R123);vec3 Rs=square(T121)*R23/(vec3(1.0)-R123);vec3 C0=R12+Rs;I=C0;vec3 Cm=Rs-T121;for (int m=1; m<=2; ++m)\n{Cm*=r123;vec3 Sm=2.0*evalSensitivity(float(m)*opd,float(m)*phi);I+=Cm*Sm;}\nreturn max(I,vec3(0.0));}\n#endif\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{float a2=square(alphaG);float d=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);}\n#ifdef SHEEN\nfloat normalDistributionFunction_CharlieSheen(float NdotH,float alphaG)\n{float invR=1./alphaG;float cos2h=NdotH*NdotH;float sin2h=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);}\n#endif\n#ifdef ANISOTROPIC\nfloat normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {float a2=alphaTB.x*alphaTB.y;vec3 v=vec3(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);float v2=dot(v,v);float w2=a2/v2;return a2*w2*w2*RECIPROCAL_PI;}\n#endif\n#ifdef BRDF_V_HEIGHT_CORRELATED\nfloat smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) {\n#ifdef MOBILE\nfloat GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);float GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL);\n#else\nfloat a2=alphaG*alphaG;float GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);float GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL);\n#endif\n}\n#else\nfloat smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG)\n{\n#ifdef MOBILE\nreturn 1.0/(dot+alphaG+(1.0-alphaG)*dot ));\n#else\nfloat alphaSquared=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));\n#endif\n}\nfloat smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG)\n{float visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;}\n#endif\n#ifdef ANISOTROPIC\nfloat smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {float lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));float lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));float v=0.5/(lambdaV+lambdaL);return v;}\n#endif\n#ifdef CLEARCOAT\nfloat visibility_Kelemen(float VdotH) {return 0.25/(VdotH*VdotH); }\n#endif\n#ifdef SHEEN\nfloat visibility_Ashikhmin(float NdotL,float NdotV)\n{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));}\n/* NOT USED\n#ifdef SHEEN_SOFTER\nfloat l(float x,float alphaG)\n{float oneMinusAlphaSq=(1.0-alphaG)*(1.0-alphaG);float a=mix(21.5473,25.3245,oneMinusAlphaSq);float b=mix(3.82987,3.32435,oneMinusAlphaSq);float c=mix(0.19823,0.16801,oneMinusAlphaSq);float d=mix(-1.97760,-1.27393,oneMinusAlphaSq);float e=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;}\nfloat lambdaSheen(float cosTheta,float alphaG)\n{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));}\nfloat visibility_CharlieSheen(float NdotL,float NdotV,float alphaG)\n{float G=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);}\n#endif\n*/\n#endif\nfloat diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {float diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));float diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));float diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;float fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;}\n#ifdef SS_TRANSLUCENCY\nvec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {vec3 S=1./maxEps(diffusionDistance);vec3 temp=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);}\nfloat computeWrappedDiffuseNdotL(float NdotL,float w) {float t=1.0+w;float invt2=1.0/square(t);return saturate((NdotL+w)*invt2);}\n#endif\n";it.IncludesShadersStore.hdrFilteringFunctions="#ifdef NUM_SAMPLES\n#if NUM_SAMPLES>0\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfloat radicalInverse_VdC(uint bits) \n{bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; }\nvec2 hammersley(uint i,uint N)\n{return vec2(float(i)/float(N),radicalInverse_VdC(i));}\n#else\nfloat vanDerCorpus(int n,int base)\n{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i)\n{if(n>0)\n{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}}\nreturn result;}\nvec2 hammersley(int i,int N)\n{return vec2(float(i)/float(N),vanDerCorpus(i,2));}\n#endif\nfloat log4(float x) {return log2(x)/2.;}\nconst float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.;\n#define inline\nvec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)\n{vec3 n=normalize(inputN);vec3 result=vec3(0.0);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfor(uint i=0u; i<NUM_SAMPLES; ++i)\n#else\nfor(int i=0; i<NUM_SAMPLES; ++i)\n#endif\n{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 Ls=hemisphereCosSample(Xi);Ls=normalize(Ls);vec3 Ns=vec3(0.,0.,1.);float NoL=dot(Ns,Ls);if (NoL>0.) {float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb;\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nresult+=c;}}\nresult=result*NUM_SAMPLES_FLOAT_INVERSED;return result;}\n#define inline\nvec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)\n{vec3 n=normalize(inputN);vec3 c=textureCube(inputTexture,n).rgb; \nif (alphaG==0.) {\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nreturn c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.;\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfor(uint i=0u; i<NUM_SAMPLES; ++i)\n#else\nfor(int i=0; i<NUM_SAMPLES; ++i)\n#endif\n{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 H=hemisphereImportanceSampleDggx(Xi,alphaG);float NoV=1.;float NoH=H.z;float NoH2=H.z*H.z;float NoL=2.*NoH2-1.;vec3 L=vec3(2.*NoH*H.x,2.*NoH*H.y,NoL);L=normalize(L);if (NoL>0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb;\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nresult+=c*NoL;}}\nresult=result/weight;return result;}}\n#endif\n#endif\n";it.IncludesShadersStore.pbrDirectLightingFunctions="#define CLEARCOATREFLECTANCE90 1.0\nstruct lightingInfo\n{vec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef CLEARCOAT\nvec4 clearCoat;\n#endif\n#ifdef SHEEN\nvec3 sheen;\n#endif\n};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) {\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\nfloat lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nvec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);}\nvec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix,vec3 posW){vec4 strq=textureProjectionMatrix*vec4(posW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);}\n#ifdef SS_TRANSLUCENCY\nvec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {float NdotL=absEps(info.NdotLUnclamped);float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;}\n#endif\n#ifdef SPECULARTERM\nvec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);\n#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\n#endif\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\n#ifdef BRDF_V_HEIGHT_CORRELATED\nfloat smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);\n#else\nfloat smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);\n#endif\nvec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n#ifdef ANISOTROPIC\nvec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);\n#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\n#endif\nfloat distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n#ifdef CLEARCOAT\nvec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4(\nclearCoatTerm*info.attenuation*NccdotL*lightColor,\n1.0-fresnel\n);}\nvec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;}\n#endif\n#ifdef SHEEN\nvec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER\nfloat visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG);\n#else */\nfloat visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */\nfloat sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n";it.IncludesShadersStore.pbrIBLFunctions="#if defined(REFLECTION) || defined(SS_REFRACTION)\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;}\nfloat getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);}\n#endif\n#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);}\n#endif\n";it.IncludesShadersStore.bumpFragmentMainFunctions="#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#if defined(WEBGL2) || defined(WEBGPU)\nmat4 toNormalMatrix(mat4 wMatrix)\n{mat4 ret=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]=vec4(0.,0.,0.,1.);return ret;}\n#else\nmat4 toNormalMatrix(mat4 m)\n{float\na00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3],\na10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3],\na20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3],\na30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3],\nb00=a00*a11-a01*a10,\nb01=a00*a12-a02*a10,\nb02=a00*a13-a03*a10,\nb03=a01*a12-a02*a11,\nb04=a01*a13-a03*a11,\nb05=a02*a13-a03*a12,\nb06=a20*a31-a21*a30,\nb07=a20*a32-a22*a30,\nb08=a20*a33-a23*a30,\nb09=a21*a32-a22*a31,\nb10=a21*a33-a23*a31,\nb11=a22*a33-a23*a32,\ndet=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;mat4 mi=mat4(\na11*b11-a12*b10+a13*b09,\na02*b10-a01*b11-a03*b09,\na31*b05-a32*b04+a33*b03,\na22*b04-a21*b05-a23*b03,\na12*b08-a10*b11-a13*b07,\na00*b11-a02*b08+a03*b07,\na32*b02-a30*b05-a33*b01,\na20*b05-a22*b02+a23*b01,\na10*b10-a11*b08+a13*b06,\na01*b08-a00*b10-a03*b06,\na30*b04-a31*b02+a33*b00,\na21*b02-a20*b04-a23*b00,\na11*b07-a10*b09-a12*b06,\na00*b09-a01*b07+a02*b06,\na31*b01-a30*b03-a32*b00,\na20*b03-a21*b01+a22*b00)/det;return mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0],\nmi[0][1],mi[1][1],mi[2][1],mi[3][1],\nmi[0][2],mi[1][2],mi[2][2],mi[3][2],\nmi[0][3],mi[1][3],mi[2][3],mi[3][3]);}\n#endif\n#endif\nvec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale)\n{\n#ifdef NORMALXYSCALE\nnormal=normalize(normal*vec3(scale,scale,1.0));\n#endif\nreturn normalize(cotangentFrame*normal);}\nvec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale)\n{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams)\n{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);}\n#endif\n";it.IncludesShadersStore.bumpFragmentFunctions="#if defined(BUMP)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)\n#endif\n#if defined(DETAIL)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)\n#endif\n#if defined(BUMP) && defined(PARALLAX)\nconst float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; i<iMaxSamples; i++)\n{currSampledHeight=texture2D(bumpSampler,texCoord+vCurrOffset).w;if (!keepWorking)\n{}\nelse if (currSampledHeight>currRayHeight)\n{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}\nelse\n{currRayHeight-=stepSize;vLastOffset=vCurrOffset;\n#ifdef PARALLAX_RHS\nvCurrOffset-=stepSize*vMaxOffset;\n#else\nvCurrOffset+=stepSize*vMaxOffset;\n#endif\nlastSampledHeight=currSampledHeight;}}\nreturn vCurrOffset;}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height;\n#ifdef PARALLAX_RHS\nreturn texCoordOffset;\n#else\nreturn -texCoordOffset;\n#endif\n}\n#endif\n";it.IncludesShadersStore.reflectionFunction="vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)\n{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0); }\nvec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)\n{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(1.0-s,t,0); }\nvec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);vec3 r=normalize(reflect(cameraToVertex,worldNormal));r=vec3(reflectionMatrix*vec4(r,0));float lon=atan(r.z,r.x);float lat=acos(r.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0);}\nvec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix)\n{vec3 viewDir=normalize(vec3(view*worldPos));vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));vec3 r=reflect(viewDir,viewNormal);r=vec3(reflectionMatrix*vec4(r,0));r.z=r.z-1.0;float m=2.0*length(r);return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);}\nvec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{vec3 viewDir=worldPos.xyz-eyePosition;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));}\nvec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;}\nvec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition)\n{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;}\nvec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix)\n{return vec3(reflectionMatrix*(view*worldPos));}\nvec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix)\n{return vec3(reflectionMatrix*vec4(positionW,1.));}\n#ifdef REFLECTION\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nreturn computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nreturn computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nreturn computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_CUBIC\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nreturn computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition);\n#else\nreturn computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn computeProjectionCoords(worldPos,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn computeSkyBoxCoords(vPositionUVW,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\n";it.IncludesShadersStore.decalFragment="#ifdef DECAL\n#ifdef GAMMADECAL\ndecalColor.rgb=toLinearSpace(decalColor.rgb);\n#endif\n#ifdef DECAL_SMOOTHALPHA\ndecalColor.a*=decalColor.a;\n#endif\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a);\n#endif\n";it.IncludesShadersStore.pbrBlockAlbedoOpacity="struct albedoOpacityOutParams\n{vec3 surfaceAlbedo;float alpha;};\n#define pbr_inline\nalbedoOpacityOutParams albedoOpacityBlock(\nin vec4 vAlbedoColor\n#ifdef ALBEDO\n,in vec4 albedoTexture\n,in vec2 albedoInfos\n#endif\n#ifdef OPACITY\n,in vec4 opacityMap\n,in vec2 vOpacityInfos\n#endif\n#ifdef DETAIL\n,in vec4 detailColor\n,in vec4 vDetailInfos\n#endif\n#ifdef DECAL\n,in vec4 decalColor\n,in vec4 vDecalInfos\n#endif \n)\n{albedoOpacityOutParams outParams;vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a;\n#ifdef ALBEDO\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\n#ifdef GAMMAALBEDO\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\n#else\nsurfaceAlbedo*=albedoTexture.rgb;\n#endif\nsurfaceAlbedo*=albedoInfos.y;\n#endif\n#ifndef DECAL_AFTER_DETAIL\n#include<decalFragment>\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nsurfaceAlbedo*=vColor.rgb;\n#endif\n#ifdef DETAIL\nfloat detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; \n#endif\n#ifdef DECAL_AFTER_DETAIL\n#include<decalFragment>\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALBEDO\n#ifdef OPACITY\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST \n#if DEBUGMODE != 88\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#endif\n#ifndef ALPHABLEND\nalpha=1.0;\n#endif\n#endif\n#endif\noutParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;return outParams;}\n";it.IncludesShadersStore.pbrBlockReflectivity="struct reflectivityOutParams\n{float microSurface;float roughness;vec3 surfaceReflectivityColor;\n#ifdef METALLICWORKFLOW\nvec3 surfaceAlbedo;\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\nvec3 ambientOcclusionColor;\n#endif\n#if DEBUGMODE>0\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap;\n#endif\n#ifndef FROSTBITE_REFLECTANCE\nvec3 metallicF0;\n#endif\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap;\n#endif\n#endif\n#endif\n};\n#define pbr_inline\nreflectivityOutParams reflectivityBlock(\nin vec4 vReflectivityColor\n#ifdef METALLICWORKFLOW\n,in vec3 surfaceAlbedo\n,in vec4 metallicReflectanceFactors\n#endif\n#ifdef REFLECTIVITY\n,in vec3 reflectivityInfos\n,in vec4 surfaceMetallicOrReflectivityColorMap\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n,in vec3 ambientOcclusionColorIn\n#endif\n#ifdef MICROSURFACEMAP\n,in vec4 microSurfaceTexel\n#endif\n#ifdef DETAIL\n,in vec4 detailColor\n,in vec4 vDetailInfos\n#endif\n)\n{reflectivityOutParams outParams;float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\n#if DEBUGMODE>0\noutParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap;\n#endif\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g;\n#endif\n#endif\n#endif\n#ifdef DETAIL\nfloat detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5));\n#endif\n#ifdef MICROSURFACEMAP\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n#if DEBUGMODE>0\noutParams.metallicRoughness=metallicRoughness;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS\nmicroSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo;\n#ifdef FROSTBITE_REFLECTANCE\noutParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r);\n#else\nvec3 metallicF0=metallicReflectanceFactors.rgb;\n#if DEBUGMODE>0\noutParams.metallicF0=metallicF0;\n#endif\noutParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r);\n#endif\n#else\n#ifdef REFLECTIVITY\nsurfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb;\n#if DEBUGMODE>0\noutParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap;\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE\n#endif\n#endif\n#endif\nmicroSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;return outParams;}\n";it.IncludesShadersStore.pbrBlockAmbientOcclusion="struct ambientOcclusionOutParams\n{vec3 ambientOcclusionColor;\n#if DEBUGMODE>0 && defined(AMBIENT)\nvec3 ambientOcclusionColorMap;\n#endif\n};ambientOcclusionOutParams ambientOcclusionBlock(\n#ifdef AMBIENT\nin vec3 ambientOcclusionColorMap_,\nin vec4 vAmbientInfos\n#endif\n)\n{ambientOcclusionOutParams outParams;vec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#if DEBUGMODE>0\noutParams.ambientOcclusionColorMap=ambientOcclusionColorMap;\n#endif\n#endif\noutParams.ambientOcclusionColor=ambientOcclusionColor;return outParams;}\n";it.IncludesShadersStore.pbrBlockAlphaFresnel="#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\nstruct alphaFresnelOutParams\n{float alpha;};\n#define pbr_inline\nalphaFresnelOutParams alphaFresnelBlock(\nin vec3 normalW,\nin vec3 viewDirectionW,\nin float alpha,\nin float microSurface\n)\n{alphaFresnelOutParams outParams;float opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (outParams.alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\noutParams.alpha=1.0;\n#endif\n#endif\nreturn outParams;}\n#endif\n#endif\n";it.IncludesShadersStore.pbrBlockAnisotropic="#ifdef ANISOTROPIC\nstruct anisotropicOutParams\n{float anisotropy;vec3 anisotropicTangent;vec3 anisotropicBitangent;vec3 anisotropicNormal;\n#if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE)\nvec3 anisotropyMapData;\n#endif\n};\n#define pbr_inline\nanisotropicOutParams anisotropicBlock(\nin vec3 vAnisotropy,\nin float roughness,\n#ifdef ANISOTROPIC_TEXTURE\nin vec3 anisotropyMapData,\n#endif\nin mat3 TBN,\nin vec3 normalW,\nin vec3 viewDirectionW\n)\n{anisotropicOutParams outParams;float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);\n#ifdef ANISOTROPIC_TEXTURE\nanisotropy*=anisotropyMapData.b;\n#if DEBUGMODE>0\noutParams.anisotropyMapData=anisotropyMapData;\n#endif\nanisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0;\n#ifdef ANISOTROPIC_LEGACY\nanisotropyDirection.rg*=anisotropyMapData.rg;\n#else\nanisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg);\n#endif\n#endif\nmat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);return outParams;}\n#endif\n";it.IncludesShadersStore.pbrBlockReflection="#ifdef REFLECTION\nstruct reflectionOutParams\n{vec4 environmentRadiance;vec3 environmentIrradiance;\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords;\n#else\nvec2 reflectionCoords;\n#endif\n#ifdef SS_TRANSLUCENCY\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nvec3 irradianceVector;\n#endif\n#endif\n#endif\n};\n#define pbr_inline\nvoid createReflectionCoords(\nin vec3 vPositionW,\nin vec3 normalW,\n#ifdef ANISOTROPIC\nin anisotropicOutParams anisotropicOut,\n#endif\n#ifdef REFLECTIONMAP_3D\nout vec3 reflectionCoords\n#else\nout vec2 reflectionCoords\n#endif\n)\n{\n#ifdef ANISOTROPIC\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal);\n#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nreflectionCoords=reflectionVector;\n#else\nreflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n}\n#define pbr_inline\n#define inline\nvoid sampleReflectionTexture(\nin float alphaG,\nin vec3 vReflectionMicrosurfaceInfos,\nin vec2 vReflectionInfos,\nin vec3 vReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nin float NdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nin float roughness,\n#endif\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\nconst vec3 reflectionCoords,\n#else\nin sampler2D reflectionSampler,\nconst vec2 reflectionCoords,\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\nin samplerCube reflectionSamplerHigh,\n#else\nin sampler2D reflectionSamplerLow,\nin sampler2D reflectionSamplerHigh,\n#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\n#endif\nout vec4 environmentRadiance\n)\n{\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#elif defined(LINEARSPECULARREFLECTION)\nfloat reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);\n#endif\n#ifdef LODBASEDMICROSFURACE\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\n#ifdef REALTIME_FILTERING\nenvironmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0);\n#else\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#endif\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentMid,\nlodReflectionNormalizedDoubled\n);} else {environmentRadiance=mix(\nenvironmentMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\nenvironmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;}\n#define pbr_inline\n#define inline\nreflectionOutParams reflectionBlock(\nin vec3 vPositionW\n,in vec3 normalW\n,in float alphaG\n,in vec3 vReflectionMicrosurfaceInfos\n,in vec2 vReflectionInfos\n,in vec3 vReflectionColor\n#ifdef ANISOTROPIC\n,in anisotropicOutParams anisotropicOut\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\n,in float NdotVUnclamped\n#endif\n#ifdef LINEARSPECULARREFLECTION\n,in float roughness\n#endif\n#ifdef REFLECTIONMAP_3D\n,in samplerCube reflectionSampler\n#else\n,in sampler2D reflectionSampler\n#endif\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\n,in vec3 vEnvironmentIrradiance\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n,in mat4 reflectionMatrix\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n#ifdef REFLECTIONMAP_3D\n,in samplerCube irradianceSampler\n#else\n,in sampler2D irradianceSampler\n#endif\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\n,in samplerCube reflectionSamplerLow\n,in samplerCube reflectionSamplerHigh\n#else\n,in sampler2D reflectionSamplerLow\n,in sampler2D reflectionSamplerHigh\n#endif\n#endif\n#ifdef REALTIME_FILTERING\n,in vec2 vReflectionFilteringInfo\n#endif\n)\n{reflectionOutParams outParams;vec4 environmentRadiance=vec4(0.,0.,0.,0.);\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=vec3(0.);\n#else\nvec2 reflectionCoords=vec2(0.);\n#endif\ncreateReflectionCoords(\nvPositionW,\nnormalW,\n#ifdef ANISOTROPIC\nanisotropicOut,\n#endif\nreflectionCoords\n);sampleReflectionTexture(\nalphaG,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nroughness,\n#endif\n#ifdef REFLECTIONMAP_3D\nreflectionSampler,\nreflectionCoords,\n#else\nreflectionSampler,\nreflectionCoords,\n#endif\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\nenvironmentRadiance\n);vec3 environmentIrradiance=vec3(0.,0.,0.);\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\n#ifdef ANISOTROPIC\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\n#ifdef INVERTCUBICMAP\nirradianceVector.y*=-1.0;\n#endif\n#if defined(REALTIME_FILTERING)\nenvironmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo);\n#else\nenvironmentIrradiance=computeEnvironmentIrradiance(irradianceVector);\n#endif\n#ifdef SS_TRANSLUCENCY\noutParams.irradianceVector=irradianceVector;\n#endif\n#endif\n#elif defined(USEIRRADIANCEMAP)\nvec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb;\n#ifdef RGBDREFLECTION\nenvironmentIrradiance.rgb=fromRGBD(environmentIrradiance4);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\nenvironmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;return outParams;}\n#endif\n";it.IncludesShadersStore.pbrBlockSheen="#ifdef SHEEN\nstruct sheenOutParams\n{float sheenIntensity;vec3 sheenColor;float sheenRoughness;\n#ifdef SHEEN_LINKWITHALBEDO\nvec3 surfaceAlbedo;\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfloat sheenAlbedoScaling;\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nvec3 finalSheenRadianceScaled;\n#endif\n#if DEBUGMODE>0\n#ifdef SHEEN_TEXTURE\nvec4 sheenMapData;\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nvec3 sheenEnvironmentReflectance;\n#endif\n#endif\n};\n#define pbr_inline\n#define inline\nsheenOutParams sheenBlock(\nin vec4 vSheenColor\n#ifdef SHEEN_ROUGHNESS\n,in float vSheenRoughness\n#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\n,in vec4 sheenMapRoughnessData\n#endif\n#endif\n,in float roughness\n#ifdef SHEEN_TEXTURE\n,in vec4 sheenMapData\n,in float sheenMapLevel\n#endif\n,in float reflectance\n#ifdef SHEEN_LINKWITHALBEDO\n,in vec3 baseColor\n,in vec3 surfaceAlbedo\n#endif\n#ifdef ENVIRONMENTBRDF\n,in float NdotV\n,in vec3 environmentBrdf\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\n,in vec2 AARoughnessFactors\n,in vec3 vReflectionMicrosurfaceInfos\n,in vec2 vReflectionInfos\n,in vec3 vReflectionColor\n,in vec4 vLightingIntensity\n#ifdef REFLECTIONMAP_3D\n,in samplerCube reflectionSampler\n,in vec3 reflectionCoords\n#else\n,in sampler2D reflectionSampler\n,in vec2 reflectionCoords\n#endif\n,in float NdotVUnclamped\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\n,in samplerCube reflectionSamplerLow\n,in samplerCube reflectionSamplerHigh\n#else\n,in sampler2D reflectionSamplerLow\n,in sampler2D reflectionSamplerHigh\n#endif\n#endif\n#ifdef REALTIME_FILTERING\n,in vec2 vReflectionFilteringInfo\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\n,in float seo\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\n,in float eho\n#endif\n#endif\n)\n{sheenOutParams outParams;float sheenIntensity=vSheenColor.a;\n#ifdef SHEEN_TEXTURE\n#if DEBUGMODE>0\noutParams.sheenMapData=sheenMapData;\n#endif\n#endif\n#ifdef SHEEN_LINKWITHALBEDO\nfloat sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor;\n#ifdef SHEEN_TEXTURE\nsheenIntensity*=sheenMapData.a;\n#endif\n#else\nvec3 sheenColor=vSheenColor.rgb;\n#ifdef SHEEN_TEXTURE\n#ifdef SHEEN_GAMMATEXTURE\nsheenColor.rgb*=toLinearSpace(sheenMapData.rgb);\n#else\nsheenColor.rgb*=sheenMapData.rgb;\n#endif\nsheenColor.rgb*=sheenMapLevel;\n#endif\n#ifdef SHEEN_ROUGHNESS\nfloat sheenRoughness=vSheenRoughness;\n#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE\n#if defined(SHEEN_TEXTURE)\nsheenRoughness*=sheenMapData.a;\n#endif\n#elif defined(SHEEN_TEXTURE_ROUGHNESS)\nsheenRoughness*=sheenMapRoughnessData.a;\n#endif\n#else\nfloat sheenRoughness=roughness;\n#ifdef SHEEN_TEXTURE\nsheenIntensity*=sheenMapData.a;\n#endif\n#endif\n#if !defined(SHEEN_ALBEDOSCALING)\nsheenIntensity*=(1.-reflectance);\n#endif\nsheenColor*=sheenIntensity;\n#endif\n#ifdef ENVIRONMENTBRDF\n/*#ifdef SHEEN_SOFTER\nvec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness));\n#else*/\n#ifdef SHEEN_ROUGHNESS\nvec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness);\n#else\nvec3 environmentSheenBrdf=environmentBrdf;\n#endif\n/*#endif*/\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nfloat sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness);\n#ifdef SPECULARAA\nsheenAlphaG+=AARoughnessFactors.y;\n#endif\nvec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture(\nsheenAlphaG,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nsheenRoughness,\n#endif\nreflectionSampler,\nreflectionCoords,\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\nenvironmentSheenRadiance\n);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf);\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nsheenEnvironmentReflectance*=seo;\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\nsheenEnvironmentReflectance*=eho;\n#endif\n#if DEBUGMODE>0\noutParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance;\n#endif\noutParams.finalSheenRadianceScaled=\nenvironmentSheenRadiance.rgb *\nsheenEnvironmentReflectance *\nvLightingIntensity.z;\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\noutParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b;\n#endif\noutParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;return outParams;}\n#endif\n";it.IncludesShadersStore.pbrBlockClearcoat="struct clearcoatOutParams\n{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness;\n#ifdef REFLECTION\nvec3 finalClearCoatRadianceScaled;\n#endif\n#ifdef CLEARCOAT_TINT\nvec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness;\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nvec3 energyConservationFactorClearCoat;\n#endif\n#if DEBUGMODE>0\n#ifdef CLEARCOAT_BUMP\nmat3 TBNClearCoat;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nvec2 clearCoatMapData;\n#endif\n#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\nvec4 clearCoatTintMapData;\n#endif\n#ifdef REFLECTION\nvec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance;\n#endif\nfloat clearCoatNdotV;\n#endif\n};\n#ifdef CLEARCOAT\n#define pbr_inline\n#define inline\nclearcoatOutParams clearcoatBlock(\nin vec3 vPositionW\n,in vec3 geometricNormalW\n,in vec3 viewDirectionW\n,in vec2 vClearCoatParams\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\n,in vec4 clearCoatMapRoughnessData\n#endif\n,in vec3 specularEnvironmentR0\n#ifdef CLEARCOAT_TEXTURE\n,in vec2 clearCoatMapData\n#endif\n#ifdef CLEARCOAT_TINT\n,in vec4 vClearCoatTintParams\n,in float clearCoatColorAtDistance\n,in vec4 vClearCoatRefractionParams\n#ifdef CLEARCOAT_TINT_TEXTURE\n,in vec4 clearCoatTintMapData\n#endif\n#endif\n#ifdef CLEARCOAT_BUMP\n,in vec2 vClearCoatBumpInfos\n,in vec4 clearCoatBumpMapData\n,in vec2 vClearCoatBumpUV\n#if defined(TANGENT) && defined(NORMAL)\n,in mat3 vTBN\n#else\n,in vec2 vClearCoatTangentSpaceParams\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n,in mat4 normalMatrix\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\n,in vec3 faceNormal\n#endif\n#ifdef REFLECTION\n,in vec3 vReflectionMicrosurfaceInfos\n,in vec2 vReflectionInfos\n,in vec3 vReflectionColor\n,in vec4 vLightingIntensity\n#ifdef REFLECTIONMAP_3D\n,in samplerCube reflectionSampler\n#else\n,in sampler2D reflectionSampler\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\n,in samplerCube reflectionSamplerLow\n,in samplerCube reflectionSamplerHigh\n#else\n,in sampler2D reflectionSamplerLow\n,in sampler2D reflectionSamplerHigh\n#endif\n#endif\n#ifdef REALTIME_FILTERING\n,in vec2 vReflectionFilteringInfo\n#endif\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\n,in float ambientMonochrome\n#endif\n#endif\n#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\n,in float frontFacingMultiplier\n#endif\n)\n{clearcoatOutParams outParams;float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y;\n#ifdef CLEARCOAT_TEXTURE\nclearCoatIntensity*=clearCoatMapData.x;\n#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE\nclearCoatRoughness*=clearCoatMapData.y;\n#endif\n#if DEBUGMODE>0\noutParams.clearCoatMapData=clearCoatMapData;\n#endif\n#endif\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nclearCoatRoughness*=clearCoatMapRoughnessData.y;\n#endif\noutParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness;\n#ifdef CLEARCOAT_TINT\nvec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a;\n#ifdef CLEARCOAT_TINT_TEXTURE\n#ifdef CLEARCOAT_TINT_GAMMATEXTURE\nclearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb);\n#else\nclearCoatColor*=clearCoatTintMapData.rgb;\n#endif\nclearCoatThickness*=clearCoatTintMapData.a;\n#if DEBUGMODE>0\noutParams.clearCoatTintMapData=clearCoatTintMapData;\n#endif\n#endif\noutParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness;\n#endif\n#ifdef CLEARCOAT_REMAP_F0\nvec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0);\n#else\nvec3 specularEnvironmentR0Updated=specularEnvironmentR0;\n#endif\noutParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW;\n#ifdef CLEARCOAT_BUMP\n#ifdef NORMALXYSCALE\nfloat clearCoatNormalScale=1.0;\n#else\nfloat clearCoatNormalScale=vClearCoatBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBNClearCoat=vTBN;\n#else\nvec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams);\n#endif\n#if DEBUGMODE>0\noutParams.TBNClearCoat=TBNClearCoat;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nclearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW);\n#else\nclearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y);\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nclearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nclearCoatNormalW=clearCoatNormalW*frontFacingMultiplier;\n#endif\noutParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped);\n#if DEBUGMODE>0\noutParams.clearCoatNdotV=clearCoatNdotV;\n#endif\n#ifdef CLEARCOAT_TINT\nvec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));\n#endif\n#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION))\nvec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);\n#endif\n#if defined(REFLECTION)\nfloat clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness);\n#ifdef SPECULARAA\nclearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y;\n#endif\nvec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nclearCoatReflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 clearCoatReflectionCoords=clearCoatReflectionVector;\n#else\nvec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nclearCoatReflectionCoords/=clearCoatReflectionVector.z;\n#endif\nclearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;\n#endif\nsampleReflectionTexture(\nclearCoatAlphaG,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nclearCoatNdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nclearCoatRoughness,\n#endif\nreflectionSampler,\nclearCoatReflectionCoords,\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\nenvironmentClearCoatRadiance\n);\n#if DEBUGMODE>0\noutParams.environmentClearCoatRadiance=environmentClearCoatRadiance;\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf);\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho;\n#endif\n#endif\n#endif\n#else\nvec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness));\n#endif\nclearCoatEnvironmentReflectance*=clearCoatIntensity;\n#if DEBUGMODE>0\noutParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance;\n#endif\noutParams.finalClearCoatRadianceScaled=\nenvironmentClearCoatRadiance.rgb *\nclearCoatEnvironmentReflectance *\nvLightingIntensity.z;\n#endif\n#if defined(CLEARCOAT_TINT)\noutParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity);\n#endif\nfloat fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat);\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\noutParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf);\n#endif\nreturn outParams;}\n#endif\n";it.IncludesShadersStore.pbrBlockIridescence="struct iridescenceOutParams\n{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;};\n#ifdef IRIDESCENCE\n#define pbr_inline\n#define inline\niridescenceOutParams iridescenceBlock(\nin vec4 vIridescenceParams\n,in float viewAngle\n,in vec3 specularEnvironmentR0\n#ifdef IRIDESCENCE_TEXTURE\n,in vec2 iridescenceMapData\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\n,in vec2 iridescenceThicknessMapData\n#endif\n#ifdef CLEARCOAT\n,in float NdotVUnclamped\n#ifdef CLEARCOAT_TEXTURE\n,in vec2 clearCoatMapData\n#endif\n#endif\n)\n{iridescenceOutParams outParams;float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.;\n#ifdef IRIDESCENCE_TEXTURE\niridescenceIntensity*=iridescenceMapData.x;\n#endif\n#if defined(IRIDESCENCE_THICKNESS_TEXTURE)\niridescenceThicknessWeight=iridescenceThicknessMapData.g;\n#endif\nfloat iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; \n#ifdef CLEARCOAT\nfloat clearCoatIntensity=vClearCoatParams.x;\n#ifdef CLEARCOAT_TEXTURE\nclearCoatIntensity*=clearCoatMapData.x;\n#endif\ntopIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0));\n#endif\nvec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;return outParams;}\n#endif\n";it.IncludesShadersStore.pbrBlockSubSurface="struct subSurfaceOutParams\n{vec3 specularEnvironmentReflectance;\n#ifdef SS_REFRACTION\nvec3 finalRefraction;vec3 surfaceAlbedo;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nfloat alpha;\n#endif\n#ifdef REFLECTION\nfloat refractionFactorForIrradiance;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nvec3 transmittance;float translucencyIntensity;\n#ifdef REFLECTION\nvec3 refractionIrradiance;\n#endif\n#endif\n#if DEBUGMODE>0\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec4 thicknessMap;\n#endif\n#ifdef SS_REFRACTION\nvec4 environmentRefraction;vec3 refractionTransmittance;\n#endif\n#endif\n};\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#define pbr_inline\n#define inline\nvec4 sampleEnvironmentRefraction(\nin float ior\n,in float thickness\n,in float refractionLOD\n,in vec3 normalW\n,in vec3 vPositionW\n,in vec3 viewDirectionW\n,in mat4 view\n,in vec4 vRefractionInfos\n,in mat4 refractionMatrix\n,in vec4 vRefractionMicrosurfaceInfos\n,in float alphaG\n#ifdef SS_REFRACTIONMAP_3D\n,in samplerCube refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,in samplerCube refractionSamplerLow\n,in samplerCube refractionSamplerHigh\n#endif\n#else\n,in sampler2D refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,in sampler2D refractionSamplerLow\n,in sampler2D refractionSamplerHigh\n#endif\n#endif\n#ifdef ANISOTROPIC\n,in anisotropicOutParams anisotropicOut\n#endif\n#ifdef REALTIME_FILTERING\n,in vec2 vRefractionFilteringInfo\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n,in vec3 refractionPosition\n,in vec3 refractionSize\n#endif\n) {vec4 environmentRefraction=vec4(0.,0.,0.,0.);\n#ifdef ANISOTROPIC\nvec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior);\n#else\nvec3 refractionVector=refract(-viewDirectionW,normalW,ior);\n#endif\n#ifdef SS_REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n#ifdef SS_REFRACTIONMAP_3D\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nrefractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition);\n#endif\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\n#ifdef SS_USE_THICKNESS_AS_DEPTH\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0)));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\n#endif\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODBASEDMICROSFURACE\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef SS_LODINREFRACTIONALPHA\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\n#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D)\nenvironmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0);\n#else\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#endif\n#else\nfloat lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);} else {environmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);}\n#endif\n#ifdef SS_RGBDREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef SS_GAMMAREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\nreturn environmentRefraction;}\n#endif\n#define pbr_inline\n#define inline\nsubSurfaceOutParams subSurfaceBlock(\nin vec3 vSubSurfaceIntensity\n,in vec2 vThicknessParam\n,in vec4 vTintColor\n,in vec3 normalW\n,in vec3 specularEnvironmentReflectance\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n,in vec4 thicknessMap\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\n,in vec4 refractionIntensityMap\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\n,in vec4 translucencyIntensityMap\n#endif\n#ifdef REFLECTION\n#ifdef SS_TRANSLUCENCY\n,in mat4 reflectionMatrix\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n,in vec3 irradianceVector_\n#endif\n#if defined(REALTIME_FILTERING)\n,in samplerCube reflectionSampler\n,in vec2 vReflectionFilteringInfo\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n#ifdef REFLECTIONMAP_3D\n,in samplerCube irradianceSampler\n#else\n,in sampler2D irradianceSampler\n#endif\n#endif\n#endif\n#endif\n#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n,in vec3 surfaceAlbedo\n#endif\n#ifdef SS_REFRACTION\n,in vec3 vPositionW\n,in vec3 viewDirectionW\n,in mat4 view\n,in vec4 vRefractionInfos\n,in mat4 refractionMatrix\n,in vec4 vRefractionMicrosurfaceInfos\n,in vec4 vLightingIntensity\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n,in float alpha\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\n,in float NdotVUnclamped\n#endif\n#ifdef SS_LINEARSPECULARREFRACTION\n,in float roughness\n#endif\n,in float alphaG\n#ifdef SS_REFRACTIONMAP_3D\n,in samplerCube refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,in samplerCube refractionSamplerLow\n,in samplerCube refractionSamplerHigh\n#endif\n#else\n,in sampler2D refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,in sampler2D refractionSamplerLow\n,in sampler2D refractionSamplerHigh\n#endif\n#endif\n#ifdef ANISOTROPIC\n,in anisotropicOutParams anisotropicOut\n#endif\n#ifdef REALTIME_FILTERING\n,in vec2 vRefractionFilteringInfo\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n,in vec3 refractionPosition\n,in vec3 refractionSize\n#endif\n#ifdef SS_DISPERSION\n,in float dispersion\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\n,in vec3 vDiffusionDistance\n,in vec4 vTranslucencyColor\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\n,in vec4 translucencyColorMap\n#endif\n#endif\n)\n{subSurfaceOutParams outParams;outParams.specularEnvironmentReflectance=specularEnvironmentReflectance;\n#ifdef SS_REFRACTION\nfloat refractionIntensity=vSubSurfaceIntensity.x;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nrefractionIntensity*=(1.0-alpha);outParams.alpha=1.0;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nfloat translucencyIntensity=vSubSurfaceIntensity.y;\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n#ifdef SS_USE_GLTF_TEXTURES\nfloat thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x;\n#else\nfloat thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;\n#endif\n#if DEBUGMODE>0\noutParams.thicknessMap=thicknessMap;\n#endif\n#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS)\n#ifdef SS_USE_GLTF_TEXTURES\nrefractionIntensity*=thicknessMap.r;\n#else\nrefractionIntensity*=thicknessMap.g;\n#endif\n#endif\n#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS)\n#ifdef SS_USE_GLTF_TEXTURES\ntranslucencyIntensity*=thicknessMap.a;\n#else\ntranslucencyIntensity*=thicknessMap.b;\n#endif\n#endif\n#else\nfloat thickness=vThicknessParam.y;\n#endif\n#if defined(SS_REFRACTION) && defined(SS_REFRACTIONINTENSITY_TEXTURE)\n#ifdef SS_USE_GLTF_TEXTURES\nrefractionIntensity*=refractionIntensityMap.r;\n#else\nrefractionIntensity*=refractionIntensityMap.g;\n#endif\n#endif\n#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCYINTENSITY_TEXTURE)\n#ifdef SS_USE_GLTF_TEXTURES\ntranslucencyIntensity*=translucencyIntensityMap.a;\n#else\ntranslucencyIntensity*=translucencyIntensityMap.b;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nthickness=maxEps(thickness);vec4 translucencyColor=vTranslucencyColor;\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\ntranslucencyColor*=translucencyColorMap;\n#endif\nvec3 transmittance=transmittanceBRDF_Burley(translucencyColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity;\n#endif\n#ifdef SS_REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\n#ifdef SS_HAS_THICKNESS\nfloat ior=vRefractionInfos.y;\n#else\nfloat ior=vRefractionMicrosurfaceInfos.w;\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\nfloat refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped);\n#elif defined(SS_LINEARSPECULARREFRACTION)\nfloat refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness);\n#else\nfloat refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG);\n#endif\nfloat refraction_ior=vRefractionInfos.y;\n#ifdef SS_DISPERSION\nfloat realIOR=1.0/refraction_ior;float iorDispersionSpread=0.04*dispersion*(realIOR-1.0);vec3 iors=vec3(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (int i=0; i<3; i++) {refraction_ior=iors[i];\n#endif\nvec4 envSample=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG\n#ifdef SS_REFRACTIONMAP_3D\n,refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,refractionSamplerLow\n,refractionSamplerHigh\n#endif\n#else\n,refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,refractionSamplerLow\n,refractionSamplerHigh\n#endif\n#endif\n#ifdef ANISOTROPIC\n,anisotropicOut\n#endif\n#ifdef REALTIME_FILTERING\n,vRefractionFilteringInfo\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n,refractionPosition\n,refractionSize\n#endif\n);\n#ifdef SS_DISPERSION\nenvironmentRefraction[i]=envSample[i];}\n#else\nenvironmentRefraction=envSample;\n#endif\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n#ifdef SS_REFRACTION\nvec3 refractionTransmittance=vec3(refractionIntensity);\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness);\n#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)\nfloat maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo;\n#else\nvec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y);\n#endif\n#ifdef SS_ALBEDOFORREFRACTIONTINT\nenvironmentRefraction.rgb*=surfaceAlbedo.rgb;\n#endif\noutParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity);\n#ifdef REFLECTION\noutParams.refractionFactorForIrradiance=(1.-refractionIntensity);\n#endif\n#ifdef UNUSED_MULTIPLEBOUNCES\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity);\n#endif\nrefractionTransmittance*=1.0-outParams.specularEnvironmentReflectance;\n#if DEBUGMODE>0\noutParams.refractionTransmittance=refractionTransmittance;\n#endif\noutParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z;\n#if DEBUGMODE>0\noutParams.environmentRefraction=environmentRefraction;\n#endif\n#endif\n#if defined(REFLECTION) && defined(SS_TRANSLUCENCY)\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP)\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\n#ifdef INVERTCUBICMAP\nirradianceVector.y*=-1.0;\n#endif\n#else\nvec3 irradianceVector=irradianceVector_;\n#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP)\n#if defined(REALTIME_FILTERING)\nvec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo);\n#else\nvec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector);\n#endif\n#elif defined(USEIRRADIANCEMAP)\n#ifdef REFLECTIONMAP_3D\nvec3 irradianceCoords=irradianceVector;\n#else\nvec2 irradianceCoords=irradianceVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nirradianceCoords/=irradianceVector.z;\n#endif\nirradianceCoords.y=1.0-irradianceCoords.y;\n#endif\nvec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords);\n#ifdef RGBDREFLECTION\nrefractionIrradiance.rgb=fromRGBD(refractionIrradiance);\n#endif\n#ifdef GAMMAREFLECTION\nrefractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb);\n#endif\n#else\nvec4 refractionIrradiance=vec4(0.);\n#endif\nrefractionIrradiance.rgb*=transmittance;\n#ifdef SS_ALBEDOFORTRANSLUCENCYTINT\nrefractionIrradiance.rgb*=surfaceAlbedo.rgb;\n#endif\noutParams.refractionIrradiance=refractionIrradiance.rgb;\n#endif\nreturn outParams;}\n#endif\n";it.IncludesShadersStore.clipPlaneFragment="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fClipDistance>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE2\nelse if (fClipDistance2>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE3\nelse if (fClipDistance3>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE4\nelse if (fClipDistance4>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE5\nelse if (fClipDistance5>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE6\nelse if (fClipDistance6>0.0)\n{discard;}\n#endif\n";it.IncludesShadersStore.pbrBlockNormalGeometric="vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\nvec3 geometricNormalW=normalW;\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\ngeometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW;\n#endif\n";it.IncludesShadersStore.bumpFragment="vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#elif defined(BUMP)\nfloat normalScale=vBumpInfos.y;\n#else\nfloat normalScale=1.0;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#elif defined(BUMP)\nvec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);\n#else\nvec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.));\n#endif\n#elif defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nvec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.));\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef DETAIL\nvec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB);\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\n#define CUSTOM_FRAGMENT_BUMP_FRAGMENT\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW);\n#elif !defined(DETAIL)\nnormalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);\n#else\nvec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;\n#if DETAIL_NORMALBLENDMETHOD==0 \ndetailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));\n#elif DETAIL_NORMALBLENDMETHOD==1 \ndetailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;\n#endif\nnormalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);\n#endif\n#elif defined(DETAIL)\ndetailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);\n#endif\n";it.IncludesShadersStore.pbrBlockNormalFinal="#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n";it.IncludesShadersStore.depthPrePass="#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);return;\n#endif\n";it.IncludesShadersStore.pbrBlockLightmapInit="#ifdef LIGHTMAP\nvec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);\n#ifdef RGBDLIGHTMAP\nlightmapColor.rgb=fromRGBD(lightmapColor);\n#endif\n#ifdef GAMMALIGHTMAP\nlightmapColor.rgb=toLinearSpace(lightmapColor.rgb);\n#endif\nlightmapColor.rgb*=vLightmapInfos.y;\n#endif\n";it.IncludesShadersStore.pbrBlockGeometryInfo="float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz);\n#ifdef SPECULARAA\nalphaG+=AARoughnessFactors.y;\n#endif\n#if defined(ENVIRONMENTBRDF)\nvec3 environmentBrdf=getBRDFLookup(NdotV,roughness);\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=aoOut.ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);\n#endif\n#endif\n#endif\n#endif\n";it.IncludesShadersStore.pbrBlockReflectance0="float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a);\n#else \nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\n#endif\n#ifdef ALPHAFRESNEL\nfloat reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90;\n#endif\n";it.IncludesShadersStore.pbrBlockReflectance="#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf);\n#ifdef RADIANCEOCCLUSION\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\nvec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n#ifdef CLEARCOAT\nspecularEnvironmentReflectance*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nspecularEnvironmentReflectance*=clearcoatOut.absorption;\n#endif\n#endif\n";it.IncludesShadersStore.pbrBlockDirectLighting="vec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef CLEARCOAT\nvec3 clearCoatBase=vec3(0.,0.,0.);\n#endif\n#ifdef SHEEN\nvec3 sheenBase=vec3(0.,0.,0.);\n#endif\npreLightingInfo preInfo;lightingInfo info;float shadow=1.; \nfloat aggShadow=0.;float numLights=0.;\n#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\nvec3 absorption=vec3(0.);\n#endif\n";it.IncludesShadersStore.lightFragment="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,vPositionW);\n#elif defined(POINTLIGHT{X})\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,vPositionW);\n#elif defined(HEMILIGHT{X})\npreInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(DIRLIGHT{X})\npreInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#endif\npreInfo.NdotV=NdotV;\n#ifdef SPOTLIGHT{X}\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\n#elif defined(POINTLIGHT{X})\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\n#else\npreInfo.attenuation=1.0;\n#endif\n#ifdef HEMILIGHT{X}\npreInfo.roughness=roughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#ifdef IRIDESCENCE\npreInfo.iridescenceIntensity=iridescenceIntensity;\n#endif\n#ifdef HEMILIGHT{X}\ninfo.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef SPECULARTERM\n#ifdef ANISOTROPIC\ninfo.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#endif\n#ifdef SHEEN\n#ifdef SHEEN_LINKWITHALBEDO\npreInfo.roughness=sheenOut.sheenIntensity;\n#else\n#ifdef HEMILIGHT{X}\npreInfo.roughness=sheenOut.sheenRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#endif\ninfo.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef CLEARCOAT\n#ifdef HEMILIGHT{X}\npreInfo.roughness=clearcoatOut.clearCoatRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\ninfo.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb);\n#ifdef CLEARCOAT_TINT\nabsorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;\n#ifdef SPECULARTERM\ninfo.specular*=absorption;\n#endif\n#endif\ninfo.diffuse*=info.clearCoat.w;\n#ifdef SPECULARTERM\ninfo.specular*=info.clearCoat.w;\n#endif\n#ifdef SHEEN\ninfo.sheen*=info.clearCoat.w;\n#endif\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},textureProjectionMatrix{X},vPositionW);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nfor (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) \n{\n#ifdef SHADOWCSM_RIGHTHANDED{X}\ndiff{X}=viewFrustumZ{X}[i]+vPositionFromCamera{X}.z;\n#else\ndiff{X}=viewFrustumZ{X}[i]-vPositionFromCamera{X}.z;\n#endif\nif (diff{X}>=0.) {index{X}=i;break;}}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\n#endif\n{\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#else\nshadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#endif\n#else\nshadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}];\n#endif\n#ifndef SHADOWCSMNOBLEND{X}\nfloat frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\n{index{X}+=1;float nextShadow=0.;\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nnextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#else\nnextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#endif\n#else\nnextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\nshadow=mix(nextShadow,shadow,diffRatio);\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\n#endif\n}\n#endif\n}\n#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;shadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\naggShadow+=shadow;numLights+=1.0;\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\n#else \ndiffuseBase+=info.diffuse*shadow;\n#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\n#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#endif\n#endif\n";it.IncludesShadersStore.pbrBlockFinalLitComponents="aggShadow=aggShadow/numLights;\n#if defined(ENVIRONMENTBRDF)\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf);\n#endif\n#endif\n#ifndef METALLICWORKFLOW\n#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n#endif\n#endif\n#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF)\nsurfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb;\n#endif\n#ifdef REFLECTION\nvec3 finalIrradiance=reflectionOut.environmentIrradiance;\n#if defined(CLEARCOAT)\nfinalIrradiance*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nfinalIrradiance*=clearcoatOut.absorption;\n#endif\n#endif\n#if defined(SS_REFRACTION)\nfinalIrradiance*=subSurfaceOut.refractionFactorForIrradiance;\n#endif\n#if defined(SS_TRANSLUCENCY)\nfinalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance;\n#endif\nfinalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalSpecularScaled*=energyConservationFactor;\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfinalSpecularScaled*=sheenOut.sheenAlbedoScaling;\n#endif\n#endif\n#ifdef REFLECTION\nvec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalRadianceScaled*=energyConservationFactor;\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfinalRadianceScaled*=sheenOut.sheenAlbedoScaling;\n#endif\n#endif\n#ifdef SHEEN\nvec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w;\n#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nsheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nsheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption;\n#endif\n#endif\n#endif\n#ifdef CLEARCOAT\nvec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat;\n#endif\n#ifdef SS_REFRACTION\nsubSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor;\n#ifdef CLEARCOAT_TINT\nsubSurfaceOut.finalRefraction*=clearcoatOut.absorption;\n#endif\n#endif\n#endif\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#if defined(CLEARCOAT)\nluminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled);\n#endif\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalClearCoatScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA)\nalpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);\n#endif\n#endif\n";it.IncludesShadersStore.pbrBlockFinalUnlitComponents="vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\n#ifdef GAMMAEMISSIVE\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\n#else\nfinalEmissive*=emissiveColorTex.rgb;\n#endif\nfinalEmissive*= vEmissiveInfos.y;\n#endif\nfinalEmissive*=vLightingIntensity.y;\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor;\n#endif\nfinalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse;\n";it.IncludesShadersStore.pbrBlockFinalColorComposition="vec4 finalColor=vec4(\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance +\n#endif\n#ifdef SPECULARTERM\nfinalSpecularScaled +\n#endif\n#ifdef SHEEN\nfinalSheenScaled +\n#endif\n#ifdef CLEARCOAT\nfinalClearCoatScaled +\n#endif\n#ifdef REFLECTION\nfinalRadianceScaled +\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\nsheenOut.finalSheenRadianceScaled +\n#endif\n#ifdef CLEARCOAT\nclearcoatOut.finalClearCoatRadianceScaled +\n#endif\n#endif\n#ifdef SS_REFRACTION\nsubSurfaceOut.finalRefraction +\n#endif\n#endif\nfinalAmbient +\nfinalDiffuse,\nalpha);\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor.rgb;\n#else\nfinalColor.rgb+=lightmapColor.rgb;\n#endif\n#endif\n#endif\nfinalColor.rgb+=finalEmissive;\n#define CUSTOM_FRAGMENT_BEFORE_FOG\nfinalColor=max(finalColor,0.0);\n";it.IncludesShadersStore.logDepthFragment="#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif\n";it.IncludesShadersStore.fogFragment="#ifdef FOG\nfloat fog=CalcFogFactor();\n#ifdef PBR\nfog=toLinearSpace(fog);\n#endif\ncolor.rgb=mix(vFogColor,color.rgb,fog);\n#endif\n";it.IncludesShadersStore.pbrBlockImageProcessing="#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING)\n#if !defined(SKIPFINALCOLORCLAMP)\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#endif\n#else\nfinalColor=applyImageProcessing(finalColor);\n#endif\nfinalColor.a*=visibility;\n#ifdef PREMULTIPLYALPHA\nfinalColor.rgb*=finalColor.a;\n#endif\n";it.IncludesShadersStore.oitFragment="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\nfloat fragDepth=gl_FragCoord.z; \n#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS\nuint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x;\n#endif\nivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0);\n#ifdef USE_REVERSE_DEPTHBUFFER\nfloat furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y;\n#else\nfloat nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y;\n#endif\nfloat alphaMultiplier=1.0-lastFrontColor.a;\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepth>nearestDepth || fragDepth<furthestDepth) {\n#else\nif (fragDepth<nearestDepth || fragDepth>furthestDepth) {\n#endif\nreturn;}\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepth<nearestDepth && fragDepth>furthestDepth) {\n#else\nif (fragDepth>nearestDepth && fragDepth<furthestDepth) {\n#endif\ndepth.rg=vec2(-fragDepth,fragDepth);return;}\n#endif\n";it.IncludesShadersStore.pbrDebug="#if DEBUGMODE>0\nif (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) {\n#if DEBUGMODE==1\ngl_FragColor.rgb=vPositionW.rgb;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==2 && defined(NORMAL)\ngl_FragColor.rgb=vNormalW.rgb;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC)\ngl_FragColor.rgb=TBN[0];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC)\ngl_FragColor.rgb=TBN[1];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==5\ngl_FragColor.rgb=normalW;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==6 && defined(MAINUV1)\ngl_FragColor.rgb=vec3(vMainUV1,0.0);\n#elif DEBUGMODE==7 && defined(MAINUV2)\ngl_FragColor.rgb=vec3(vMainUV2,0.0);\n#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\ngl_FragColor.rgb=clearcoatOut.TBNClearCoat[0];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\ngl_FragColor.rgb=clearcoatOut.TBNClearCoat[1];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==10 && defined(CLEARCOAT)\ngl_FragColor.rgb=clearcoatOut.clearCoatNormalW;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==11 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicNormal;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==12 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicTangent;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==13 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicBitangent;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==20 && defined(ALBEDO)\ngl_FragColor.rgb=albedoTexture.rgb;\n#ifndef GAMMAALBEDO\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==21 && defined(AMBIENT)\ngl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb;\n#elif DEBUGMODE==22 && defined(OPACITY)\ngl_FragColor.rgb=opacityMap.rgb;\n#elif DEBUGMODE==23 && defined(EMISSIVE)\ngl_FragColor.rgb=emissiveColorTex.rgb;\n#ifndef GAMMAEMISSIVE\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==24 && defined(LIGHTMAP)\ngl_FragColor.rgb=lightmapColor.rgb;\n#ifndef GAMMALIGHTMAP\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb;\n#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0);\n#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\ngl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb;\n#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE)\ngl_FragColor.rgb=sheenOut.sheenMapData.rgb;\n#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)\ngl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb;\n#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)\ngl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb;\n#elif DEBUGMODE==32 && defined(BUMP)\ngl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb;\n#elif DEBUGMODE==40 && defined(SS_REFRACTION)\ngl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==41 && defined(REFLECTION)\ngl_FragColor.rgb=reflectionOut.environmentRadiance.rgb;\n#ifndef GAMMAREFLECTION\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION)\ngl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==50\ngl_FragColor.rgb=diffuseBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==51 && defined(SPECULARTERM)\ngl_FragColor.rgb=specularBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==52 && defined(CLEARCOAT)\ngl_FragColor.rgb=clearCoatBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==53 && defined(SHEEN)\ngl_FragColor.rgb=sheenBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==54 && defined(REFLECTION)\ngl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb;\n#ifndef GAMMAREFLECTION\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==60\ngl_FragColor.rgb=surfaceAlbedo.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==61\ngl_FragColor.rgb=clearcoatOut.specularEnvironmentR0;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==62 && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r);\n#elif DEBUGMODE==71 && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.metallicF0;\n#elif DEBUGMODE==63\ngl_FragColor.rgb=vec3(roughness);\n#elif DEBUGMODE==64\ngl_FragColor.rgb=vec3(alphaG);\n#elif DEBUGMODE==65\ngl_FragColor.rgb=vec3(NdotV);\n#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\ngl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==67 && defined(CLEARCOAT)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness);\n#elif DEBUGMODE==68 && defined(CLEARCOAT)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV);\n#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)\ngl_FragColor.rgb=subSurfaceOut.transmittance;\n#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION)\ngl_FragColor.rgb=subSurfaceOut.refractionTransmittance;\n#elif DEBUGMODE==72\ngl_FragColor.rgb=vec3(microSurface);\n#elif DEBUGMODE==73\ngl_FragColor.rgb=vAlbedoColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW)\ngl_FragColor.rgb=vReflectivityColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==75\ngl_FragColor.rgb=vEmissiveColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION)\ngl_FragColor.rgb=vec3(seo);\n#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\ngl_FragColor.rgb=vec3(eho);\n#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION)\ngl_FragColor.rgb=vec3(energyConservationFactor);\n#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ngl_FragColor.rgb=specularEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ngl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION)\ngl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==86 && defined(ALPHABLEND)\ngl_FragColor.rgb=vec3(luminanceOverAlpha);\n#elif DEBUGMODE==87\ngl_FragColor.rgb=vec3(alpha);\n#elif DEBUGMODE==88 && defined(ALBEDO)\ngl_FragColor.rgb=vec3(albedoTexture.a);\n#elif DEBUGMODE==89\ngl_FragColor.rgb=aoOut.ambientOcclusionColor.rgb;\n#else\nfloat stripeWidth=30.;float stripePos=floor((gl_FragCoord.x+gl_FragCoord.y)/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor);\n#endif\ngl_FragColor.rgb*=vDebugMode.y;\n#ifdef DEBUGMODE_NORMALIZE\ngl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5;\n#endif\n#ifdef DEBUGMODE_GAMMA\ngl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb);\n#endif\ngl_FragColor.a=1.0;\n#ifdef PREPASS\ngl_FragData[0]=toLinearSpace(gl_FragColor); \ngl_FragData[1]=vec4(0.,0.,0.,0.); \n#endif\n#ifdef DEBUGMODE_FORCERETURN\nreturn;\n#endif\n}\n#endif\n";it.ShadersStore.pbrPixelShader="#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include<prePassDeclaration>[SCENE_MRT_COUNT]\nprecision highp float;\n#include<oitDeclaration>\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE\n#endif\n#include<__decl__pbrFragment>\n#include<pbrFragmentExtraDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<pbrFragmentSamplersDeclaration>\n#include<imageProcessingDeclaration>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#include<helperFunctions>\n#include<subSurfaceScatteringFunctions>\n#include<importanceSampling>\n#include<pbrHelperFunctions>\n#include<imageProcessingFunctions>\n#include<shadowsFragmentFunctions>\n#include<harmonicsFunctions>\n#include<pbrDirectLightingSetupFunctions>\n#include<pbrDirectLightingFalloffFunctions>\n#include<pbrBRDFFunctions>\n#include<hdrFilteringFunctions>\n#include<pbrDirectLightingFunctions>\n#include<pbrIBLFunctions>\n#include<bumpFragmentMainFunctions>\n#include<bumpFragmentFunctions>\n#ifdef REFLECTION\n#include<reflectionFunction>\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#include<pbrBlockAlbedoOpacity>\n#include<pbrBlockReflectivity>\n#include<pbrBlockAmbientOcclusion>\n#include<pbrBlockAlphaFresnel>\n#include<pbrBlockAnisotropic>\n#include<pbrBlockReflection>\n#include<pbrBlockSheen>\n#include<pbrBlockClearcoat>\n#include<pbrBlockIridescence>\n#include<pbrBlockSubSurface>\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\n#include<pbrBlockNormalGeometric>\n#include<bumpFragment>\n#include<pbrBlockNormalFinal>\nalbedoOpacityOutParams albedoOpacityOut;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#endif\n#ifdef DECAL\nvec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);\n#endif\nalbedoOpacityOut=albedoOpacityBlock(\nvAlbedoColor\n#ifdef ALBEDO\n,albedoTexture\n,vAlbedoInfos\n#endif\n#ifdef OPACITY\n,opacityMap\n,vOpacityInfos\n#endif\n#ifdef DETAIL\n,detailColor\n,vDetailInfos\n#endif\n#ifdef DECAL\n,decalColor\n,vDecalInfos\n#endif\n);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha;\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\n#include<depthPrePass>\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\nambientOcclusionOutParams aoOut;\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb;\n#endif\naoOut=ambientOcclusionBlock(\n#ifdef AMBIENT\nambientOcclusionColorMap,\nvAmbientInfos\n#endif \n);\n#include<pbrBlockLightmapInit>\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\nvec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut;\n#if defined(REFLECTIVITY)\nvec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap;\n#ifndef METALLICWORKFLOW\n#ifdef REFLECTIVITY_GAMMA\nsurfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap);\n#endif\nsurfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y;\n#endif\n#endif\n#if defined(MICROSURFACEMAP)\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\n#endif\n#ifdef METALLICWORKFLOW\nvec4 metallicReflectanceFactors=vMetallicReflectanceFactors;\n#ifdef REFLECTANCE\nvec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset);\n#ifdef REFLECTANCE_GAMMA\nreflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap);\n#endif\nmetallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb;\n#endif\n#ifdef METALLIC_REFLECTANCE\nvec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset);\n#ifdef METALLIC_REFLECTANCE_GAMMA\nmetallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap);\n#endif\n#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY\nmetallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb;\n#endif\nmetallicReflectanceFactors*=metallicReflectanceFactorsMap.a;\n#endif\n#endif\nreflectivityOut=reflectivityBlock(\nvReflectivityColor\n#ifdef METALLICWORKFLOW\n,surfaceAlbedo\n,metallicReflectanceFactors\n#endif\n#ifdef REFLECTIVITY\n,vReflectivityInfos\n,surfaceMetallicOrReflectivityColorMap\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n,aoOut.ambientOcclusionColor\n#endif\n#ifdef MICROSURFACEMAP\n,microSurfaceTexel\n#endif\n#ifdef DETAIL\n,detailColor\n,vDetailInfos\n#endif\n);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness;\n#ifdef METALLICWORKFLOW\nsurfaceAlbedo=reflectivityOut.surfaceAlbedo;\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\naoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor;\n#endif\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\nalphaFresnelOutParams alphaFresnelOut;alphaFresnelOut=alphaFresnelBlock(\nnormalW,\nviewDirectionW,\nalpha,\nmicroSurface\n);alpha=alphaFresnelOut.alpha;\n#endif\n#endif\n#include<pbrBlockGeometryInfo>\n#ifdef ANISOTROPIC\nanisotropicOutParams anisotropicOut;\n#ifdef ANISOTROPIC_TEXTURE\nvec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y;\n#endif\nanisotropicOut=anisotropicBlock(\nvAnisotropy,\nroughness,\n#ifdef ANISOTROPIC_TEXTURE\nanisotropyMapData,\n#endif\nTBN,\nnormalW,\nviewDirectionW \n);\n#endif\n#ifdef REFLECTION\nreflectionOutParams reflectionOut;\n#ifndef USE_CUSTOM_REFLECTION\nreflectionOut=reflectionBlock(\nvPositionW\n,normalW\n,alphaG\n,vReflectionMicrosurfaceInfos\n,vReflectionInfos\n,vReflectionColor\n#ifdef ANISOTROPIC\n,anisotropicOut\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\n,NdotVUnclamped\n#endif\n#ifdef LINEARSPECULARREFLECTION\n,roughness\n#endif\n,reflectionSampler\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\n,vEnvironmentIrradiance\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n,reflectionMatrix\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n,irradianceSampler\n#endif\n#ifndef LODBASEDMICROSFURACE\n,reflectionSamplerLow\n,reflectionSamplerHigh\n#endif\n#ifdef REALTIME_FILTERING\n,vReflectionFilteringInfo\n#endif\n);\n#else\n#define CUSTOM_REFLECTION\n#endif\n#endif\n#include<pbrBlockReflectance0>\n#ifdef SHEEN\nsheenOutParams sheenOut;\n#ifdef SHEEN_TEXTURE\nvec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset);\n#endif\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nvec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w;\n#endif\nsheenOut=sheenBlock(\nvSheenColor\n#ifdef SHEEN_ROUGHNESS\n,vSheenRoughness\n#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\n,sheenMapRoughnessData\n#endif\n#endif\n,roughness\n#ifdef SHEEN_TEXTURE\n,sheenMapData\n,vSheenInfos.y\n#endif\n,reflectance\n#ifdef SHEEN_LINKWITHALBEDO\n,baseColor\n,surfaceAlbedo\n#endif\n#ifdef ENVIRONMENTBRDF\n,NdotV\n,environmentBrdf\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\n,AARoughnessFactors\n,vReflectionMicrosurfaceInfos\n,vReflectionInfos\n,vReflectionColor\n,vLightingIntensity\n,reflectionSampler\n,reflectionOut.reflectionCoords\n,NdotVUnclamped\n#ifndef LODBASEDMICROSFURACE\n,reflectionSamplerLow\n,reflectionSamplerHigh\n#endif\n#ifdef REALTIME_FILTERING\n,vReflectionFilteringInfo\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\n,seo\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\n,eho\n#endif\n#endif\n);\n#ifdef SHEEN_LINKWITHALBEDO\nsurfaceAlbedo=sheenOut.surfaceAlbedo;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifdef CLEARCOAT_TEXTURE\nvec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y;\n#endif\n#endif\n#ifdef IRIDESCENCE\niridescenceOutParams iridescenceOut;\n#ifdef IRIDESCENCE_TEXTURE\nvec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nvec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w;\n#endif\niridescenceOut=iridescenceBlock(\nvIridescenceParams\n,NdotV\n,specularEnvironmentR0\n#ifdef IRIDESCENCE_TEXTURE\n,iridescenceMapData\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\n,iridescenceThicknessMapData\n#endif\n#ifdef CLEARCOAT\n,NdotVUnclamped\n#ifdef CLEARCOAT_TEXTURE\n,clearCoatMapData\n#endif\n#endif\n);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0;\n#endif\nclearcoatOutParams clearcoatOut;\n#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nvec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w;\n#endif\n#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\nvec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset);\n#endif\n#ifdef CLEARCOAT_BUMP\nvec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset);\n#endif\nclearcoatOut=clearcoatBlock(\nvPositionW\n,geometricNormalW\n,viewDirectionW\n,vClearCoatParams\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\n,clearCoatMapRoughnessData\n#endif\n,specularEnvironmentR0\n#ifdef CLEARCOAT_TEXTURE\n,clearCoatMapData\n#endif\n#ifdef CLEARCOAT_TINT\n,vClearCoatTintParams\n,clearCoatColorAtDistance\n,vClearCoatRefractionParams\n#ifdef CLEARCOAT_TINT_TEXTURE\n,clearCoatTintMapData\n#endif\n#endif\n#ifdef CLEARCOAT_BUMP\n,vClearCoatBumpInfos\n,clearCoatBumpMapData\n,vClearCoatBumpUV\n#if defined(TANGENT) && defined(NORMAL)\n,vTBN\n#else\n,vClearCoatTangentSpaceParams\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n,normalMatrix\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\n,faceNormal\n#endif\n#ifdef REFLECTION\n,vReflectionMicrosurfaceInfos\n,vReflectionInfos\n,vReflectionColor\n,vLightingIntensity\n,reflectionSampler\n#ifndef LODBASEDMICROSFURACE\n,reflectionSamplerLow\n,reflectionSamplerHigh\n#endif\n#ifdef REALTIME_FILTERING\n,vReflectionFilteringInfo\n#endif\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\n,ambientMonochrome\n#endif\n#endif\n#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\n,(gl_FrontFacing ? 1. : -1.)\n#endif\n);\n#else\nclearcoatOut.specularEnvironmentR0=specularEnvironmentR0;\n#endif\n#include<pbrBlockReflectance>\nsubSurfaceOutParams subSurfaceOut;\n#ifdef SUBSURFACE\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset);\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nvec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset);\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nvec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset);\n#endif\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nvec4 translucencyColorMap=texture2D(translucencyColorSampler,vTranslucencyColorUV+uvOffset);\n#endif\nsubSurfaceOut=subSurfaceBlock(\nvSubSurfaceIntensity\n,vThicknessParam\n,vTintColor\n,normalW\n,specularEnvironmentReflectance\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n,thicknessMap\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\n,refractionIntensityMap\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\n,translucencyIntensityMap\n#endif\n#ifdef REFLECTION\n#ifdef SS_TRANSLUCENCY\n,reflectionMatrix\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n,reflectionOut.irradianceVector\n#endif\n#if defined(REALTIME_FILTERING)\n,reflectionSampler\n,vReflectionFilteringInfo\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n,irradianceSampler\n#endif\n#endif\n#endif\n#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n,surfaceAlbedo\n#endif\n#ifdef SS_REFRACTION\n,vPositionW\n,viewDirectionW\n,view\n,vRefractionInfos\n,refractionMatrix\n,vRefractionMicrosurfaceInfos\n,vLightingIntensity\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n,alpha\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\n,NdotVUnclamped\n#endif\n#ifdef SS_LINEARSPECULARREFRACTION\n,roughness\n#endif\n,alphaG\n,refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,refractionSamplerLow\n,refractionSamplerHigh\n#endif\n#ifdef ANISOTROPIC\n,anisotropicOut\n#endif\n#ifdef REALTIME_FILTERING\n,vRefractionFilteringInfo\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n,vRefractionPosition\n,vRefractionSize\n#endif\n#ifdef SS_DISPERSION\n,dispersion\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\n,vDiffusionDistance\n,vTranslucencyColor\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\n,translucencyColorMap\n#endif\n#endif\n);\n#ifdef SS_REFRACTION\nsurfaceAlbedo=subSurfaceOut.surfaceAlbedo;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nalpha=subSurfaceOut.alpha;\n#endif\n#endif\n#else\nsubSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance;\n#endif\n#include<pbrBlockDirectLighting>\n#include<lightFragment>[0..maxSimultaneousLights]\n#include<pbrBlockFinalLitComponents>\n#endif \n#include<pbrBlockFinalUnlitComponents>\n#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION\n#include<pbrBlockFinalColorComposition>\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#include<pbrBlockImageProcessing>\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\n#ifdef PREPASS\nfloat writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0;\n#ifdef PREPASS_POSITION\ngl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);\n#endif\n#ifdef PREPASS_VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);\n#endif\n#ifdef PREPASS_ALBEDO_SQRT\nvec3 sqAlbedo=sqrt(surfaceAlbedo); \n#endif\n#ifdef PREPASS_IRRADIANCE\nvec3 irradiance=finalDiffuse;\n#ifndef UNLIT\n#ifdef REFLECTION\nirradiance+=finalIrradiance;\n#endif\n#endif\n#ifdef SS_SCATTERING\ngl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); \nirradiance/=sqAlbedo;\n#else\ngl_FragData[0]=finalColor; \nfloat scatteringDiffusionProfile=255.;\n#endif\ngl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); \n#else\ngl_FragData[0]=vec4(finalColor.rgb,finalColor.a);\n#endif\n#ifdef PREPASS_DEPTH\ngl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_NORMAL\n#ifdef PREPASS_NORMAL_WORLDSPACE\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); \n#else\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); \n#endif\n#endif\n#ifdef PREPASS_ALBEDO_SQRT\ngl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); \n#endif\n#ifdef PREPASS_REFLECTIVITY\n#ifndef UNLIT\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo;\n#else\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo;\n#endif\n#endif\n#endif\n#if !defined(PREPASS) || defined(WEBGL2)\ngl_FragColor=finalColor;\n#endif\n#include<oitFragment>\n#if ORDER_INDEPENDENT_TRANSPARENCY\nif (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;}\n#endif\n#include<pbrDebug>\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";it.IncludesShadersStore.decalVertexDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;uniform mat4 decalMatrix;\n#endif\n";it.IncludesShadersStore.pbrVertexDeclaration="uniform mat4 view;uniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;uniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix;\n#endif\n#ifdef METALLIC_REFLECTANCE\nuniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix;\n#endif\n#ifdef REFLECTANCE\nuniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;\n#endif\n#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#ifdef IRIDESCENCE\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nuniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;\n#endif\n#endif\n#ifdef NORMAL\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;\n#endif\n#endif\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;uniform mat4 detailMatrix;\n#endif\n#include<decalVertexDeclaration>\n#define ADDITIONAL_VERTEX_DECLARATION\n";it.IncludesShadersStore.uvAttributeDeclaration="#ifdef UV{X}\nattribute vec2 uv{X};\n#endif\n";it.IncludesShadersStore.bonesDeclaration="#if NUM_BONE_INFLUENCERS>0\nattribute vec4 matricesIndices;attribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nuniform highp sampler2D boneSampler;uniform float boneTextureWidth;\n#else\nuniform mat4 mBones[BonesPerMesh];\n#endif\n#ifdef BONES_VELOCITY_ENABLED\nuniform mat4 mPreviousBones[BonesPerMesh];\n#endif\n#ifdef BONETEXTURE\n#define inline\nmat4 readMatrixFromRawSampler(sampler2D smp,float index)\n{float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);}\n#endif\n#endif\n#endif\n";it.IncludesShadersStore.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture;\n#ifdef INSTANCES\nattribute vec4 bakedVertexAnimationSettingsInstanced;\n#endif\n#define inline\nmat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame)\n{float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);}\n#endif\n";it.IncludesShadersStore.instancesDeclaration="#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#ifdef INSTANCESCOLOR\nattribute vec4 instanceColor;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform mat4 world;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3;\n#ifdef THIN_INSTANCES\nuniform mat4 previousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform mat4 world;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform mat4 previousWorld;\n#endif\n#endif\n";it.IncludesShadersStore.prePassVertexDeclaration="#ifdef PREPASS\n#ifdef PREPASS_DEPTH\nvarying vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nuniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#endif\n";it.IncludesShadersStore.samplerVertexDeclaration="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n";it.IncludesShadersStore.bumpVertexDeclaration="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n";it.IncludesShadersStore.clipPlaneVertexDeclaration="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;varying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;varying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;varying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;varying float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;varying float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;varying float fClipDistance6;\n#endif\n";it.IncludesShadersStore.fogVertexDeclaration="#ifdef FOG\nvarying vec3 vFogDistance;\n#endif\n";it.IncludesShadersStore.lightVxFragmentDeclaration="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#endif\n";it.IncludesShadersStore.lightVxUboDeclaration="#ifdef LIGHT{X}\nuniform Light{X}\n{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;vec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;vec2 depthValues;} light{X};\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";it.IncludesShadersStore.morphTargetsVertexGlobalDeclaration="#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#ifdef MORPHTARGETS_TEXTURE \nuniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)\n{ \nfloat y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;}\n#endif\n#endif\n";it.IncludesShadersStore.morphTargetsVertexDeclaration="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#ifdef MORPHTARGETS_UV\nattribute vec2 uv_{X};\n#endif\n#elif {X}==0\nuniform int morphTargetCount;\n#endif\n#endif\n";it.IncludesShadersStore.morphTargetsVertexGlobal="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nfloat vertexID;\n#endif\n#endif\n";it.IncludesShadersStore.morphTargetsVertex="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (int i=0; i<NUM_MORPH_INFLUENCERS; i++) {if (i>=morphTargetCount) break;vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler(i,vertexID)-position)*morphTargetInfluences[i];vertexID+=1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(readVector3FromRawSampler(i,vertexID) -normal)*morphTargetInfluences[i];vertexID+=1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated+=(readVector3FromRawSampler(i,vertexID).xy-uv)*morphTargetInfluences[i];vertexID+=1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(readVector3FromRawSampler(i,vertexID) -tangent.xyz)*morphTargetInfluences[i];\n#endif\n}\n#endif\n#else\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";it.IncludesShadersStore.instancesVertex="#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nmat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\nfinalWorld=world*finalWorld;\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\nmat4 finalWorld=world;\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nmat4 finalPreviousWorld=previousWorld;\n#endif\n#endif\n";it.IncludesShadersStore.bonesVertex="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];\n#endif\n#else\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";it.IncludesShadersStore.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\n#define BVASNAME bakedVertexAnimationSettingsInstanced\n#else\n#define BVASNAME bakedVertexAnimationSettings\n#endif\nfloat VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;}\n#endif\n";it.IncludesShadersStore.prePassVertex="#ifdef PREPASS_DEPTH\nvViewPos=(view*worldPos).rgb;\n#endif\n#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*worldPos;\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n";it.IncludesShadersStore.uvVariableDeclaration="#if !defined(UV{X}) && defined(MAINUV{X})\nvec2 uv{X}=vec2(0.,0.);\n#endif\n#ifdef MAINUV{X}\nvMainUV{X}=uv{X};\n#endif\n";it.IncludesShadersStore.samplerVertexImplementation="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nif (v_INFONAME_==0.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));}\n#ifdef UV2\nelse if (v_INFONAME_==1.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));}\n#endif\n#ifdef UV3\nelse if (v_INFONAME_==2.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));}\n#endif\n#ifdef UV4\nelse if (v_INFONAME_==3.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));}\n#endif\n#ifdef UV5\nelse if (v_INFONAME_==4.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));}\n#endif\n#ifdef UV6\nelse if (v_INFONAME_==5.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));}\n#endif\n#endif\n";it.IncludesShadersStore.bumpVertex="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif\n";it.IncludesShadersStore.clipPlaneVertex="#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nfClipDistance5=dot(worldPos,vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nfClipDistance6=dot(worldPos,vClipPlane6);\n#endif\n";it.IncludesShadersStore.fogVertex="#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif\n";it.IncludesShadersStore.shadowsVertex="#ifdef SHADOWS\n#if defined(SHADOWCSM{X})\nvPositionFromCamera{X}=view*worldPos;for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) {vPositionFromLight{X}[i]=lightMatrix{X}[i]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric{X}[i]=(-vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvDepthMetric{X}[i]=(vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n}\n#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric{X}=(-vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvDepthMetric{X}=(vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#endif\n";it.IncludesShadersStore.vertexColorMixing="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvColor=vec4(1.0);\n#ifdef VERTEXCOLOR\n#ifdef VERTEXALPHA\nvColor*=color;\n#else\nvColor.rgb*=color.rgb;\n#endif\n#endif\n#ifdef INSTANCESCOLOR\nvColor*=instanceColor;\n#endif\n#endif\n";it.IncludesShadersStore.logDepthVertex="#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif\n";it.ShadersStore.pbrVertexShader="precision highp float;\n#include<__decl__pbrVertex>\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#include<uvAttributeDeclaration>[2..7]\n#include<mainUVVaryingDeclaration>[1..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\n#include<prePassVertexDeclaration>\n#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)\n#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)\n#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)\n#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)\n#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\n#ifdef CLEARCOAT\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)\n#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)\n#endif\n#ifdef SHEEN\n#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#endif\n#ifdef ANISOTROPIC\n#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)\n#endif\n#ifdef SUBSURFACE\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor)\n#endif\nvarying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos);\n#include<prePassVertex>\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);\n#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#if DEBUGMODE>0\nvClipSpacePosition=gl_Position;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\n#endif\n#include<uvVariableDeclaration>[2..7]\n#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#ifdef CLEARCOAT\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)\n#endif\n#ifdef SHEEN\n#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z)\n#endif\n#ifdef ANISOTROPIC\n#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)\n#endif\n#ifdef SUBSURFACE\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x)\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}";class Rr{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 i=this._mesh.getScene();for(let e=0;e<i.meshes.length;e++){const s=i.meshes[e];if(s.material){if(s.computeBonesUsingShaders&&0!==s.numBoneInfluencers)if(s.material.getEffect()===t)s.computeBonesUsingShaders=!1;else if(s.subMeshes)for(const e of s.subMeshes){if(e.effect===t){s.computeBonesUsingShaders=!1;break}}}else!this._mesh.material&&s.computeBonesUsingShaders&&s.numBoneInfluencers>0&&(s.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;i<t.length;i++)e=e.replace("#define "+t[i],"");this._currentRank++}return e}}class vr extends ir{constructor(){super(...arguments),this.CLEARCOAT=!1,this.CLEARCOAT_DEFAULTIOR=!1,this.CLEARCOAT_TEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this.CLEARCOAT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,this.CLEARCOAT_BUMP=!1,this.CLEARCOAT_BUMPDIRECTUV=0,this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,this.CLEARCOAT_REMAP_F0=!1,this.CLEARCOAT_TINT=!1,this.CLEARCOAT_TINT_TEXTURE=!1,this.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TINT_GAMMATEXTURE=!1}}class Ir extends or{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new vr,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=Ir._DefaultIndexOfRefraction,this.indexOfRefraction=Ir._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._textureRoughness=null,this.textureRoughness=null,this._remapF0OnInterfaceChange=!0,this.remapF0OnInterfaceChange=!0,this._bumpTexture=null,this.bumpTexture=null,this._isTintEnabled=!1,this.isTintEnabled=!1,this.tintColor=J.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[tt.MATERIAL_TextureDirtyFlag]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;const s=this._material._disableBumpMap;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&dr.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&dr.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1;if(i.getCaps().standardDerivatives&&this._bumpTexture&&dr.ClearCoatBumpTextureEnabled&&!s&&!this._bumpTexture.isReady())return!1;if(this._isTintEnabled&&this._tintTexture&&dr.ClearCoatTintTextureEnabled&&!this._tintTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&dr.ClearCoatTextureEnabled?ts(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&dr.ClearCoatTextureEnabled?ts(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&dr.ClearCoatBumpTextureEnabled?ts(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===Ir._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&dr.ClearCoatTintTextureEnabled?(ts(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)}bindForSubMesh(e,t,i,s){if(!this._isEnabled)return;const n=s.materialDefines,r=this._material.isFrozen,a=this._material._disableBumpMap,o=this._material._invertNormalMapX,l=this._material._invertNormalMapY;if(!e.useUbo||!r||!e.isSync){(this._texture||this._textureRoughness)&&dr.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&is(this._texture,e,"clearCoat"),this._textureRoughness&&!n.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&is(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&dr.ClearCoatTextureEnabled&&!a&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),is(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",o?1:-1,l?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",o?-1:1,l?-1:1)),this._tintTexture&&dr.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),is(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);const s=1-this._indexOfRefraction,r=1+this._indexOfRefraction,h=Math.pow(-s/r,2),c=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",h,c,s,r),this._isTintEnabled&&(e.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),e.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}t.texturesEnabled&&(this._texture&&dr.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!n.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&dr.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&dr.ClearCoatBumpTextureEnabled&&!a&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&dr.ClearCoatTintTextureEnabled&&e.setTexture("clearCoatTintSampler",this._tintTexture))}hasTexture(e){return this._texture===e||(this._textureRoughness===e||(this._bumpTexture===e||this._tintTexture===e))}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness),this._bumpTexture&&e.push(this._bumpTexture),this._tintTexture&&e.push(this._tintTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose(),this._bumpTexture?.dispose(),this._tintTexture?.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}}Ir._DefaultIndexOfRefraction=1.5,e([a(),r("_markAllSubMeshesAsTexturesDirty")],Ir.prototype,"isEnabled",void 0),e([a()],Ir.prototype,"intensity",void 0),e([a()],Ir.prototype,"roughness",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Ir.prototype,"indexOfRefraction",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Ir.prototype,"texture",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Ir.prototype,"useRoughnessFromMainTexture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Ir.prototype,"textureRoughness",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Ir.prototype,"remapF0OnInterfaceChange",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Ir.prototype,"bumpTexture",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Ir.prototype,"isTintEnabled",void 0),e([l()],Ir.prototype,"tintColor",void 0),e([a()],Ir.prototype,"tintColorAtDistance",void 0),e([a()],Ir.prototype,"tintThickness",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Ir.prototype,"tintTexture",void 0);class Sr extends ir{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0}}class Cr extends or{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new Sr,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=Cr._DefaultMinimumThickness,this.maximumThickness=Cr._DefaultMaximumThickness,this.indexOfRefraction=Cr._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[tt.MATERIAL_TextureDirtyFlag]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&dr.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&dr.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&dr.IridescenceTextureEnabled?ts(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&dr.IridescenceTextureEnabled?ts(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||((this._texture||this._thicknessTexture)&&dr.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._thicknessTexture?.coordinatesIndex??0,this._thicknessTexture?.level??0),this._texture&&is(this._texture,e,"iridescence"),this._thicknessTexture&&is(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&dr.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&dr.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){e&&(this._texture?.dispose(),this._thicknessTexture?.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}}Cr._DefaultMinimumThickness=100,Cr._DefaultMaximumThickness=400,Cr._DefaultIndexOfRefraction=1.3,e([a(),r("_markAllSubMeshesAsTexturesDirty")],Cr.prototype,"isEnabled",void 0),e([a()],Cr.prototype,"intensity",void 0),e([a()],Cr.prototype,"minimumThickness",void 0),e([a()],Cr.prototype,"maximumThickness",void 0),e([a()],Cr.prototype,"indexOfRefraction",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Cr.prototype,"texture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Cr.prototype,"thicknessTexture",void 0);class br extends ir{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class yr extends or{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new br,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new w(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[tt.MATERIAL_TextureDirtyFlag],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[tt.MATERIAL_MiscDirtyFlag]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&dr.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(li.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&dr.AnisotropicTextureEnabled?ts(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&dr.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),is(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&dr.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),void 0===e.legacy&&(this.legacy=!0)}}e([a(),r("_markAllSubMeshesAsTexturesDirty")],yr.prototype,"isEnabled",void 0),e([a()],yr.prototype,"intensity",void 0),e([h()],yr.prototype,"direction",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],yr.prototype,"texture",void 0),e([a(),r("_markAllSubMeshesAsMiscDirty")],yr.prototype,"legacy",void 0);class Mr extends ir{constructor(){super(...arguments),this.SHEEN=!1,this.SHEEN_TEXTURE=!1,this.SHEEN_GAMMATEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS=!1,this.SHEEN_TEXTUREDIRECTUV=0,this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,this.SHEEN_LINKWITHALBEDO=!1,this.SHEEN_ROUGHNESS=!1,this.SHEEN_ALBEDOSCALING=!1,this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1}}class xr extends or{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new Mr,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=J.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[tt.MATERIAL_TextureDirtyFlag]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&dr.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&dr.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=null!==this._roughness,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&dr.SheenTextureEnabled?(ts(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&dr.SheenTextureEnabled?ts(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,s){if(!this._isEnabled)return;const n=s.materialDefines,r=this._material.isFrozen;e.useUbo&&r&&e.isSync||((this._texture||this._textureRoughness)&&dr.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&is(this._texture,e,"sheen"),this._textureRoughness&&!n.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&is(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),null!==this._roughness&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&dr.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!n.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&dr.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}}e([a(),r("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"isEnabled",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"linkSheenWithAlbedo",void 0),e([a()],xr.prototype,"intensity",void 0),e([l()],xr.prototype,"color",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"texture",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"useRoughnessFromMainTexture",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"roughness",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"textureRoughness",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],xr.prototype,"albedoScaling",void 0);class Or extends ir{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_SCATTERING=!1,this.SS_DISPERSION=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,this.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_USE_GLTF_TEXTURES=!1}}class Dr extends or{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){this._volumeIndexOfRefraction=e>=1?e:-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new Or,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this.useAlbedoToTintRefraction=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=J.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=J.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this.translucencyColor=null,this._translucencyColorTexture=null,this.translucencyColorTexture=null,this._useGltfStyleTextures=!0,this.useGltfStyleTextures=!0,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[tt.MATERIAL_TextureDirtyFlag],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[tt.MATERIAL_PrePassDirtyFlag]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&dr.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;if(this._translucencyColorTexture&&dr.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking())return!1;if(this._translucencyIntensityTexture&&dr.TranslucencyIntensityTextureEnabled&&!this._translucencyIntensityTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&dr.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,void(e.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0);if(e._areTexturesDirty){if(e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&dr.ThicknessTextureEnabled&&ts(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&dr.RefractionIntensityTextureEnabled&&ts(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&dr.TranslucencyIntensityTextureEnabled&&ts(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&dr.TranslucencyColorTextureEnabled&&ts(this._translucencyColorTexture,e,"SS_TRANSLUCENCYCOLOR_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._refractionIntensityTexture,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._translucencyIntensityTexture,this._isRefractionEnabled&&t.texturesEnabled){const i=this._getRefractionTexture(t);i&&dr.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,s){if(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled)if(0===this.maximumThickness&&0===this.minimumThickness)e.updateFloat2("vThicknessParam",0,0);else{s.getRenderingMesh().getWorldMatrix().decompose(X.Vector3[0]);const t=Math.max(Math.abs(X.Vector3[0].x),Math.abs(X.Vector3[0].y),Math.abs(X.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*t,(this.maximumThickness-this.minimumThickness)*t)}}bindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const n=s.materialDefines,r=this._material.isFrozen,a=this._material.realTimeFiltering,o=n.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!r||!e.isSync){if(this._thicknessTexture&&dr.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),is(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&dr.RefractionIntensityTextureEnabled&&n.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),is(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&dr.TranslucencyColorTextureEnabled&&n.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),is(this._translucencyColorTexture,e,"translucencyColor")),this._translucencyIntensityTexture&&dr.TranslucencyIntensityTextureEnabled&&n.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),is(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&dr.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;l.isCube||l.depth&&(t=l.depth);const i=l.getSize().width,s=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",l.level,1/s,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),a&&e.updateFloat2("vRefractionFilteringInfo",i,q.Log2(i)),l.boundingBoxSize){const t=l;e.updateVector3("vRefractionPosition",t.boundingBoxPosition),e.updateVector3("vRefractionSize",t.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateColor4("vTranslucencyColor",this.translucencyColor??this.tintColor,0),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&dr.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&dr.RefractionIntensityTextureEnabled&&n.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&dr.TranslucencyIntensityTextureEnabled&&n.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&dr.TranslucencyColorTextureEnabled&&n.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),l&&dr.RefractionTextureEnabled&&(o?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){dr.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||(this._refractionTexture===e||(this._refractionIntensityTexture===e||(this._translucencyIntensityTexture===e||this._translucencyColorTexture===e)))}hasRenderTargetTextures(){return!!(dr.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture),this._translucencyColorTexture&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&e.push(this._translucencyIntensityTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),this._translucencyColorTexture&&this._translucencyColorTexture.animations&&this._translucencyColorTexture.animations.length>0&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.animations&&this._translucencyIntensityTexture.animations.length>0&&e.push(this._translucencyIntensityTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose(),this._translucencyColorTexture&&this._translucencyColorTexture.dispose(),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","translucencyColorSampler")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"},{name:"vTranslucencyColor",size:4,type:"vec4"},{name:"vTranslucencyColorInfos",size:2,type:"vec2"},{name:"translucencyColorMatrix",size:16,type:"mat4"}]}}}e([a(),r("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"isRefractionEnabled",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"isTranslucencyEnabled",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"isDispersionEnabled",void 0),e([a(),r("_markScenePrePassDirty")],Dr.prototype,"isScatteringEnabled",void 0),e([a()],Dr.prototype,"_scatteringDiffusionProfileIndex",void 0),e([a()],Dr.prototype,"refractionIntensity",void 0),e([a()],Dr.prototype,"translucencyIntensity",void 0),e([a()],Dr.prototype,"useAlbedoToTintRefraction",void 0),e([a()],Dr.prototype,"useAlbedoToTintTranslucency",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"thicknessTexture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"refractionTexture",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"indexOfRefraction",void 0),e([a()],Dr.prototype,"_volumeIndexOfRefraction",void 0),e([r("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"volumeIndexOfRefraction",null),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"invertRefractionY",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"linkRefractionWithTransparency",void 0),e([a()],Dr.prototype,"minimumThickness",void 0),e([a()],Dr.prototype,"maximumThickness",void 0),e([a()],Dr.prototype,"useThicknessAsDepth",void 0),e([l()],Dr.prototype,"tintColor",void 0),e([a()],Dr.prototype,"tintColorAtDistance",void 0),e([a()],Dr.prototype,"dispersion",void 0),e([l()],Dr.prototype,"diffusionDistance",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"useMaskFromThicknessTexture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"refractionIntensityTexture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"translucencyIntensityTexture",void 0),e([l()],Dr.prototype,"translucencyColor",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"translucencyColorTexture",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"useGltfStyleTextures",void 0);class Pr extends ir{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class Nr extends or{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new Pr,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=ls.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[tt.MATERIAL_TextureDirtyFlag]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&dr.DetailTextureEnabled&&!this._texture.isReady())}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&dr.DetailTextureEnabled&&this._isEnabled?(ts(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||this._texture&&dr.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),is(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&dr.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture?.dispose()}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}e([o("detailTexture"),r("_markAllSubMeshesAsTexturesDirty")],Nr.prototype,"texture",void 0),e([a()],Nr.prototype,"diffuseBlendLevel",void 0),e([a()],Nr.prototype,"roughnessBlendLevel",void 0),e([a()],Nr.prototype,"bumpLevel",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Nr.prototype,"normalBlendMethod",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Nr.prototype,"isEnabled",void 0);const Lr={effect:null,subMesh:null};class Fr extends ir{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_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.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,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,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!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.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class wr extends ur{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(tt.MATERIAL_TextureDirtyFlag)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(tt.MATERIAL_TextureDirtyFlag)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new U(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=wr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=J.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new J(0,0,0),this._albedoColor=new J(1,1,1),this._reflectivityColor=new J(1,1,1),this._reflectionColor=new J(1,1,1),this._emissiveColor=new J(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=wr.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._forceAlphaTest=!1,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=tt.TEXTURE_FILTERING_QUALITY_LOW,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new ei(16),this._globalAmbientColor=new J(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new hr(this),this.clearCoat=new Ir(this),this.iridescence=new Cr(this),this.anisotropy=new yr(this),this.sheen=new xr(this),this.subSurface=new Dr(this),this.detailMap=new Nr(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),dr.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=tr(this.getScene()),this.prePassConfiguration=new cr}get hasRenderTargetTextures(){return!!(dr.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){return this._transparencyMode===wr.PBRMATERIAL_OPAQUE||this._transparencyMode===wr.PBRMATERIAL_ALPHATEST||this.subSurface?.disableAlphaBlending}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){return!!this._forceAlphaTest||!this.subSurface?.disableAlphaBlending&&(this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===wr.PBRMATERIAL_ALPHATEST))}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==wr.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new Fr(this._eventInfo.defineNames));const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=this.getScene(),a=r.getEngine();if(n._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,r.texturesEnabled)){if(this._albedoTexture&&dr.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&dr.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&dr.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&dr.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&e.getInternalTexture()?._sphericalPolynomialPromise)return!1}if(this._lightmapTexture&&dr.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&dr.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(dr.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking())return!1;if(this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(a.getCaps().standardDerivatives&&this._bumpTexture&&dr.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&dr.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;a.getCaps().standardDerivatives||e.isVerticesDataPresent(li.NormalKind)||(e.createNormals(!0),ce.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const o=t.effect,l=n._areLightsDisposed;let h=this._prepareEffect(e,n,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),c=!1;if(h)if(this._onEffectCreatedObservable&&(Lr.effect=h,Lr.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Lr)),this.allowShaderHotSwapping&&o&&!h.isReady()){if(h=o,n.markAsUnprocessed(),c=this.isFrozen,l)return n._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(h,n,this._materialContext);return!(!t.effect||!t.effect.isReady())&&(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!c,s._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,i=null,s=null,n=null,r=null,a){if(this._prepareDefines(e,t,n,r,a),!t.isDirty)return null;t.markAsProcessed();const o=this.getScene().getEngine(),l=new Rr;let h=0;t.USESPHERICALINVERTEX&&l.addFallback(h++,"USESPHERICALINVERTEX"),t.FOG&&l.addFallback(h,"FOG"),t.SPECULARAA&&l.addFallback(h,"SPECULARAA"),t.POINTSIZE&&l.addFallback(h,"POINTSIZE"),t.LOGARITHMICDEPTH&&l.addFallback(h,"LOGARITHMICDEPTH"),t.PARALLAX&&l.addFallback(h,"PARALLAX"),t.PARALLAX_RHS&&l.addFallback(h,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&l.addFallback(h++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(h++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(h++,"TANGENT"),t.BUMP&&l.addFallback(h++,"BUMP"),h=function(e,t,i=4,s=0){let n=0;for(let r=0;r<i&&e["LIGHT"+r];r++)r>0&&(n=s+r,t.addFallback(n,"LIGHT"+r)),e.SHADOWS||(e["SHADOW"+r]&&t.addFallback(s,"SHADOW"+r),e["SHADOWPCF"+r]&&t.addFallback(s,"SHADOWPCF"+r),e["SHADOWPCSS"+r]&&t.addFallback(s,"SHADOWPCSS"+r),e["SHADOWPOISSON"+r]&&t.addFallback(s,"SHADOWPOISSON"+r),e["SHADOWESM"+r]&&t.addFallback(s,"SHADOWESM"+r),e["SHADOWCLOSEESM"+r]&&t.addFallback(s,"SHADOWCLOSEESM"+r));return n++}(t,l,this._maxSimultaneousLights,h++),t.SPECULARTERM&&l.addFallback(h++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&l.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&l.addFallback(h++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&l.addFallback(h++,"LIGHTMAP"),t.NORMAL&&l.addFallback(h++,"NORMAL"),t.AMBIENT&&l.addFallback(h++,"AMBIENT"),t.EMISSIVE&&l.addFallback(h++,"EMISSIVE"),t.VERTEXCOLOR&&l.addFallback(h++,"VERTEXCOLOR"),t.MORPHTARGETS&&l.addFallback(h++,"MORPHTARGETS"),t.MULTIVIEW&&l.addFallback(0,"MULTIVIEW");const c=[li.PositionKind];t.NORMAL&&c.push(li.NormalKind),t.TANGENT&&c.push(li.TangentKind);for(let e=1;e<=tt.MAX_SUPPORTED_UV_SETS;++e)t["UV"+e]&&c.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&c.push(li.ColorKind),function(e,t,i,s){i.NUM_BONE_INFLUENCERS>0&&(s.addCPUSkinningFallback(0,t),e.push(tt.MatricesIndicesKind),e.push(tt.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(tt.MatricesIndicesExtraKind),e.push(tt.MatricesWeightsExtraKind)))}(c,e,t,l),function(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&function(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"))}(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(tt.ColorInstanceKind)}(c,t),function(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&M.LastCreatedEngine){const n=M.LastCreatedEngine.getCaps().maxVertexAttribs,r=t.morphTargetManager;if(r?.isUsingTextureForTargets)return;const a=r&&r.supportsNormals&&i.NORMAL,o=r&&r.supportsTangents&&i.TANGENT,l=r&&r.supportsUVs&&i.UV1;for(let i=0;i<s;i++)e.push(tt.PositionKind+i),a&&e.push(tt.NormalKind+i),o&&e.push(tt.TangentKind+i),l&&e.push(tt.UVKind+"_"+i),e.length>n&&ce.Error("Cannot add more vertex attributes for mesh "+t.name)}}(c,e,t),function(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}(c,0,t);let u="pbr";const d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],_=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],f=["Material","Scene","Mesh"],m={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=l,this._eventInfo.fallbackRank=h,this._eventInfo.defines=t,this._eventInfo.uniforms=d,this._eventInfo.attributes=c,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=f,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=m,this._callbackPluginEventGeneric(128,this._eventInfo),cr.AddUniforms(d),function(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")}(d),nn&&(nn.PrepareUniforms(d,t),nn.PrepareSamplers(_,t)),function(e,t,i,s=4){let n,r=null;if(e.uniformsNames){const a=e;n=a.uniformsNames,r=a.uniformBuffersNames,t=a.samplers,i=a.defines,s=a.maxSimultaneousLights||0}else n=e,t||(t=[]);for(let e=0;e<s&&i["LIGHT"+e];e++)os(e,n,t,i["PROJECTEDLIGHTTEXTURE"+e],r);i.NUM_MORPH_INFLUENCERS&&(n.push("morphTargetInfluences"),n.push("morphTargetCount")),i.BAKED_VERTEX_ANIMATION_TEXTURE&&(n.push("bakedVertexAnimationSettings"),n.push("bakedVertexAnimationTextureSizeInverted"),n.push("bakedVertexAnimationTime"),t.push("bakedVertexAnimationTexture"))}({uniformsNames:d,uniformBuffersNames:f,samplers:_,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const p={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,d,f,_,t,c,p));const g=t.toString(),E=o.createEffect(u,{attributes:c,uniformsNames:d,uniformBuffersNames:f,samplers:_,defines:g,fallbacks:l,onCompiled:i,onError:s,indexParameters:m,processFinalCode:p.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},o);return this._eventInfo.customCode=void 0,E}_prepareDefines(e,t,i=null,s=null,n=!1){const r=this.getScene(),a=r.getEngine();!function(e,t,i,s,n=4,r=!1){if(!i._areLightsDirty)return i._needNormals;let a=0;const o={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!r)for(const s of t.lightSources)if(rs(e,t,s,a,i,0,o),a++,a===n)break;i.SPECULARTERM=o.specularEnabled,i.SHADOWS=o.shadowEnabled;for(let e=a;e<n;e++)void 0!==i["LIGHT"+e]&&(i["LIGHT"+e]=!1,i["HEMILIGHT"+e]=!1,i["POINTLIGHT"+e]=!1,i["DIRLIGHT"+e]=!1,i["SPOTLIGHT"+e]=!1,i["SHADOW"+e]=!1,i["SHADOWCSM"+e]=!1,i["SHADOWCSMDEBUG"+e]=!1,i["SHADOWCSMNUM_CASCADES"+e]=!1,i["SHADOWCSMUSESHADOWMAXZ"+e]=!1,i["SHADOWCSMNOBLEND"+e]=!1,i["SHADOWCSM_RIGHTHANDED"+e]=!1,i["SHADOWPCF"+e]=!1,i["SHADOWPCSS"+e]=!1,i["SHADOWPOISSON"+e]=!1,i["SHADOWESM"+e]=!1,i["SHADOWCLOSEESM"+e]=!1,i["SHADOWCUBE"+e]=!1,i["SHADOWLOWQUALITY"+e]=!1,i["SHADOWMEDIUMQUALITY"+e]=!1);const l=e.getEngine().getCaps();void 0===i.SHADOWFLOAT&&(o.needRebuild=!0),i.SHADOWFLOAT=o.shadowEnabled&&(l.textureFloatRender&&l.textureFloatLinearFiltering||l.textureHalfFloatRender&&l.textureHalfFloatLinearFiltering),i.LIGHTMAPEXCLUDED=o.lightmapMode,o.needRebuild&&i.rebuild(),o.needNormals}(r,e,t,0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,function(e,t){if(e.activeCamera){const i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}(r,t);const o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(function(e,t,i){const s=t.PREPASS;if(!t._arePrePassDirty)return;const n=[{type:tt.PREPASS_POSITION_TEXTURE_TYPE,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:tt.PREPASS_VELOCITY_TEXTURE_TYPE,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:tt.PREPASS_REFLECTIVITY_TEXTURE_TYPE,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:tt.PREPASS_IRRADIANCE_TEXTURE_TYPE,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:tt.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:tt.PREPASS_DEPTH_TEXTURE_TYPE,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:tt.PREPASS_NORMAL_TEXTURE_TYPE,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i<n.length;i++){const s=e.prePassRenderer.getIndex(n[i].type);-1!==s?(t[n[i].define]=!0,t[n[i].index]=s):t[n[i].define]=!1}}else{t.PREPASS=!1;for(let e=0;e<n.length;e++)t[n[e].define]=!1}t.PREPASS!=s&&(t.markAsUnprocessed(),t.markAsImageProcessingDirty())}(r,t,this.canRenderToMRT&&!o),function(e,t,i){const s=t.ORDER_INDEPENDENT_TRANSPARENCY,n=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,s===t.ORDER_INDEPENDENT_TRANSPARENCY&&n===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}(r,t,o),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=tt.MAX_SUPPORTED_UV_SETS;++e)t["MAINUV"+e]=!1;if(r.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,a.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&dr.DiffuseTextureEnabled?(ts(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&dr.AmbientTextureEnabled?(ts(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&dr.OpacityTextureEnabled?(ts(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&dr.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,a._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===wn.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.coordinatesMode){case wn.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case wn.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case wn.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case wn.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case wn.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case wn.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case wn.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case wn.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case wn.CUBIC_MODE:case wn.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==wn.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||a.getCaps().maxVaryingVectors<=8?t.USESPHERICALINVERTEX=!1:t.USESPHERICALINVERTEX=!0))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;this._lightmapTexture&&dr.LightmapTextureEnabled?(ts(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&dr.EmissiveTextureEnabled?(ts(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,dr.SpecularTextureEnabled?(this._metallicTexture?(ts(this._metallicTexture,t,"REFLECTIVITY"),t.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,t.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,t.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,t.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,t.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(ts(this._reflectivityTexture,t,"REFLECTIVITY"),t.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,t.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,t.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):t.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture?(t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture,this._metallicReflectanceTexture?(ts(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(ts(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1):(t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1),this._microSurfaceTexture?ts(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1):(t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1),a.getCaps().standardDerivatives&&this._bumpTexture&&dr.BumpTextureEnabled&&!this._disableBumpMap?(ts(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&dr.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=r.useRightHandedSystem,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAX_RHS=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&dr.ReflectionTextureEnabled?(t.ENVIRONMENTBRDF=!0,t.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(t.ENVIRONMENTBRDF=!1,t.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?t.ALPHAFROMALBEDO=!0:t.ALPHAFROMALBEDO=!1}t.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===wr.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===wr.LIGHTFALLOFF_GLTF?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!0):(t.USEPHYSICALLIGHTFALLOFF=!0,t.USEGLTFLIGHTFALLOFF=!1),t.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?t.TWOSIDEDLIGHTING=!0:t.TWOSIDEDLIGHTING=!1,t.SPECULARAA=a.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=this.alphaMode===tt.ALPHA_PREMULTIPLIED||this.alphaMode===tt.ALPHA_PREMULTIPLIED_PORTERDUFF,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(ns(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(li.NormalKind),t.DEBUGMODE=this._debugMode),as(r,a,this,t,!!i,s,n),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),function(e,t,i,s,n=!1,r=!0,a=!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(tt.NormalKind),t._needNormals&&e.isVerticesDataPresent(tt.TangentKind)&&(t.TANGENT=!0);for(let i=1;i<=tt.MAX_SUPPORTED_UV_SETS;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);{const i=e.useVertexColors&&e.isVerticesDataPresent(tt.ColorKind);t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&r}e.isVerticesDataPresent(tt.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),function(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;const s=e.getScene().prePassRenderer;if(s&&s.enabled){const i=-1===s.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}(e,t),n&&function(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.NUM_MORPH_INFLUENCERS=i.numMaxInfluencers||i.numInfluencers,t.MORPHTARGETS=t.NUM_MORPH_INFLUENCERS>0,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}(e,t),a&&function(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}(e,t)}(e,t,0,0,!0,this._transparencyMode!==wr.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const s={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(4,this._eventInfo);const n=new Fr(this._eventInfo.defineNames),r=this._prepareEffect(e,n,void 0,void 0,s.useInstances,s.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(Lr.effect=r,Lr.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Lr)),r.isReady()?t&&t(this):r.onCompileObservable.add((()=>{t&&t(this)}))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionFilteringInfo",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("reflectionMatrix",16),e.addUniform("vReflectionColor",3),e.addUniform("vAlbedoColor",4),e.addUniform("vLightingIntensity",4),e.addUniform("vReflectionMicrosurfaceInfos",3),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),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),super.buildUniformLayout()}bindForSubMesh(e,t,i){const s=this.getScene(),n=i.materialDefines;if(!n)return;const r=i.effect;if(!r)return;this._activeEffect=r,t.getMeshUniformBuffer().bindToEffect(r,"Mesh"),t.transferToEffect(e);const a=s.getEngine();this._uniformBuffer.bindToEffect(r,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),n.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(s,r,i,t.visibility);!function(e,t,i){var s;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const n=e.skeleton;if(n.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const i=n.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(n.bones.length+1))}else{const r=n.getTransformMatrices(e);r&&(t.setMatrices("mBones",r),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(tt.PREPASS_VELOCITY_TEXTURE_TYPE)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=r.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),s=r,i.previousBones[e.uniqueId].set(s)))}}}(t,this._activeEffect,this.prePassConfiguration);let l=null;const h=this._uniformBuffer;if(o){if(this.bindViewProjection(r),l=this._getReflectionTexture(),!h.useUbo||!this.isFrozen||!h.isSync||i._drawWrapper._forceRebindOnNextCall){if(s.texturesEnabled){if(this._albedoTexture&&dr.DiffuseTextureEnabled&&(h.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),is(this._albedoTexture,h,"albedo")),this._ambientTexture&&dr.AmbientTextureEnabled&&(h.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),is(this._ambientTexture,h,"ambient")),this._opacityTexture&&dr.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),is(this._opacityTexture,h,"opacity")),l&&dr.ReflectionTextureEnabled){if(h.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),h.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){const e=l;h.updateVector3("vReflectionPosition",e.boundingBoxPosition),h.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=l.getSize().width;h.updateFloat2("vReflectionFilteringInfo",e,q.Log2(e))}if(!n.USEIRRADIANCEMAP){const e=l.sphericalPolynomial;if(n.USESPHERICALFROMREFLECTIONMAP&&e)if(n.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;h.updateVector3("vSphericalL00",t.l00),h.updateVector3("vSphericalL1_1",t.l1_1),h.updateVector3("vSphericalL10",t.l10),h.updateVector3("vSphericalL11",t.l11),h.updateVector3("vSphericalL2_2",t.l2_2),h.updateVector3("vSphericalL2_1",t.l2_1),h.updateVector3("vSphericalL20",t.l20),h.updateVector3("vSphericalL21",t.l21),h.updateVector3("vSphericalL22",t.l22)}else h.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),h.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),h.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),h.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),h.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),h.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),h.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),h.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),h.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}h.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}this._emissiveTexture&&dr.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),is(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&dr.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),is(this._lightmapTexture,h,"lightmap")),dr.SpecularTextureEnabled&&(this._metallicTexture?(h.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),is(this._metallicTexture,h,"reflectivity")):this._reflectivityTexture&&(h.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),is(this._reflectivityTexture,h,"reflectivity")),this._metallicReflectanceTexture&&(h.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),is(this._metallicReflectanceTexture,h,"metallicReflectance")),this._reflectanceTexture&&n.REFLECTANCE&&(h.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),is(this._reflectanceTexture,h,"reflectance")),this._microSurfaceTexture&&(h.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),is(this._microSurfaceTexture,h,"microSurfaceSampler"))),this._bumpTexture&&a.getCaps().standardDerivatives&&dr.BumpTextureEnabled&&!this._disableBumpMap&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),is(this._bumpTexture,h,"bump"),s._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),n.METALLICWORKFLOW){te.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,te.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,h.updateColor4("vReflectivityColor",te.Color3[0],1);const e=this.subSurface?._indexOfRefraction??1.5,t=1,i=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(i*this._metallicF0Factor,te.Color3[0]);const s=this._metallicF0Factor;h.updateColor4("vMetallicReflectanceFactors",te.Color3[0],s)}else h.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);h.updateColor3("vEmissiveColor",dr.EmissiveTextureEnabled?this._emissiveColor:J.BlackReadOnly),h.updateColor3("vReflectionColor",this._reflectionColor),!n.SS_REFRACTION&&this.subSurface?._linkRefractionWithTransparency?h.updateColor4("vAlbedoColor",this._albedoColor,1):h.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*s.environmentIntensity,this._lightingInfos.w=this._specularIntensity,h.updateVector4("vLightingIntensity",this._lightingInfos),s.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor),h.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}s.texturesEnabled&&(this._albedoTexture&&dr.DiffuseTextureEnabled&&h.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&dr.AmbientTextureEnabled&&h.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&dr.OpacityTextureEnabled&&h.setTexture("opacitySampler",this._opacityTexture),l&&dr.ReflectionTextureEnabled&&(n.LODBASEDMICROSFURACE?h.setTexture("reflectionSampler",l):(h.setTexture("reflectionSampler",l._lodTextureMid||l),h.setTexture("reflectionSamplerLow",l._lodTextureLow||l),h.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)),n.USEIRRADIANCEMAP&&h.setTexture("irradianceSampler",l.irradianceTexture)),n.ENVIRONMENTBRDF&&h.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&dr.EmissiveTextureEnabled&&h.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&dr.LightmapTextureEnabled&&h.setTexture("lightmapSampler",this._lightmapTexture),dr.SpecularTextureEnabled&&(this._metallicTexture?h.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&h.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&h.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&n.REFLECTANCE&&h.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&h.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&a.getCaps().standardDerivatives&&dr.BumpTextureEnabled&&!this._disableBumpMap&&h.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(r),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),function(e,t,i){let s=t.clipPlane??i.clipPlane;Ji(e,"vClipPlane",s),s=t.clipPlane2??i.clipPlane2,Ji(e,"vClipPlane2",s),s=t.clipPlane3??i.clipPlane3,Ji(e,"vClipPlane3",s),s=t.clipPlane4??i.clipPlane4,Ji(e,"vClipPlane4",s),s=t.clipPlane5??i.clipPlane5,Ji(e,"vClipPlane5",s),s=t.clipPlane6??i.clipPlane6,Ji(e,"vClipPlane6",s)}(this._activeEffect,this,s),this.bindEyePosition(r)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!o&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&function(e,t,i,s,n=4){const r=Math.min(t.lightSources.length,n);for(let n=0;n<r;n++)ss(t.lightSources[n],n,e,i,"boolean"==typeof s?s:s.SPECULARTERM,t.receiveShadows)}(s,t,this._activeEffect,n,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==Dn.FOGMODE_NONE||l||this.subSurface.refractionTexture||t.receiveShadows||n.PREPASS)&&this.bindView(r),function(e,t,i,s=!1){i&&e.fogEnabled&&(!t||t.applyFog)&&e.fogMode!==tt.FOGMODE_NONE&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),s?(e.fogColor.toLinearSpaceToRef(es,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",es)):i.setColor3("vFogColor",e.fogColor))}(s,t,this._activeEffect,!0),n.NUM_MORPH_INFLUENCERS&&function(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}(t,this._activeEffect),n.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(r,n.INSTANCES),this._imageProcessingConfiguration.bind(this._activeEffect),function(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=i.activeCamera;e.mode===tt.ORTHOGRAPHIC_CAMERA&&ce.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}(n,this._activeEffect,s)),this._afterBind(t,this._activeEffect,i),h.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!super.hasTexture(e)||(this._albedoTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._emissiveTexture===e||(this._reflectivityTexture===e||(this._metallicTexture===e||(this._metallicReflectanceTexture===e||(this._reflectanceTexture===e||(this._microSurfaceTexture===e||(this._bumpTexture===e||this._lightmapTexture===e)))))))))))}setPrePassRenderer(){if(!this.subSurface?.isScatteringEnabled)return!1;const e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._albedoTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._metallicTexture?.dispose(),this._reflectivityTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._metallicReflectanceTexture?.dispose(),this._reflectanceTexture?.dispose(),this._microSurfaceTexture?.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}wr.PBRMATERIAL_OPAQUE=ls.MATERIAL_OPAQUE,wr.PBRMATERIAL_ALPHATEST=ls.MATERIAL_ALPHATEST,wr.PBRMATERIAL_ALPHABLEND=ls.MATERIAL_ALPHABLEND,wr.PBRMATERIAL_ALPHATESTANDBLEND=ls.MATERIAL_ALPHATESTANDBLEND,wr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,wr.LIGHTFALLOFF_PHYSICAL=0,wr.LIGHTFALLOFF_GLTF=1,wr.LIGHTFALLOFF_STANDARD=2,e([function(e){return n(9,e)}()],wr.prototype,"_imageProcessingConfiguration",void 0),e([r("_markAllSubMeshesAsMiscDirty")],wr.prototype,"debugMode",void 0);class Br extends wr{get refractionTexture(){return this.subSurface.refractionTexture}set refractionTexture(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)}get indexOfRefraction(){return this.subSurface.indexOfRefraction}set indexOfRefraction(e){this.subSurface.indexOfRefraction=e}get invertRefractionY(){return this.subSurface.invertRefractionY}set invertRefractionY(e){this.subSurface.invertRefractionY=e}get linkRefractionWithTransparency(){return this.subSurface.linkRefractionWithTransparency}set linkRefractionWithTransparency(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)}get usePhysicalLightFalloff(){return this._lightFalloff===wr.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?wr.LIGHTFALLOFF_PHYSICAL:wr.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===wr.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?wr.LIGHTFALLOFF_GLTF:wr.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}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}constructor(e,t){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=Br.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=J.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new J(0,0,0),this.albedoColor=new J(1,1,1),this.reflectivityColor=new J(1,1,1),this.reflectionColor=new J(1,1,1),this.emissiveColor=new J(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=tr(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const s=se.Clone((()=>new Br(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return s.id=e,s.name=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const s=se.Parse((()=>new Br(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),ls._ParsePlugins(e,s,t,i),e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}Br.PBRMATERIAL_OPAQUE=wr.PBRMATERIAL_OPAQUE,Br.PBRMATERIAL_ALPHATEST=wr.PBRMATERIAL_ALPHATEST,Br.PBRMATERIAL_ALPHABLEND=wr.PBRMATERIAL_ALPHABLEND,Br.PBRMATERIAL_ALPHATESTANDBLEND=wr.PBRMATERIAL_ALPHATESTANDBLEND,Br.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=wr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"directIntensity",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"emissiveIntensity",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"environmentIntensity",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"specularIntensity",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"disableBumpMap",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"albedoTexture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"ambientTexture",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"ambientTextureStrength",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),e([o(),r("_markAllSubMeshesAsTexturesAndMiscDirty")],Br.prototype,"opacityTexture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"reflectionTexture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"emissiveTexture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"reflectivityTexture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"metallicTexture",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"metallic",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"roughness",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"metallicF0Factor",void 0),e([l(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"metallicReflectanceColor",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"metallicReflectanceTexture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"reflectanceTexture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"microSurfaceTexture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"bumpTexture",void 0),e([o(),r("_markAllSubMeshesAsTexturesDirty",null)],Br.prototype,"lightmapTexture",void 0),e([l("ambient"),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"ambientColor",void 0),e([l("albedo"),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"albedoColor",void 0),e([l("reflectivity"),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"reflectivityColor",void 0),e([l("reflection"),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"reflectionColor",void 0),e([l("emissive"),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"emissiveColor",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"microSurface",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useLightmapAsShadowmap",void 0),e([a(),r("_markAllSubMeshesAsTexturesAndMiscDirty")],Br.prototype,"useAlphaFromAlbedoTexture",void 0),e([a(),r("_markAllSubMeshesAsTexturesAndMiscDirty")],Br.prototype,"forceAlphaTest",void 0),e([a(),r("_markAllSubMeshesAsTexturesAndMiscDirty")],Br.prototype,"alphaCutOff",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useSpecularOverAlpha",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useRoughnessFromMetallicTextureGreen",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useMetallnessFromMetallicTextureBlue",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useAmbientInGrayScale",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),e([a()],Br.prototype,"usePhysicalLightFalloff",null),e([a()],Br.prototype,"useGLTFLightFalloff",null),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useRadianceOverAlpha",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useObjectSpaceNormalMap",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useParallax",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useParallaxOcclusion",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"parallaxScaleBias",void 0),e([a(),r("_markAllSubMeshesAsLightsDirty")],Br.prototype,"disableLighting",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"forceIrradianceInFragment",void 0),e([a(),r("_markAllSubMeshesAsLightsDirty")],Br.prototype,"maxSimultaneousLights",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"invertNormalMapX",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"invertNormalMapY",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"twoSidedLighting",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useAlphaFresnel",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useLinearAlphaFresnel",void 0),e([r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"environmentBRDFTexture",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"forceNormalForward",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"enableSpecularAntiAliasing",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useHorizonOcclusion",void 0),e([a(),r("_markAllSubMeshesAsTexturesDirty")],Br.prototype,"useRadianceOcclusion",void 0),e([a(),r("_markAllSubMeshesAsMiscDirty")],Br.prototype,"unlit",void 0),e([a(),r("_markAllSubMeshesAsMiscDirty")],Br.prototype,"applyDecalMapAfterDetailMap",void 0),C("BABYLON.PBRMaterial",Br),St.prototype._partialLoadFile=function(e,t,i,s,n=null){this._loadFile(e,(e=>{i[t]=e,i._internalCount++,6===i._internalCount&&s(i)}),void 0,void 0,!0,((e,t)=>{n&&e&&n(e.status+" "+e.statusText,t)}))},St.prototype._cascadeLoadFiles=function(e,t,i,s=null){const n=[];n._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,n,t,s)},St.prototype._cascadeLoadImgs=function(e,t,i,s,n=null,r){const a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(s[o],o,a,e,t,i,n,r)},St.prototype._partialLoadImg=function(e,t,i,s,n,r,a=null,o){const l=Xt();Dt(e,(e=>{i[t]=e,i._internalCount++,s&&s.removePendingData(l),6===i._internalCount&&r&&r(n,i)}),((e,t)=>{s&&s.removePendingData(l),a&&a(e,t)}),s?s.offlineProvider:null,o),s&&s.addPendingData(l)},St.prototype.createCubeTextureBase=function(e,t,i,s,n=null,r=null,a,o=null,l=!1,h=0,c=0,u=null,d=null,_=null,f=!1,m=null){const p=u||new vt(this,7);p.isCube=!0,p.url=e,p.generateMipMaps=!s,p._lodGenerationScale=h,p._lodGenerationOffset=c,p._useSRGBBuffer=!!f&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!s),p!==u&&(p.label=e.substring(0,60)),this._doNotHandleContextLost||(p._extension=o,p._files=i,p._buffer=m);const g=e;this._transformTextureUrl&&!u&&(e=this._transformTextureUrl(e));const E=e.split("?")[0],T=E.lastIndexOf("."),A=o||(T>-1?E.substring(T).toLowerCase():"");let R=null;for(const e of St._TextureLoaders)if(e.canLoad(A)){R=e;break}const v=(u,E)=>{e===g?r&&u&&r(u.status+" "+u.statusText,E):(ce.Warn(`Failed to load ${e}, falling back to the ${g}`),this.createCubeTextureBase(g,t,i,!!s,n,r,a,o,l,h,c,p,d,_,f,m))};if(R){const s=e=>{d&&d(p,e),R.loadCubeData(e,p,l,n,r)};m?s(m):i&&6===i.length?R.supportCascades?this._cascadeLoadFiles(t,(e=>s(e.map((e=>new Uint8Array(e))))),i,r):r?r("Textures type does not support cascades."):ce.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>s(new Uint8Array(e))),void 0,void 0,!0,v)}else{if(!i||0===i.length)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(t,p,((e,t)=>{_&&_(e,t)}),i,r)}return this._internalTexturesCache.push(p),p},Pi.prototype._createDepthStencilCubeTexture=function(e,t){const i=new vt(this,12);if(i.isCube=!0,1===this.webGLVersion)return ce.Error("Depth cube texture is not supported by WebGL 1."),i;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t},n=this._gl;this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction);for(let t=0;t<6;t++)s.generateStencil?n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,n.DEPTH24_STENCIL8,e,e,0,n.DEPTH_STENCIL,n.UNSIGNED_INT_24_8,null):n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,n.DEPTH_COMPONENT24,e,e,0,n.DEPTH_COMPONENT,n.UNSIGNED_INT,null);return this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(i),i},Pi.prototype._setCubeMapTextureParams=function(e,t,i){const s=this._gl;s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,t?s.LINEAR_MIPMAP_LINEAR:s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),e.samplingMode=t?tt.TEXTURE_TRILINEAR_SAMPLINGMODE:tt.TEXTURE_LINEAR_LINEAR,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null)},Pi.prototype.createCubeTexture=function(e,t,i,s,n=null,r=null,a,o=null,l=!1,h=0,c=0,u=null,d,_=!1,f=null){const m=this._gl;return this.createCubeTextureBase(e,t,i,!!s,n,r,a,o,l,h,c,u,(e=>this._bindTextureDirectly(m.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?qt(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,r=i,o=[m.TEXTURE_CUBE_MAP_POSITIVE_X,m.TEXTURE_CUBE_MAP_POSITIVE_Y,m.TEXTURE_CUBE_MAP_POSITIVE_Z,m.TEXTURE_CUBE_MAP_NEGATIVE_X,m.TEXTURE_CUBE_MAP_NEGATIVE_Y,m.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(m.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const l=a?this._getInternalFormat(a,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:m.RGBA;let h=a?this._getInternalFormat(a):m.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(h=l);for(let e=0;e<o.length;e++)if(t[e].width!==i||t[e].height!==r){if(this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext)return void ce.Warn("Cannot create canvas to resize texture.");this._workingCanvas.width=i,this._workingCanvas.height=r,this._workingContext.drawImage(t[e],0,0,t[e].width,t[e].height,0,0,i,r),m.texImage2D(o[e],0,l,h,m.UNSIGNED_BYTE,this._workingCanvas)}else m.texImage2D(o[e],0,l,h,m.UNSIGNED_BYTE,t[e]);s||m.generateMipmap(m.TEXTURE_CUBE_MAP),this._setCubeMapTextureParams(e,!s),e.width=i,e.height=r,e.isReady=!0,a&&(e.format=a),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),n&&n()}),!!_,f)},Pi.prototype.generateMipMapsForCubemap=function(e,t=!0){if(e.generateMipMaps){const i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}};const Ur=131072,kr=131072;function Gr(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}const Vr=Gr("DXT1"),Xr=Gr("DXT3"),Hr=Gr("DXT5"),zr=Gr("DX10");class Wr{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35);let s=1;t[2]&Ur&&(s=Math.max(1,t[7]));const n=t[21],r=n===zr?i[32]:0;let a=tt.TEXTURETYPE_UNSIGNED_INT;switch(n){case 113:a=tt.TEXTURETYPE_HALF_FLOAT;break;case 116:a=tt.TEXTURETYPE_FLOAT;break;case zr:if(10===r){a=tt.TEXTURETYPE_HALF_FLOAT;break}if(2===r){a=tt.TEXTURETYPE_FLOAT;break}}return{width:t[4],height:t[3],mipmapCount:s,isFourCC:!(4&~t[20]),isRGB:!(64&~t[20]),isLuminance:(t[20]&kr)===kr,isCube:!(512&~t[28]),isCompressed:n===Vr||n===Xr||n===Hr,dxgiFormat:r,textureType:a}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,s,n,r){const a=new Float32Array(s),o=new Uint16Array(n,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const s=4*(t+i*e);a[l]=$n(o[s]),a[l+1]=$n(o[s+1]),a[l+2]=$n(o[s+2]),Wr.StoreLODInAlphaChannel?a[l+3]=r:a[l+3]=$n(o[s+3]),l+=4}return a}static _GetHalfFloatRGBAArrayBuffer(e,t,i,s,n,r){if(Wr.StoreLODInAlphaChannel){const a=new Uint16Array(s),o=new Uint16Array(n,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const s=4*(t+i*e);a[l]=o[s],a[l+1]=o[s+1],a[l+2]=o[s+2],a[l+3]=Zn(r),l+=4}return a}return new Uint16Array(n,i,s)}static _GetFloatRGBAArrayBuffer(e,t,i,s,n,r){if(Wr.StoreLODInAlphaChannel){const a=new Float32Array(s),o=new Float32Array(n,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const s=4*(t+i*e);a[l]=o[s],a[l+1]=o[s+1],a[l+2]=o[s+2],a[l+3]=r,l+=4}return a}return new Float32Array(n,i,s)}static _GetFloatAsHalfFloatRGBAArrayBuffer(e,t,i,s,n,r){const a=new Uint16Array(s),o=new Float32Array(n,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++)a[l]=Zn(o[l]),a[l+1]=Zn(o[l+1]),a[l+2]=Zn(o[l+2]),Wr.StoreLODInAlphaChannel?a[l+3]=Zn(r):a[l+3]=Zn(o[l+3]),l+=4;return a}static _GetFloatAsUIntRGBAArrayBuffer(e,t,i,s,n,r){const a=new Uint8Array(s),o=new Float32Array(n,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const s=4*(t+i*e);a[l]=255*q.Clamp(o[s]),a[l+1]=255*q.Clamp(o[s+1]),a[l+2]=255*q.Clamp(o[s+2]),Wr.StoreLODInAlphaChannel?a[l+3]=r:a[l+3]=255*q.Clamp(o[s+3]),l+=4}return a}static _GetHalfFloatAsUIntRGBAArrayBuffer(e,t,i,s,n,r){const a=new Uint8Array(s),o=new Uint16Array(n,i);let l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const s=4*(t+i*e);a[l]=255*q.Clamp($n(o[s])),a[l+1]=255*q.Clamp($n(o[s+1])),a[l+2]=255*q.Clamp($n(o[s+2])),Wr.StoreLODInAlphaChannel?a[l+3]=r:a[l+3]=255*q.Clamp($n(o[s+3])),l+=4}return a}static _GetRGBAArrayBuffer(e,t,i,s,n,r,a,o,l){const h=new Uint8Array(s),c=new Uint8Array(n,i);let u=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const s=4*(t+i*e);h[u]=c[s+r],h[u+1]=c[s+a],h[u+2]=c[s+o],h[u+3]=c[s+l],u+=4}return h}static _ExtractLongWordOrder(e){return 0===e||255===e||-16777216===e?0:1+Wr._ExtractLongWordOrder(e>>8)}static _GetRGBArrayBuffer(e,t,i,s,n,r,a,o){const l=new Uint8Array(s),h=new Uint8Array(n,i);let c=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const s=3*(t+i*e);l[c]=h[s+r],l[c+1]=h[s+a],l[c+2]=h[s+o],c+=3}return l}static _GetLuminanceArrayBuffer(e,t,i,s,n){const r=new Uint8Array(s),a=new Uint8Array(n,i);let o=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const s=t+i*e;r[o]=a[s],o++}return r}static UploadDDSLevels(e,t,i,s,n,r,a=-1,o,l=!0){let h=null;s.sphericalPolynomial&&(h=[]);const c=!!e.getCaps().s3tc;t.generateMipMaps=n;const u=new Int32Array(i.buffer,i.byteOffset,31);let d,_,f,m,p,g,E,T=0,A=0,R=1;if(542327876!==u[0])return void ce.Error("Invalid magic number in DDS header");if(!s.isFourCC&&!s.isRGB&&!s.isLuminance)return void ce.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");if(s.isCompressed&&!c)return void ce.Error("Compressed textures are not supported on this platform.");let v=u[22];m=u[1]+4;let I=!1;if(s.isFourCC)switch(d=u[21],d){case Vr:R=8,A=tt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1;break;case Xr:R=16,A=tt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3;break;case Hr:R=16,A=tt.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5;break;case 113:I=!0,v=64;break;case 116:I=!0,v=128;break;case zr:{m+=20;let e=!1;switch(s.dxgiFormat){case 10:I=!0,v=64,e=!0;break;case 2:I=!0,v=128,e=!0;break;case 88:s.isRGB=!0,s.isFourCC=!1,v=32,e=!0}if(e)break}default:return void ce.Error(["Unsupported FourCC code:",(S=d,String.fromCharCode(255&S,S>>8&255,S>>16&255,S>>24&255))])}var S;const C=Wr._ExtractLongWordOrder(u[23]),b=Wr._ExtractLongWordOrder(u[24]),y=Wr._ExtractLongWordOrder(u[25]),M=Wr._ExtractLongWordOrder(u[26]);I&&(A=e._getRGBABufferInternalSizedFormat(s.textureType)),g=1,u[2]&Ur&&!1!==n&&(g=Math.max(1,u[7]));const x=o||0,O=e.getCaps();for(let n=x;n<r;n++){for(_=u[4],f=u[3],E=0;E<g;++E){if(-1===a||a===E){const r=-1===a?E:0;if(!s.isCompressed&&s.isFourCC){t.format=tt.TEXTUREFORMAT_RGBA,T=_*f*4;let s=null;if(e._badOS||e._badDesktopOS||!O.textureHalfFloat&&!O.textureFloat)128===v?(s=Wr._GetFloatAsUIntRGBAArrayBuffer(_,f,i.byteOffset+m,T,i.buffer,r),h&&0==r&&h.push(Wr._GetFloatRGBAArrayBuffer(_,f,i.byteOffset+m,T,i.buffer,r))):64===v&&(s=Wr._GetHalfFloatAsUIntRGBAArrayBuffer(_,f,i.byteOffset+m,T,i.buffer,r),h&&0==r&&h.push(Wr._GetHalfFloatAsFloatRGBAArrayBuffer(_,f,i.byteOffset+m,T,i.buffer,r))),t.type=tt.TEXTURETYPE_UNSIGNED_INT;else{const e=O.textureFloat&&(l&&O.textureFloatLinearFiltering||!l),n=O.textureHalfFloat&&(l&&O.textureHalfFloatLinearFiltering||!l),a=(128===v||64===v&&!n)&&e?tt.TEXTURETYPE_FLOAT:(64===v||128===v&&!e)&&n?tt.TEXTURETYPE_HALF_FLOAT:tt.TEXTURETYPE_UNSIGNED_BYTE;let o,c=null;if(128===v)switch(a){case tt.TEXTURETYPE_FLOAT:o=Wr._GetFloatRGBAArrayBuffer,c=null;break;case tt.TEXTURETYPE_HALF_FLOAT:o=Wr._GetFloatAsHalfFloatRGBAArrayBuffer,c=Wr._GetFloatRGBAArrayBuffer;break;case tt.TEXTURETYPE_UNSIGNED_BYTE:o=Wr._GetFloatAsUIntRGBAArrayBuffer,c=Wr._GetFloatRGBAArrayBuffer}else switch(a){case tt.TEXTURETYPE_FLOAT:o=Wr._GetHalfFloatAsFloatRGBAArrayBuffer,c=null;break;case tt.TEXTURETYPE_HALF_FLOAT:o=Wr._GetHalfFloatRGBAArrayBuffer,c=Wr._GetHalfFloatAsFloatRGBAArrayBuffer;break;case tt.TEXTURETYPE_UNSIGNED_BYTE:o=Wr._GetHalfFloatAsUIntRGBAArrayBuffer,c=Wr._GetHalfFloatAsFloatRGBAArrayBuffer}t.type=a,s=o(_,f,i.byteOffset+m,T,i.buffer,r),h&&0==r&&h.push(c?c(_,f,i.byteOffset+m,T,i.buffer,r):s)}s&&e._uploadDataToTextureDirectly(t,s,n,r)}else if(s.isRGB)t.type=tt.TEXTURETYPE_UNSIGNED_INT,24===v?(t.format=tt.TEXTUREFORMAT_RGB,T=_*f*3,p=Wr._GetRGBArrayBuffer(_,f,i.byteOffset+m,T,i.buffer,C,b,y),e._uploadDataToTextureDirectly(t,p,n,r)):(t.format=tt.TEXTUREFORMAT_RGBA,T=_*f*4,p=Wr._GetRGBAArrayBuffer(_,f,i.byteOffset+m,T,i.buffer,C,b,y,M),e._uploadDataToTextureDirectly(t,p,n,r));else if(s.isLuminance){const s=e._getUnpackAlignement(),a=_;T=Math.floor((_+s-1)/s)*s*(f-1)+a,p=Wr._GetLuminanceArrayBuffer(_,f,i.byteOffset+m,T,i.buffer),t.format=tt.TEXTUREFORMAT_LUMINANCE,t.type=tt.TEXTURETYPE_UNSIGNED_INT,e._uploadDataToTextureDirectly(t,p,n,r)}else T=Math.max(4,_)/4*Math.max(4,f)/4*R,p=new Uint8Array(i.buffer,i.byteOffset+m,T),t.type=tt.TEXTURETYPE_UNSIGNED_INT,e._uploadCompressedDataToTextureDirectly(t,A,_,f,p,n,r)}m+=v?_*f*(v/8):T,_*=.5,f*=.5,_=Math.max(1,_),f=Math.max(1,f)}if(void 0!==o)break}h&&h.length>0?s.sphericalPolynomial=Ar.ConvertCubeMapToSphericalPolynomial({size:u[4],right:h[0],left:h[1],up:h[2],down:h[3],front:h[4],back:h[5],format:tt.TEXTUREFORMAT_RGBA,type:tt.TEXTURETYPE_FLOAT,gammaSpace:!1}):s.sphericalPolynomial=void 0}}Wr.StoreLODInAlphaChannel=!1,Pi.prototype.createPrefilteredCubeTexture=function(e,t,i,s,n=null,r=null,a,o=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(n&&n(null));const r=e.texture;if(l?e.info.sphericalPolynomial&&(r._sphericalPolynomial=e.info.sphericalPolynomial):r._sphericalPolynomial=new Er,r._source=9,this.getCaps().textureLOD)return void(n&&n(r));const a=this._gl,o=e.width;if(!o)return;const h=[];for(let n=0;n<3;n++){const l=1-n/2,c=s,u=q.Log2(o)*i+s,d=c+(u-c)*l,_=Math.round(Math.min(Math.max(d,0),u)),f=new vt(this,2);if(f.type=r.type,f.format=r.format,f.width=Math.pow(2,Math.max(q.Log2(o)-_,0)),f.height=f.width,f.isCube=!0,f._cachedWrapU=tt.TEXTURE_CLAMP_ADDRESSMODE,f._cachedWrapV=tt.TEXTURE_CLAMP_ADDRESSMODE,this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,f,!0),f.samplingMode=tt.TEXTURE_LINEAR_LINEAR,a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),e.isDDS){const t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),Wr.UploadDDSLevels(this,f,i,t,!0,6,_)}else ce.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);const m=new Ln(t);m._isCube=!0,m._texture=f,f.isReady=!0,h.push(m)}r._lodTextureHigh=h[2],r._lodTextureMid=h[1],r._lodTextureLow=h[0],n&&n(r)}),r,a,o,l,i,s)};class Yr extends Ln{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(G.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let s="";return e.forEach((e=>s+=e)),new Yr(s,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,s=!0){const n=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const r=new Yr(e,t,null,!1,null,null,null,void 0,!0,i,s);return t.useDelayedTextureLoading=n,r}constructor(e,t,i=null,s=!1,n=null,r=null,a=null,o=tt.TEXTUREFORMAT_RGBA,l=!1,h=null,c=!1,u=.8,d=0,_,f){super(t),this.onLoadObservable=new g,this.boundingBoxPosition=B.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new G,this._buffer=null,this.name=e,this.url=e,this._noMipmap=s,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=G.Identity(),this.coordinatesMode=wn.CUBIC_MODE;let m=null,p=null;null===i||Array.isArray(i)?(this._noMipmap=s,this._format=o,this._createPolynomials=c,m=i,this._loaderOptions=_,this._useSRGBBuffer=f,this._lodScale=u,this._lodOffset=d):(m=i.extensions??null,this._noMipmap=i.noMipmap??!1,n=i.files??null,p=i.buffer??null,this._format=i.format??tt.TEXTUREFORMAT_RGBA,l=i.prefiltered??!1,h=i.forcedExtension??null,this._createPolynomials=i.createPolynomials??!1,this._lodScale=i.lodScale??.8,this._lodOffset=i.lodOffset??0,this._loaderOptions=i.loaderOptions,this._useSRGBBuffer=i.useSRGBBuffer,r=i.onLoad??null,a=i.onError??null),(e||n)&&this.updateURL(e,h,r,l,a,m,this.getScene()?.useDelayedTextureLoading,n,p)}getClassName(){return"CubeTexture"}updateURL(e,t=null,i=null,s=!1,n=null,r=null,a=!1,o=null,l=null){this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,t&&(this._forcedExtension=t);const h=e.lastIndexOf("."),c=t||(h>-1?e.substring(h).toLowerCase():""),u=0===c.indexOf(".dds"),d=0===c.indexOf(".env"),_=0===c.indexOf(".basis");if(d?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=s,s&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),o)this._files=o;else if(_||d||u||r||(r=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,r){for(let t=0;t<r.length;t++)this._files.push(e+r[t]);this._extensions=r}this._buffer=l,a?(this.delayLoadState=tt.DELAYLOADSTATE_NOTLOADED,this._delayedOnLoad=i,this._delayedOnError=n):this._loadTexture(i,n)}delayLoad(e){this.delayLoadState===tt.DELAYLOADSTATE_NOTLOADED&&(e&&(this._forcedExtension=e),this.delayLoadState=tt.DELAYLOADSTATE_LOADED,this._loadTexture(this._delayedOnLoad,this._delayedOnError))}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){if(e.updateFlag===this._textureMatrix.updateFlag)return;if(e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene()?.markAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag,(e=>-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!this.getScene()?.useRightHandedSystem)return;const t=X.Vector3[0],i=X.Quaternion[0],s=X.Vector3[1];this._textureMatrix.decompose(t,i,s),i.z*=-1,i.w*=-1,G.ComposeToRef(t,i,s,this._textureMatrixRefraction)}getRefractionTextureMatrix(){return this.getScene()?.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){const i=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const n=()=>{this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),this.getScene()?.markAllMaterialsAsDirty(tt.MATERIAL_TextureDirtyFlag)),e&&e()},r=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),wn.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Qt.SetImmediate((()=>n())):this._texture.onLoadedObservable.add((()=>n())):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,i,this._lodScale,this._lodOffset,e,r,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,i,this._files,this._noMipmap,e,r,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer,this._buffer),this._texture?.onLoadedObservable.add((()=>this.onLoadObservable.notifyObservers(this))))}static Parse(e,t,i){const s=se.Parse((()=>{let s=!1;return e.prefiltered&&(s=e.prefiltered),new Yr(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(s.boundingBoxPosition=B.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=B.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t<e.animations.length;t++){const i=e.animations[t],n=b("BABYLON.Animation");n&&s.animations.push(n.Parse(i))}return s}clone(){let e=0;const t=se.Clone((()=>{const t=new Yr(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}e([a()],Yr.prototype,"url",void 0),e([c()],Yr.prototype,"boundingBoxPosition",void 0),e([c()],Yr.prototype,"boundingBoxSize",null),e([a("rotationY")],Yr.prototype,"rotationY",null),e([a("files")],Yr.prototype,"_files",void 0),e([a("forcedExtension")],Yr.prototype,"_forcedExtension",void 0),e([a("extensions")],Yr.prototype,"_extensions",void 0),e([_("textureMatrix")],Yr.prototype,"_textureMatrix",void 0),e([_("textureMatrixRefraction")],Yr.prototype,"_textureMatrixRefraction",void 0),wn._CubeTextureParser=Yr.Parse,C("BABYLON.CubeTexture",Yr),gs._GroundMeshParser=(e,t)=>Kr.Parse(e,t);class Kr extends gs{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);const i=this;i.createOrUpdateSubmeshesOctree&&i.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),s=X.Matrix[5];i.invertToRef(s);const n=X.Vector3[8];if(B.TransformCoordinatesFromFloatsToRef(e,0,t,s,n),e=n.x,t=n.z,e<this._minX||e>=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const r=this._getFacetAt(e,t),a=-(r.x*e+r.z*t+r.w)/r.y;return B.TransformCoordinatesFromFloatsToRef(0,a,0,i,n),n.y}getNormalAtCoordinates(e,t){const i=new B(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),n=X.Matrix[5];s.invertToRef(n);const r=X.Vector3[8];if(B.TransformCoordinatesFromFloatsToRef(e,0,t,n,r),e=r.x,t=r.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const a=this._getFacetAt(e,t);return B.TransformNormalFromFloatsToRef(a.x,a.y,a.z,s,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),s=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),n=this._heightQuads[s*this._subdivisionsX+i];let r;return r=t<n.slope.x*e+n.slope.y?n.facet1:n.facet2,r}_initHeightQuads(){const e=this._subdivisionsX,t=this._subdivisionsY;this._heightQuads=new Array;for(let i=0;i<t;i++)for(let t=0;t<e;t++){const s={slope:w.Zero(),facet1:new U(0,0,0,0),facet2:new U(0,0,0,0)};this._heightQuads[i*e+t]=s}return this}_computeHeightQuads(){const e=this.getVerticesData(li.PositionKind);if(!e)return this;const t=X.Vector3[3],i=X.Vector3[2],s=X.Vector3[1],n=X.Vector3[0],r=X.Vector3[4],a=X.Vector3[5],o=X.Vector3[6],l=X.Vector3[7],h=X.Vector3[8];let c=0,u=0,d=0,_=0,f=0,m=0,p=0;const g=this._subdivisionsX,E=this._subdivisionsY;for(let T=0;T<E;T++)for(let E=0;E<g;E++){c=3*E,u=T*(g+1)*3,d=(T+1)*(g+1)*3,t.x=e[u+c],t.y=e[u+c+1],t.z=e[u+c+2],i.x=e[u+c+3],i.y=e[u+c+4],i.z=e[u+c+5],s.x=e[d+c],s.y=e[d+c+1],s.z=e[d+c+2],n.x=e[d+c+3],n.y=e[d+c+4],n.z=e[d+c+5],_=(n.z-t.z)/(n.x-t.x),f=t.z-_*t.x,i.subtractToRef(t,r),s.subtractToRef(t,a),n.subtractToRef(t,o),B.CrossToRef(o,a,l),B.CrossToRef(r,o,h),l.normalize(),h.normalize(),m=-(l.x*t.x+l.y*t.y+l.z*t.z),p=-(h.x*i.x+h.y*i.y+h.z*i.z);const A=this._heightQuads[T*g+E];A.slope.copyFromFloats(_,f),A.facet1.copyFromFloats(l.x,l.y,l.z,m),A.facet2.copyFromFloats(h.x,h.y,h.z,p)}return this}serialize(e){super.serialize(e),e.subdivisionsX=this._subdivisionsX,e.subdivisionsY=this._subdivisionsY,e.minX=this._minX,e.maxX=this._maxX,e.minZ=this._minZ,e.maxZ=this._maxZ,e.width=this._width,e.height=this._height}static Parse(e,t){const i=new Kr(e.name,t);return i._subdivisionsX=e.subdivisionsX||1,i._subdivisionsY=e.subdivisionsY||1,i._minX=e.minX,i._maxX=e.maxX,i._minZ=e.minZ,i._maxZ=e.maxZ,i._width=e.width,i._height=e.height,i}}function qr(e){const t=[],i=[],s=[],n=[];let r,a;const o=e.width||1,l=e.height||1,h=0|(e.subdivisionsX||e.subdivisions||1),c=0|(e.subdivisionsY||e.subdivisions||1);for(r=0;r<=c;r++)for(a=0;a<=h;a++){const e=new B(a*o/h-o/2,0,(c-r)*l/c-l/2),t=new B(0,1,0);i.push(e.x,e.y,e.z),s.push(t.x,t.y,t.z),n.push(a/h,Si.UseOpenGLOrientationForUV?r/c:1-r/c)}for(r=0;r<c;r++)for(a=0;a<h;a++)t.push(a+1+(r+1)*(h+1)),t.push(a+1+r*(h+1)),t.push(a+r*(h+1)),t.push(a+(r+1)*(h+1)),t.push(a+1+(r+1)*(h+1)),t.push(a+r*(h+1));const u=new vi;return u.indices=t,u.positions=i,u.normals=s,u.uvs=n,u}function Qr(e){const t=void 0!==e.xmin&&null!==e.xmin?e.xmin:-1,i=void 0!==e.zmin&&null!==e.zmin?e.zmin:-1,s=void 0!==e.xmax&&null!==e.xmax?e.xmax:1,n=void 0!==e.zmax&&null!==e.zmax?e.zmax:1,r=e.subdivisions||{w:1,h:1},a=e.precision||{w:1,h:1},o=[],l=[],h=[],c=[];let u,d,_,f;r.h=r.h<1?1:r.h,r.w=r.w<1?1:r.w,a.w=a.w<1?1:a.w,a.h=a.h<1?1:a.h;const m=(s-t)/r.w,p=(n-i)/r.h;function g(e,t,i,s){const n=l.length/3,r=a.w+1;for(u=0;u<a.h;u++)for(d=0;d<a.w;d++){const e=[n+d+u*r,n+(d+1)+u*r,n+(d+1)+(u+1)*r,n+d+(u+1)*r];o.push(e[1]),o.push(e[2]),o.push(e[3]),o.push(e[0]),o.push(e[1]),o.push(e[3])}const _=B.Zero(),f=new B(0,1,0);for(u=0;u<=a.h;u++)for(_.z=u*(s-t)/a.h+t,d=0;d<=a.w;d++)_.x=d*(i-e)/a.w+e,_.y=0,l.push(_.x,_.y,_.z),h.push(f.x,f.y,f.z),c.push(d/a.w,u/a.h)}for(_=0;_<r.h;_++)for(f=0;f<r.w;f++)g(t+f*m,i+_*p,t+(f+1)*m,i+(_+1)*p);const E=new vi;return E.indices=o,E.positions=l,E.normals=h,E.uvs=c,E}function jr(e){const t=[],i=[],s=[],n=[];let r,a;const o=e.colorFilter||new J(.3,.59,.11),l=e.alphaFilter||0;let h=!1;if(e.minHeight>e.maxHeight){h=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(r=0;r<=e.subdivisions;r++)for(a=0;a<=e.subdivisions;a++){const t=new B(a*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-r)*e.height/e.subdivisions-e.height/2),c=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[c]/255,d=e.buffer[c+1]/255,_=e.buffer[c+2]/255;const f=e.buffer[c+3]/255;h&&(u=1-u,d=1-d,_=1-_);const m=u*o.r+d*o.g+_*o.b;t.y=f>=l?e.minHeight+(e.maxHeight-e.minHeight)*m:e.minHeight-A,e.heightBuffer&&(e.heightBuffer[r*(e.subdivisions+1)+a]=t.y),i.push(t.x,t.y,t.z),s.push(0,0,0),n.push(a/e.subdivisions,1-r/e.subdivisions)}for(r=0;r<e.subdivisions;r++)for(a=0;a<e.subdivisions;a++){const s=a+1+(r+1)*(e.subdivisions+1),n=a+1+r*(e.subdivisions+1),o=a+r*(e.subdivisions+1),l=a+(r+1)*(e.subdivisions+1),h=i[3*s+1]>=e.minHeight,c=i[3*n+1]>=e.minHeight,u=i[3*o+1]>=e.minHeight;h&&c&&u&&(t.push(s),t.push(n),t.push(o));i[3*l+1]>=e.minHeight&&h&&u&&(t.push(l),t.push(s),t.push(o))}vi.ComputeNormals(i,t,s);const c=new vi;return c.indices=t,c.positions=i,c.normals=s,c.uvs=n,c}function Zr(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 i=[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],s=[];let n=[];const r=e.width||e.size||1,a=e.height||e.size||1,o=e.depth||e.size||1,l=e.wrap||!1;let h=void 0===e.topBaseAt?1:e.topBaseAt,c=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,c=(c+4)%4;let u=[2,0,3,1][h],d=[2,0,1,3][c],_=[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(l){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],_=[-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]],i=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const s=[17,18,19,16],n=[22,23,20,21];for(;u>0;)e.unshift(e.pop()),s.unshift(s.pop()),u--;for(;d>0;)i.unshift(i.pop()),n.unshift(n.pop()),d--;e=e.flat(),i=i.flat(),_=_.concat(e).concat(i),t.push(s[0],s[2],s[3],s[0],s[1],s[2]),t.push(n[0],n[2],n[3],n[0],n[1],n[2])}const f=[r/2,a/2,o/2];n=_.reduce(((e,t,i)=>e.concat(t*f[i%3])),[]);const m=0===e.sideOrientation?0:e.sideOrientation||vi.DEFAULTSIDE,p=e.faceUV||new Array(6),g=e.faceColors,E=[];for(let e=0;e<6;e++)void 0===p[e]&&(p[e]=new U(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new ee(1,1,1,1));for(let e=0;e<6;e++)if(s.push(p[e].z,Si.UseOpenGLOrientationForUV?1-p[e].w:p[e].w),s.push(p[e].x,Si.UseOpenGLOrientationForUV?1-p[e].w:p[e].w),s.push(p[e].x,Si.UseOpenGLOrientationForUV?1-p[e].y:p[e].y),s.push(p[e].z,Si.UseOpenGLOrientationForUV?1-p[e].y:p[e].y),g)for(let t=0;t<4;t++)E.push(g[e].r,g[e].g,g[e].b,g[e].a);vi._ComputeSides(m,n,t,i,s,e.frontUVs,e.backUVs);const T=new vi;if(T.indices=t,T.positions=n,T.normals=i,T.uvs=s,g){const e=m===vi.DOUBLESIDE?E.concat(E):E;T.colors=e}return T}function $r(e,t={},i=null){const s=new gs(e,i);t.sideOrientation=gs._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation;return Zr(t).applyToMesh(s,t.updatable),s}vi.CreateGround=qr,vi.CreateTiledGround=Qr,vi.CreateGroundFromHeightMap=jr,gs.CreateGround=(e,t,i,s,n,r)=>function(e,t={},i){const s=new Kr(e,i);return s._setReady(!1),s._subdivisionsX=t.subdivisionsX||t.subdivisions||1,s._subdivisionsY=t.subdivisionsY||t.subdivisions||1,s._width=t.width||1,s._height=t.height||1,s._maxX=s._width/2,s._maxZ=s._height/2,s._minX=-s._maxX,s._minZ=-s._maxZ,qr(t).applyToMesh(s,t.updatable),s._setReady(!0),s}(e,{width:t,height:i,subdivisions:s,updatable:r},n),gs.CreateTiledGround=(e,t,i,s,n,r,a,o,l)=>function(e,t,i=null){const s=new gs(e,i);return Qr(t).applyToMesh(s,t.updatable),s}(e,{xmin:t,zmin:i,xmax:s,zmax:n,subdivisions:r,precision:a,updatable:l},o),gs.CreateGroundFromHeightMap=(e,t,i,s,n,r,a,o,l,h,c)=>function(e,t,i={},s=null){const n=i.width||10,r=i.height||10,a=i.subdivisions||1,o=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new J(.3,.59,.11),c=i.alphaFilter||0,u=i.updatable,d=i.onReady;s=s||M.LastCreatedScene;const _=new Kr(e,s);let f;_._subdivisionsX=a,_._subdivisionsY=a,_._width=n,_._height=r,_._maxX=_._width/2,_._maxZ=_._height/2,_._minX=-_._maxX,_._minZ=-_._maxZ,_._setReady(!1),i.passHeightBufferInCallback&&(f=new Float32Array((a+1)*(a+1)));const m=(e,t,i)=>{jr({width:n,height:r,subdivisions:a,minHeight:o,maxHeight:l,colorFilter:h,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:c,heightBuffer:f}).applyToMesh(_,u),d&&d(_,f),_._setReady(!0)};if("string"==typeof t){const e=e=>{const t=e.width,i=e.height;if(s.isDisposed)return;const n=s?.getEngine().resizeImageBitmap(e,t,i);m(n,t,i)};Qt.LoadImage(t,e,i.onError?i.onError:()=>{},s.offlineProvider)}else m(t.data,t.width,t.height);return _}(e,t,{width:i,height:s,subdivisions:n,minHeight:r,maxHeight:a,updatable:l,onReady:h,alphaFilter:c},o),vi.CreateBox=Zr,gs.CreateBox=(e,t,i=null,s,n)=>$r(e,{size:t,sideOrientation:n,updatable:s},i);class Jr{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}}class ea{constructor(){this._currentOperation=Promise.resolve()}lockAsync(e,t){t?.throwIfAborted();const i=t?()=>(t.throwIfAborted(),e()):e,s=this._currentOperation.then(i);return this._currentOperation=new Promise((e=>s.then((()=>e()),e))),s}static async LockAsync(e,t,i){if(i?.throwIfAborted(),0===t.length)return await e();const s=new Jr;let n=0;return t.forEach((r=>r.lockAsync((async()=>(n++,n===t.length&&s.resolve(await e()),s.promise)),i).catch((e=>s.reject(e))))),s.promise}}class ta{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,s){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._yoyoDirection=1,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=s,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===Ls.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=G.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,0!==this._minFrame){const e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(const t of this._target)this._preparePath(t,e),this._getOriginalValues(e),e++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const n=t.getEvents();n&&n.length>0&&n.forEach((e=>{this._events.push(e._clone())})),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){const i=this._animation.targetPropertyPath;if(i.length>1){let s=e;for(let e=0;e<i.length-1;e++){const t=i[e];if(s=s[t],void 0===s)throw new Error(`Invalid property (${t}) in property path (${i.join(".")})`)}this._targetPath=i[i.length-1],this._activeTargets[t]=s}else this._targetPath=i[0],this._activeTargets[t]=e;if(void 0===this._activeTargets[t][this._targetPath])throw new Error(`Invalid property (${this._targetPath}) in property path (${i.join(".")})`)}get animation(){return this._animation}reset(e=!1){if(e)if(this._target instanceof Array){let e=0;for(const t of this._target)void 0!==this._originalValue[e]&&this._setValue(t,this._activeTargets[e],this._originalValue[e],-1,e),e++}else void 0!==this._originalValue[0]&&this._setValue(this._target,this._directTarget,this._originalValue[0],-1,0);this._offsetsCache={},this._highLimitsCache={},this._currentFrame=0,this._blendingFactor=0;for(let e=0;e<this._events.length;e++)this._events[e].isDone=!1}isStopped(){return this._stopped}dispose(){const e=this._animation.runtimeAnimations.indexOf(this);e>-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let i=0;i<this._target.length;i++){const s=this._target[i];this._setValue(s,this._activeTargets[i],e,t,i)}else this._setValue(this._target,this._directTarget,e,t,0)}_getOriginalValues(e=0){let t;const i=this._activeTargets[e];t=i.getLocalMatrix&&"_matrix"===this._targetPath?i.getLocalMatrix():i[this._targetPath],t&&t.clone?this._originalValue[e]=t.clone():this._originalValue[e]=t}_setValue(e,t,i,s,n){if(this._currentActiveTarget=t,this._weight=s,this._enableBlending&&this._blendingFactor<=1){if(!this._originalBlendValue){const e=t[this._targetPath];e.clone?this._originalBlendValue=e.clone():this._originalBlendValue=e}this._originalBlendValue.m?Ls.AllowMatrixDecomposeForInterpolation?this._currentValue?G.DecomposeLerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=G.DecomposeLerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue?G.LerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=G.Lerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue=Ls._UniversalLerp(this._originalBlendValue,i,this._blendingFactor);const s=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.blendingSpeed:this._animation.blendingSpeed;this._blendingFactor+=s}else this._currentValue?this._currentValue.copyFrom?this._currentValue.copyFrom(i):this._currentValue=i:this._currentValue=i?.clone?i.clone():i;-1!==s?this._scene._registerTargetForLateAnimationBinding(this,this._originalValue[n]):this._animationState.loopMode===Ls.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT?this._currentValue.addToRef?this._currentValue.addToRef(this._originalValue[n],t[this._targetPath]):t[this._targetPath]=this._originalValue[n]+this._currentValue:t[this._targetPath]=this._currentValue,e.markAsDirty&&e.markAsDirty(this._animation.targetProperty)}_getCorrectLoopMode(){return this._target&&this._target.animationPropertiesOverride?this._target.animationPropertiesOverride.loopMode:this._animation.loopMode}goToFrame(e,t=-1){const i=this._animation.getKeys();e<i[0].frame?e=i[0].frame:e>i[i.length-1].frame&&(e=i[i.length-1].frame);const s=this._events;if(s.length)for(let t=0;t<s.length;t++)s[t].onlyOnce||(s[t].isDone=s[t].frame<e);this._currentFrame=e;const n=this._animation._interpolate(e,this._animationState);this.setValue(n,t)}_prepareForSpeedRatioChange(e){const t=this._previousElapsedTime*(this._animation.framePerSecond*e)/1e3;this._absoluteFrameOffset=this._previousAbsoluteFrame-t}animate(e,t,i,s,n,r=-1){const a=this._animation,o=a.targetPropertyPath;if(!o||o.length<1)return this._stopped=!0,!1;let l=!0;(t<this._minFrame||t>this._maxFrame)&&(t=this._minFrame),(i<this._minFrame||i>this._maxFrame)&&(i=this._maxFrame);const h=i-t;let c,u=e*(a.framePerSecond*n)/1e3+this._absoluteFrameOffset,d=0,_=!1;const f=s&&this._animationState.loopMode===Ls.ANIMATIONLOOPMODE_YOYO;if(f){const e=(u-t)/h,i=Math.sin(e*Math.PI);u=Math.abs(i)*h+t;const s=i>=0?1:-1;this._yoyoDirection!==s&&(_=!0),this._yoyoDirection=s}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=u,!s&&i>=t&&(u>=h&&n>0||u<=0&&n<0))l=!1,d=a._getKeyValue(this._maxValue);else if(!s&&t>=i&&(u<=h&&n<0||u>=0&&n>0))l=!1,d=a._getKeyValue(this._minValue);else if(this._animationState.loopMode!==Ls.ANIMATIONLOOPMODE_CYCLE){const e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=Ls.ANIMATIONLOOPMODE_CYCLE;const s=a._interpolate(t,this._animationState),n=a._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),a.dataType){case Ls.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=n-s;break;case Ls.ANIMATIONTYPE_QUATERNION:case Ls.ANIMATIONTYPE_VECTOR3:case Ls.ANIMATIONTYPE_VECTOR2:case Ls.ANIMATIONTYPE_SIZE:case Ls.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=n.subtract(s)}this._highLimitsCache[e]=n}d=this._highLimitsCache[e],c=this._offsetsCache[e]}if(void 0===c)switch(a.dataType){case Ls.ANIMATIONTYPE_FLOAT:c=0;break;case Ls.ANIMATIONTYPE_QUATERNION:c=ys;break;case Ls.ANIMATIONTYPE_VECTOR3:c=Ms;break;case Ls.ANIMATIONTYPE_VECTOR2:c=xs;break;case Ls.ANIMATIONTYPE_SIZE:c=Os;break;case Ls.ANIMATIONTYPE_COLOR3:c=Ds;break;case Ls.ANIMATIONTYPE_COLOR4:c=Ps}let m;if(this._host&&this._host.syncRoot){const e=this._host.syncRoot;m=t+h*((e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame))}else m=u>0&&t>i||u<0&&t<i?l&&0!==h?i+u%h:t:l&&0!==h?t+u%h:i;const p=this._events;if(!f&&(n>0&&this.currentFrame>m||n<0&&this.currentFrame<m)||f&&_){this._onLoop();for(let e=0;e<p.length;e++)p[e].onlyOnce||(p[e].isDone=!1);this._animationState.key=n>0?0:a.getKeys().length-1}this._currentFrame=m,this._animationState.repeatCount=0===h?0:u/h|0,this._animationState.highLimitValue=d,this._animationState.offsetValue=c;const g=a._interpolate(m,this._animationState);if(this.setValue(g,r),p.length)for(let e=0;e<p.length;e++)if(h>=0&&m>=p[e].frame&&p[e].frame>=t||h<0&&m<=p[e].frame&&p[e].frame<=t){const t=p[e];t.isDone||(t.onlyOnce&&(p.splice(e,1),e--),t.isDone=!0,t.action(m))}return l||(this._stopped=!0),l}}class ia extends re{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,s=null,n=null,r=null,a=null){super(e,t.getScene(),!1),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=s?.clone()??G.Identity(),this._restMatrix=n??this._localMatrix.clone(),this._bindMatrix=r??this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new G,this._absoluteBindMatrix=new G,this._absoluteInverseBindMatrix=new G,this._finalMatrix=new G,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return null===this._index?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){const e=this.parent.children.indexOf(this);-1!==e&&this.parent.children.splice(e,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){if(this._linkedTransformNode){const e=X.Vector3[0],t=X.Quaternion[0],i=X.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??k.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(t),this._linkedTransformNode.scaling.copyFrom(e)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=B.Zero(),this._localRotation=k.Zero(),this._localPosition=B.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,G.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let e=0;e<this.children.length;e++)this.children[e]._updateAbsoluteBindMatrices();this._scalingDeterminant=this._absoluteBindMatrix.determinant()<0?-1:1}markAsDirty(){return this._currentRenderId++,this._childUpdateId++,this._skeleton._markAsDirty(),this}_markAsDirtyAndCompose(){this.markAsDirty(),this._needToCompose=!0}_markAsDirtyAndDecompose(){this.markAsDirty(),this._needToDecompose=!0}_updatePosition(e,t=0,i,s=!0){const n=this.getLocalMatrix();if(0==t)s?(n.addAtIndex(12,e.x),n.addAtIndex(13,e.y),n.addAtIndex(14,e.z)):n.setTranslationFromFloats(e.x,e.y,e.z);else{let t=null;i&&(t=i.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const r=ia._TmpMats[0],a=ia._TmpVecs[0];this.parent?i&&t?(r.copyFrom(this.parent.getAbsoluteMatrix()),r.multiplyToRef(t,r)):r.copyFrom(this.parent.getAbsoluteMatrix()):G.IdentityToRef(r),s&&r.setTranslationFromFloats(0,0,0),r.invert(),B.TransformCoordinatesToRef(e,r,a),s?(n.addAtIndex(12,a.x),n.addAtIndex(13,a.y),n.addAtIndex(14,a.z)):n.setTranslationFromFloats(a.x,a.y,a.z)}this._markAsDirtyAndDecompose()}translate(e,t=0,i){this._updatePosition(e,t,i,!0)}setPosition(e,t=0,i){this._updatePosition(e,t,i,!1)}setAbsolutePosition(e,t){this.setPosition(e,1,t)}scale(e,t,i,s=!1){const n=this.getLocalMatrix(),r=ia._TmpMats[0];G.ScalingToRef(e,t,i,r),r.multiplyToRef(n,n),r.invert();for(const s of this.children){const n=s.getLocalMatrix();n.multiplyToRef(r,n),n.multiplyAtIndex(12,e),n.multiplyAtIndex(13,t),n.multiplyAtIndex(14,i),s._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),s)for(const n of this.children)n.scale(e,t,i,s)}setScale(e){this._decompose(),this._localScaling.copyFrom(e),this._markAsDirtyAndCompose()}getScale(){return this._decompose(),this._localScaling}getScaleToRef(e){this._decompose(),e.copyFrom(this._localScaling)}setYawPitchRoll(e,t,i,s=0,n){if(0===s){const r=ia._TmpQuat;return k.RotationYawPitchRollToRef(e,t,i,r),void this.setRotationQuaternion(r,s,n)}const r=ia._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,n))return;const a=ia._TmpMats[1];G.RotationYawPitchRollToRef(e,t,i,a),r.multiplyToRef(a,a),this._rotateWithMatrix(a,s,n)}rotate(e,t,i=0,s){const n=ia._TmpMats[0];n.setTranslationFromFloats(0,0,0),G.RotationAxisToRef(e,t,n),this._rotateWithMatrix(n,i,s)}setAxisAngle(e,t,i=0,s){if(0===i){const n=ia._TmpQuat;return k.RotationAxisToRef(e,t,n),void this.setRotationQuaternion(n,i,s)}const n=ia._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(n,s))return;const r=ia._TmpMats[1];G.RotationAxisToRef(e,t,r),n.multiplyToRef(r,r),this._rotateWithMatrix(r,i,s)}setRotation(e,t=0,i){this.setYawPitchRoll(e.y,e.x,e.z,t,i)}setRotationQuaternion(e,t=0,i){if(0===t)return this._decompose(),this._localRotation.copyFrom(e),void this._markAsDirtyAndCompose();const s=ia._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(s,i))return;const n=ia._TmpMats[1];G.FromQuaternionToRef(e,n),s.multiplyToRef(n,n),this._rotateWithMatrix(n,t,i)}setRotationMatrix(e,t=0,i){if(0===t){const s=ia._TmpQuat;return k.FromRotationMatrixToRef(e,s),void this.setRotationQuaternion(s,t,i)}const s=ia._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(s,i))return;const n=ia._TmpMats[1];n.copyFrom(e),s.multiplyToRef(e,n),this._rotateWithMatrix(n,t,i)}_rotateWithMatrix(e,t=0,i){const s=this.getLocalMatrix(),n=s.m[12],r=s.m[13],a=s.m[14],o=this.getParent(),l=ia._TmpMats[3],h=ia._TmpMats[4];o&&1==t?(i?(l.copyFrom(i.getWorldMatrix()),o.getAbsoluteMatrix().multiplyToRef(l,l)):l.copyFrom(o.getAbsoluteMatrix()),h.copyFrom(l),h.invert(),s.multiplyToRef(l,s),s.multiplyToRef(e,s),s.multiplyToRef(h,s)):1==t&&i?(l.copyFrom(i.getWorldMatrix()),h.copyFrom(l),h.invert(),s.multiplyToRef(l,s),s.multiplyToRef(e,s),s.multiplyToRef(h,s)):s.multiplyToRef(e,s),s.setTranslationFromFloats(n,r,a),this.computeAbsoluteMatrices(),this._markAsDirtyAndDecompose()}_getAbsoluteInverseMatrixUnscaledToRef(e,t){const i=ia._TmpMats[2];return e.copyFrom(this.getAbsoluteMatrix()),t?(e.multiplyToRef(t.getWorldMatrix(),e),G.ScalingToRef(t.scaling.x,t.scaling.y,t.scaling.z,i)):G.IdentityToRef(i),e.invert(),!isNaN(e.m[0])&&(i.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(i,e),!0)}getPosition(e=0,t=null){const i=B.Zero();return this.getPositionToRef(e,t,i),i}getPositionToRef(e=0,t,i){if(0==e){const e=this.getLocalMatrix();i.x=e.m[12],i.y=e.m[13],i.z=e.m[14]}else{let e=null;t&&(e=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let s=ia._TmpMats[0];t&&e?(s.copyFrom(this.getAbsoluteMatrix()),s.multiplyToRef(e,s)):s=this.getAbsoluteMatrix(),i.x=s.m[12],i.y=s.m[13],i.z=s.m[14]}}getAbsolutePosition(e=null){const t=B.Zero();return this.getPositionToRef(1,e,t),t}getAbsolutePositionToRef(e,t){this.getPositionToRef(1,e,t)}computeAbsoluteMatrices(){if(this._compose(),this.parent)this._localMatrix.multiplyToRef(this.parent._absoluteMatrix,this._absoluteMatrix);else{this._absoluteMatrix.copyFrom(this._localMatrix);const e=this._skeleton.getPoseMatrix();e&&this._absoluteMatrix.multiplyToRef(e,this._absoluteMatrix)}const e=this.children,t=e.length;for(let i=0;i<t;i++)e[i].computeAbsoluteMatrices()}computeAbsoluteTransforms(){this.computeAbsoluteMatrices()}getDirection(e,t=null){const i=B.Zero();return this.getDirectionToRef(e,t,i),i}getDirectionToRef(e,t=null,i){let s=null;t&&(s=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const n=ia._TmpMats[0];n.copyFrom(this.getAbsoluteMatrix()),t&&s&&n.multiplyToRef(s,n),B.TransformNormalToRef(e,n,i),i.normalize()}getRotation(e=0,t=null){const i=B.Zero();return this.getRotationToRef(e,t,i),i}getRotationToRef(e=0,t=null,i){const s=ia._TmpQuat;this.getRotationQuaternionToRef(e,t,s),s.toEulerAnglesToRef(i)}getRotationQuaternion(e=0,t=null){const i=k.Identity();return this.getRotationQuaternionToRef(e,t,i),i}getRotationQuaternionToRef(e=0,t=null,i){if(0==e)this._decompose(),i.copyFrom(this._localRotation);else{const e=ia._TmpMats[0],s=this.getAbsoluteMatrix();t?s.multiplyToRef(t.getWorldMatrix(),e):e.copyFrom(s),e.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyAtIndex(1,this._scalingDeterminant),e.multiplyAtIndex(2,this._scalingDeterminant),e.decompose(void 0,i,void 0)}}getRotationMatrix(e=0,t){const i=G.Identity();return this.getRotationMatrixToRef(e,t,i),i}getRotationMatrixToRef(e=0,t,i){if(0==e)this.getLocalMatrix().getRotationMatrixToRef(i);else{const e=ia._TmpMats[0],s=this.getAbsoluteMatrix();t?s.multiplyToRef(t.getWorldMatrix(),e):e.copyFrom(s),e.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyAtIndex(1,this._scalingDeterminant),e.multiplyAtIndex(2,this._scalingDeterminant),e.getRotationMatrixToRef(i)}}getAbsolutePositionFromLocal(e,t=null){const i=B.Zero();return this.getAbsolutePositionFromLocalToRef(e,t,i),i}getAbsolutePositionFromLocalToRef(e,t=null,i){let s=null;t&&(s=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const n=ia._TmpMats[0];n.copyFrom(this.getAbsoluteMatrix()),t&&s&&n.multiplyToRef(s,n),B.TransformCoordinatesToRef(e,n,i)}getLocalPositionFromAbsolute(e,t=null){const i=B.Zero();return this.getLocalPositionFromAbsoluteToRef(e,t,i),i}getLocalPositionFromAbsoluteToRef(e,t=null,i){let s=null;t&&(s=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const n=ia._TmpMats[0];n.copyFrom(this.getAbsoluteMatrix()),t&&s&&n.multiplyToRef(s,n),n.invert(),B.TransformCoordinatesToRef(e,n,i)}setCurrentPoseAsRest(){this.setRestMatrix(this.getLocalMatrix())}}ia._TmpVecs=R.BuildArray(2,B.Zero),ia._TmpQuat=k.Identity(),ia._TmpMats=R.BuildArray(5,G.Identity);class sa{get syncRoot(){return this._syncRoot}get masterFrame(){return 0===this._runtimeAnimations.length?0:this._runtimeAnimations[0].currentFrame}get weight(){return this._weight}set weight(e){this._weight=-1!==e?Math.min(Math.max(e,0),1):-1}get speedRatio(){return this._speedRatio}set speedRatio(e){for(let t=0;t<this._runtimeAnimations.length;t++){this._runtimeAnimations[t]._prepareForSpeedRatioChange(e)}this._speedRatio=e,null!==this._goToFrame&&this.goToFrame(this._goToFrame)}get elapsedTime(){return null===this._localDelayOffset?0:this._scene._animationTime-this._localDelayOffset}constructor(e,t,i=0,s=100,n=!1,r=1,a,o,l,h=!1,c=0){this.target=t,this.fromFrame=i,this.toFrame=s,this.loopAnimation=n,this.onAnimationEnd=a,this.onAnimationLoop=l,this.isAdditive=h,this.playOrder=c,this._localDelayOffset=null,this._pausedDelay=null,this._manualJumpDelay=null,this._runtimeAnimations=new Array,this._paused=!1,this._speedRatio=1,this._weight=-1,this._syncRoot=null,this._frameToSyncFromJump=null,this._goToFrame=null,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new g,this.onAnimationLoopObservable=new g,this._scene=e,o&&this.appendAnimations(t,o),this._speedRatio=r,e._activeAnimatables.push(this)}syncWith(e){if(this._syncRoot=e,e){const e=this._scene._activeAnimatables.indexOf(this);e>-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i<t.length;i++){const s=t[i],n=new ta(e,s,this._scene,this);n._onLoop=()=>{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(n)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i].animation;return null}getRuntimeAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i];return null}reset(){const e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].reset(!0);this._localDelayOffset=null,this._pausedDelay=null}enableBlending(e){const t=this._runtimeAnimations;for(let i=0;i<t.length;i++)t[i].animation.enableBlending=!0,t[i].animation.blendingSpeed=e}disableBlending(){const e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].animation.enableBlending=!1}goToFrame(e){const t=this._runtimeAnimations;if(t[0]){const i=t[0].animation.framePerSecond;this._frameToSyncFromJump=this._frameToSyncFromJump??t[0].currentFrame;const s=0===this.speedRatio?0:(e-this._frameToSyncFromJump)/i*1e3/this.speedRatio;this._manualJumpDelay=-s}for(let i=0;i<t.length;i++)t[i].goToFrame(e,this._weight);this._goToFrame=e}get paused(){return this._paused}pause(){this._paused||(this._paused=!0)}restart(){this._paused=!1}_raiseOnAnimationEnd(){this.onAnimationEnd&&this.onAnimationEnd(),this.onAnimationEndObservable.notifyObservers(this)}stop(e,t,i=!1,s=!1){if(e||t){const n=this._scene._activeAnimatables.indexOf(this);if(n>-1){const r=this._runtimeAnimations;for(let i=r.length-1;i>=0;i--){const s=r[i];e&&s.animation.name!=e||(t&&!t(s.target)||(s.dispose(),r.splice(i,1)))}0==r.length&&(i||this._scene._activeAnimatables.splice(n,1),s||this._raiseOnAnimationEnd())}}else{const e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);const t=this._runtimeAnimations;for(let e=0;e<t.length;e++)t[e].dispose();this._runtimeAnimations.length=0,s||this._raiseOnAnimationEnd()}}}waitAsync(){return new Promise((e=>{this.onAnimationEndObservable.add((()=>{e(this)}),void 0,void 0,this,!0)}))}_animate(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;let t=!1;const i=this._runtimeAnimations;let s;for(s=0;s<i.length;s++){const n=i[s].animate(e-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this._speedRatio,this._weight);t=t||n}if(this.animationStarted=t,!t){if(this.disposeOnEnd)for(s=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(s,1),s=0;s<i.length;s++)i[s].dispose();this._raiseOnAnimationEnd(),this.disposeOnEnd&&(this.onAnimationEnd=null,this.onAnimationLoop=null,this.onAnimationLoopObservable.clear(),this.onAnimationEndObservable.clear())}return t}}Dn.prototype._animate=function(e){if(!this.animationsEnabled)return;const t=_e.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=t}this.deltaTime=void 0!==e?e:this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=t;const i=this._activeAnimatables;if(0===i.length)return;this._animationTime+=this.deltaTime;const s=this._animationTime;for(let e=0;e<i.length;e++){const t=i[e];!t._animate(s)&&t.disposeOnEnd&&e--}this._processLateAnimationBindings()},Dn.prototype.sortActiveAnimatables=function(){this._activeAnimatables.sort(((e,t)=>e.playOrder-t.playOrder))},Dn.prototype.beginWeightedAnimation=function(e,t,i,s=1,n,r=1,a,o,l,h,c=!1){const u=this.beginAnimation(e,t,i,n,r,a,o,!1,l,h,c);return u.weight=s,u},Dn.prototype.beginAnimation=function(e,t,i,s,n=1,r,a,o=!0,l,h,c=!1){t>i&&n>0&&(n*=-1),o&&this.stopAnimation(e,void 0,l),a||(a=new sa(this,e,t,i,s,n,r,void 0,h,c));const u=!l||l(e);if(e.animations&&u&&a.appendAnimations(e,e.animations),e.getAnimatables){const c=e.getAnimatables();for(let e=0;e<c.length;e++)this.beginAnimation(c[e],t,i,s,n,r,a,o,l,h)}return a.reset(),a},Dn.prototype.beginHierarchyAnimation=function(e,t,i,s,n,r=1,a,o,l=!0,h,c,u=!1){const d=e.getDescendants(t),_=[];_.push(this.beginAnimation(e,i,s,n,r,a,o,l,h,void 0,u));for(const e of d)_.push(this.beginAnimation(e,i,s,n,r,a,o,l,h,void 0,u));return _},Dn.prototype.beginDirectAnimation=function(e,t,i,s,n,r,a,o,l=!1){if(void 0===r&&(r=1),i>s&&r>0)r*=-1;else if(s>i&&r<0){const e=s;s=i,i=e}return new sa(this,e,i,s,n,r,a,t,o,l)},Dn.prototype.beginDirectHierarchyAnimation=function(e,t,i,s,n,r,a,o,l,h=!1){const c=e.getDescendants(t),u=[];u.push(this.beginDirectAnimation(e,i,s,n,r,a,o,l,h));for(const e of c)u.push(this.beginDirectAnimation(e,i,s,n,r,a,o,l,h));return u},Dn.prototype.getAnimatableByTarget=function(e){for(let t=0;t<this._activeAnimatables.length;t++)if(this._activeAnimatables[t].target===e)return this._activeAnimatables[t];return null},Dn.prototype.getAllAnimatablesByTarget=function(e){const t=[];for(let i=0;i<this._activeAnimatables.length;i++)this._activeAnimatables[i].target===e&&t.push(this._activeAnimatables[i]);return t},Dn.prototype.stopAnimation=function(e,t,i){const s=this.getAllAnimatablesByTarget(e);for(const e of s)e.stop(t,i)},Dn.prototype.stopAllAnimations=function(){if(this._activeAnimatables){for(let e=0;e<this._activeAnimatables.length;e++)this._activeAnimatables[e].stop(void 0,void 0,!0);this._activeAnimatables.length=0}for(const e of this.animationGroups)e.stop()},Dn.prototype._registerTargetForLateAnimationBinding=function(e,t){const i=e.target;this._registeredForLateAnimationBindings.pushNoDuplicate(i),i._lateAnimationHolders||(i._lateAnimationHolders={}),i._lateAnimationHolders[e.targetPath]||(i._lateAnimationHolders[e.targetPath]={totalWeight:0,totalAdditiveWeight:0,animations:[],additiveAnimations:[],originalValue:t}),e.isAdditive?(i._lateAnimationHolders[e.targetPath].additiveAnimations.push(e),i._lateAnimationHolders[e.targetPath].totalAdditiveWeight+=e.weight):(i._lateAnimationHolders[e.targetPath].animations.push(e),i._lateAnimationHolders[e.targetPath].totalWeight+=e.weight)},Dn.prototype._processLateAnimationBindingsForMatrices=function(e){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return e.originalValue;let t=1;const i=X.Vector3[0],s=X.Vector3[1],n=X.Quaternion[0];let r=0;const a=e.animations[0],o=e.originalValue;let l=1,h=!1;if(e.totalWeight<1)l=1-e.totalWeight,o.decompose(s,n,i);else{if(r=1,t=e.totalWeight,l=a.weight/t,1==l){if(!e.totalAdditiveWeight)return a.currentValue;h=!0}a.currentValue.decompose(s,n,i)}if(!h){s.scaleInPlace(l),i.scaleInPlace(l),n.scaleInPlace(l);for(let a=r;a<e.animations.length;a++){const r=e.animations[a];if(0===r.weight)continue;l=r.weight/t;const o=X.Vector3[2],h=X.Vector3[3],c=X.Quaternion[1];r.currentValue.decompose(h,c,o),h.scaleAndAddToRef(l,s),c.scaleAndAddToRef(k.Dot(n,c)>0?l:-l,n),o.scaleAndAddToRef(l,i)}n.normalize()}for(let t=0;t<e.additiveAnimations.length;t++){const r=e.additiveAnimations[t];if(0===r.weight)continue;const a=X.Vector3[2],o=X.Vector3[3],l=X.Quaternion[1];r.currentValue.decompose(o,l,a),o.multiplyToRef(s,o),B.LerpToRef(s,o,r.weight,s),n.multiplyToRef(l,l),k.SlerpToRef(n,l,r.weight,n),a.scaleAndAddToRef(r.weight,i)}const c=a?a._animationState.workValue:X.Matrix[0].clone();return G.ComposeToRef(s,n,i,c),c},Dn.prototype._processLateAnimationBindingsForQuaternions=function(e,t){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return t;const i=e.animations[0],s=e.originalValue;let n=t;if(0===e.totalWeight&&e.totalAdditiveWeight>0)n.copyFrom(s);else if(1===e.animations.length){if(k.SlerpToRef(s,i.currentValue,Math.min(1,e.totalWeight),n),0===e.totalAdditiveWeight)return n}else if(e.animations.length>1){let i,r,a=1;if(e.totalWeight<1){const t=1-e.totalWeight;i=[],r=[],i.push(s),r.push(t)}else{if(2===e.animations.length&&(k.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],r=[],a=e.totalWeight}for(let t=0;t<e.animations.length;t++){const s=e.animations[t];i.push(s.currentValue),r.push(s.weight/a)}let o=0;for(let e=0;e<i.length;)e?(o+=r[e],k.SlerpToRef(n,i[e],r[e]/o,n),e++):(k.SlerpToRef(i[e],i[e+1],r[e+1]/(r[e]+r[e+1]),t),n=t,o=r[e]+r[e+1],e+=2)}for(let t=0;t<e.additiveAnimations.length;t++){const i=e.additiveAnimations[t];0!==i.weight&&(n.multiplyToRef(i.currentValue,X.Quaternion[0]),k.SlerpToRef(n,X.Quaternion[0],i.weight,n))}return n},Dn.prototype._processLateAnimationBindings=function(){if(this._registeredForLateAnimationBindings.length){for(let e=0;e<this._registeredForLateAnimationBindings.length;e++){const t=this._registeredForLateAnimationBindings.data[e];for(const e in t._lateAnimationHolders){const i=t._lateAnimationHolders[e],s=i.animations[0],n=i.originalValue;if(null==n)continue;const r=Ls.AllowMatrixDecomposeForInterpolation&&n.m;let a=t[e];if(r)a=this._processLateAnimationBindingsForMatrices(i);else{if(void 0!==n.w)a=this._processLateAnimationBindingsForQuaternions(i,a||k.Identity());else{let e=0,t=1;const r=s&&s._animationState.loopMode===Ls.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT;if(i.totalWeight<1)a=r?n.clone?n.clone():n:s&&n.scale?n.scale(1-i.totalWeight):s?n*(1-i.totalWeight):n.clone?n.clone():n;else if(s){t=i.totalWeight;const o=s.weight/t;a=1!==o?s.currentValue.scale?s.currentValue.scale(o):s.currentValue*o:s.currentValue,r&&(a.addToRef?a.addToRef(n,a):a+=n),e=1}for(let s=e;s<i.animations.length;s++){const e=i.animations[s],n=e.weight/t;n&&(e.currentValue.scaleAndAddToRef?e.currentValue.scaleAndAddToRef(n,a):a+=e.currentValue*n)}for(let e=0;e<i.additiveAnimations.length;e++){const t=i.additiveAnimations[e],s=t.weight;s&&(t.currentValue.scaleAndAddToRef?t.currentValue.scaleAndAddToRef(s,a):a+=t.currentValue*s)}}}t[e]=a}t._lateAnimationHolders={}}this._registeredForLateAnimationBindings.reset()}},ia.prototype.copyAnimationRange=function(e,t,i,s=!1,n=null){0===this.animations.length&&(this.animations.push(new Ls(this.name,"_matrix",e.animations[0].framePerSecond,Ls.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));const r=e.animations[0].getRange(t);if(!r)return!1;const a=r.from,o=r.to,l=e.animations[0].getKeys(),h=e.length,c=e.getParent(),u=this.getParent(),d=s&&c&&h&&this.length&&h!==this.length,_=d&&u&&c?u.length/c.length:1,f=s&&!u&&n&&(1!==n.x||1!==n.y||1!==n.z),m=this.animations[0].getKeys();let p,g,E;for(let e=0,t=l.length;e<t;e++)p=l[e],p.frame>=a&&p.frame<=o&&(s?(E=p.value.clone(),d?(g=E.getTranslation(),E.setTranslation(g.scaleInPlace(_))):f&&n?(g=E.getTranslation(),E.setTranslation(g.multiplyInPlace(n))):E=p.value):E=p.value,m.push({frame:p.frame+i,value:E}));return this.animations[0].createRange(t,a+i,o+i),!0};it.ShadersStore.rgbdEncodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include<helperFunctions>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}";const na="image/png",ra=2,aa=[134,22,135,150,246,214,150,54];function oa(e){if(e.version>ra)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "${ra}".`);return 2===e.version?e:e={...e,version:2,imageType:na}}function la(e,t,i){const s=(i=oa(i)).specular;if(!s)return Promise.resolve();e._lodGenerationScale=s.lodGenerationScale;const n=function(e,t){const i=(t=oa(t)).specular;let s=q.Log2(t.width);if(s=Math.round(s)+1,i.mipmaps.length!==6*s)throw new Error(`Unsupported specular mipmaps number "${i.mipmaps.length}"`);const n=new Array(s);for(let t=0;t<s;t++){n[t]=new Array(6);for(let s=0;s<6;s++){const r=i.mipmaps[6*t+s];n[t][s]=new Uint8Array(e.buffer,e.byteOffset+i.specularDataPosition+r.position,r.length)}}return n}(t,i);return ca(e,n,i.imageType)}function ha(e,t,i,s,n,r,a,o,l,h,c){return new Promise(((u,d)=>{if(i){const i=t.createTexture(null,!0,!0,null,tt.TEXTURE_NEAREST_SAMPLINGMODE,null,(e=>{d(e)}),e);s.getEffect().executeWhenCompiled((()=>{s.externalTextureSamplerBinding=!0,s.onApply=s=>{s._bindTexture("textureSampler",i),s.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([s],h,!0,r,a),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(n),u())}))}else{if(t._uploadImageToTexture(c,e,r,a),o){const i=l[a];i&&t._uploadImageToTexture(i._texture,e,r,0)}u()}}))}function ca(e,t,i=na){if(!Qt.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");const s=q.ILog2(e.width)+1,n=e.getEngine();let r=!1,a=!1,o=null,l=null,h=null;const c=n.getCaps();if(e.format=tt.TEXTUREFORMAT_RGBA,e.type=tt.TEXTURETYPE_UNSIGNED_INT,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,n.updateTextureSamplingMode(tt.TEXTURE_TRILINEAR_SAMPLINGMODE,e),c.textureLOD?n._features.supportRenderAndCopyToLodForFloatTextures?c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering?(r=!0,e.type=tt.TEXTURETYPE_HALF_FLOAT):c.textureFloatRender&&c.textureFloatLinearFiltering&&(r=!0,e.type=tt.TEXTURETYPE_FLOAT):r=!1:(r=!1,a=!0,h={}),r)o=new kn("rgbdDecode","rgbdDecode",null,null,1,null,tt.TEXTURE_TRILINEAR_SAMPLINGMODE,n,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,l=n.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:tt.TEXTURE_TRILINEAR_SAMPLINGMODE,type:e.type,format:tt.TEXTUREFORMAT_RGBA});else if(e._isRGBD=!0,e.invertY=!0,a){const t=3,i=e._lodGenerationScale,r=e._lodGenerationOffset;for(let a=0;a<t;a++){const o=(s-1)*i+r,l=r+(o-r)*(1-a/(t-1)),c=Math.round(Math.min(Math.max(l,0),o)),u=new vt(n,2);u.isCube=!0,u.invertY=!0,u.generateMipMaps=!1,n.updateTextureSamplingMode(tt.TEXTURE_LINEAR_LINEAR,u);const d=new Ln(null);switch(d._isCube=!0,d._texture=u,h[c]=d,a){case 0:e._lodTextureLow=d;break;case 1:e._lodTextureMid=d;break;case 2:e._lodTextureHigh=d}}}const u=[];for(let s=0;s<t.length;s++)for(let c=0;c<6;c++){const d=t[s][c],_=new Blob([d],{type:i}),f=URL.createObjectURL(_);let m;if(n._features.forceBitmapOverHTMLImageElement)m=n.createImageBitmap(_,{premultiplyAlpha:"none"}).then((t=>ha(t,n,r,o,f,c,s,a,h,l,e)));else{const t=new Image;t.src=f,m=new Promise(((i,u)=>{t.onload=()=>{ha(t,n,r,o,f,c,s,a,h,l,e).then((()=>i())).catch((e=>{u(e)}))},t.onerror=e=>{u(e)}}))}u.push(m)}if(t.length<s){let i;const r=Math.pow(2,s-1-t.length),a=r*r*4;switch(e.type){case tt.TEXTURETYPE_UNSIGNED_INT:i=new Uint8Array(a);break;case tt.TEXTURETYPE_HALF_FLOAT:i=new Uint16Array(a);break;case tt.TEXTURETYPE_FLOAT:i=new Float32Array(a)}for(let r=t.length;r<s;r++)for(let t=0;t<6;t++)n._uploadArrayBufferViewToTexture(e,i,t,r)}return Promise.all(u).then((()=>{l&&(n._releaseTexture(e),l._swapAndDie(e)),o&&o.dispose(),a&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))}))}Ui._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,s,n){if(Array.isArray(e))return;const r=function(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;for(let e=0;e<aa.length;e++)if(t.getUint8(i++)!==aa[e])return ce.Error("Not a babylon environment map"),null;let s="",n=0;for(;n=t.getUint8(i++);)s+=String.fromCharCode(n);let r=JSON.parse(s);return r=oa(r),r.specular&&(r.specular.specularDataPosition=i,r.specular.lodGenerationScale=r.specular.lodGenerationScale||.8),r}(e);if(r){t.width=r.width,t.height=r.width;try{!function(e,t){const i=(t=oa(t)).irradiance;if(!i)return;const s=new Er;B.FromArrayToRef(i.x,0,s.x),B.FromArrayToRef(i.y,0,s.y),B.FromArrayToRef(i.z,0,s.z),B.FromArrayToRef(i.xx,0,s.xx),B.FromArrayToRef(i.yy,0,s.yy),B.FromArrayToRef(i.zz,0,s.zz),B.FromArrayToRef(i.yz,0,s.yz),B.FromArrayToRef(i.zx,0,s.zx),B.FromArrayToRef(i.xy,0,s.xy),e._sphericalPolynomial=s}(t,r),la(t,e,r).then((()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}),(e=>{n?.("Can not upload environment levels",e)}))}catch(e){n?.("Can not upload environment file",e)}}else n&&n("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}});class ua{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=Qt.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===Hs.KEYDOWN){if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault()}}else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.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;for(let t=0;t<this._keys.length;t++){const i=this._keys[t],s=e._computeLocalCameraSpeed();-1!==this.keysLeft.indexOf(i)?e._localDirection.copyFromFloats(-s,0,0):-1!==this.keysUp.indexOf(i)?e._localDirection.copyFromFloats(0,0,s):-1!==this.keysRight.indexOf(i)?e._localDirection.copyFromFloats(s,0,0):-1!==this.keysDown.indexOf(i)?e._localDirection.copyFromFloats(0,0,-s):-1!==this.keysUpward.indexOf(i)?e._localDirection.copyFromFloats(0,s,0):-1!==this.keysDownward.indexOf(i)?e._localDirection.copyFromFloats(0,-s,0):-1!==this.keysRotateLeft.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y-=this._getLocalRotation()):-1!==this.keysRotateRight.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y+=this._getLocalRotation()):-1!==this.keysRotateUp.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x-=this._getLocalRotation()):-1!==this.keysRotateDown.indexOf(i)&&(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x+=this._getLocalRotation()),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),B.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}getClassName(){return"FreeCameraKeyboardMoveInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}_getLocalRotation(){const e=this.camera._calculateHandednessMultiplier();return this.rotationSpeed*this._engine.getDeltaTime()/1e3*e}}e([a()],ua.prototype,"keysUp",void 0),e([a()],ua.prototype,"keysUpward",void 0),e([a()],ua.prototype,"keysDown",void 0),e([a()],ua.prototype,"keysDownward",void 0),e([a()],ua.prototype,"keysLeft",void 0),e([a()],ua.prototype,"keysRight",void 0),e([a()],ua.prototype,"rotationSpeed",void 0),e([a()],ua.prototype,"keysRotateLeft",void 0),e([a()],ua.prototype,"keysRotateRight",void 0),e([a()],ua.prototype,"keysRotateUp",void 0),e([a()],ua.prototype,"keysRotateDown",void 0),ks.FreeCameraKeyboardMoveInput=ua;class da{constructor(e=!0){this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3,this._previousPosition=null,this.onPointerMovedObservable=new g,this._allowCameraRotation=!0,this._currentActiveButton=-1,this._activePointerId=-1}attachControl(e){e=Qt.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();this._pointerInput||(this._pointerInput=s=>{const n=s.event,r="touch"===n.pointerType;if(!this.touchEnabled&&r)return;if(s.type!==Es.POINTERMOVE&&-1===this.buttons.indexOf(n.button))return;const a=n.target;if(s.type===Es.POINTERDOWN){if(r&&-1!==this._activePointerId||!r&&-1!==this._currentActiveButton)return;this._activePointerId=n.pointerId;try{a?.setPointerCapture(n.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=n.button),this._previousPosition={x:n.clientX,y:n.clientY},e||(n.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(s.event)}else if(s.type===Es.POINTERUP){if(r&&this._activePointerId!==n.pointerId||!r&&this._currentActiveButton!==n.button)return;try{a?.releasePointerCapture(n.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||n.preventDefault(),this._activePointerId=-1}else if(s.type===Es.POINTERMOVE&&(this._activePointerId===n.pointerId||!r))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(s.event);else if(this._previousPosition){const t=this.camera._calculateHandednessMultiplier(),i=(n.clientX-this._previousPosition.x)*t,s=n.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=s/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:s}),this._previousPosition={x:n.clientX,y:n.clientY},e||n.preventDefault()}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;const s=this.camera._calculateHandednessMultiplier(),n=i.movementX*s;this.camera.cameraRotation.y+=n/this.angularSensibility;const r=i.movementY;this.camera.cameraRotation.x+=r/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Es.POINTERDOWN|Es.POINTERUP|Es.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}e([a()],da.prototype,"buttons",void 0),e([a()],da.prototype,"angularSensibility",void 0),ks.FreeCameraMouseInput=da;class _a{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new g,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=Qt.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Es.POINTERWHEEL)return;const i=t.event,s=i.deltaMode===Ks.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*s*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*s*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*s*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Es.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}var fa,ma,pa,ga;e([a()],_a.prototype,"wheelPrecisionX",void 0),e([a()],_a.prototype,"wheelPrecisionY",void 0),e([a()],_a.prototype,"wheelPrecisionZ",void 0),function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(fa||(fa={}));class Ea extends _a{constructor(){super(...arguments),this._moveRelative=B.Zero(),this._rotateRelative=B.Zero(),this._moveScene=B.Zero(),this._wheelXAction=fa.MoveRelative,this._wheelXActionCoordinate=0,this._wheelYAction=fa.MoveRelative,this._wheelYActionCoordinate=2,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==fa.MoveRelative||(this._wheelXAction=fa.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==fa.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==fa.MoveRelative||(this._wheelYAction=fa.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==fa.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==fa.MoveRelative||(this._wheelZAction=fa.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==fa.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==fa.RotateRelative||(this._wheelXAction=fa.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==fa.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==fa.RotateRelative||(this._wheelYAction=fa.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==fa.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==fa.RotateRelative||(this._wheelZAction=fa.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==fa.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==fa.MoveScene||(this._wheelXAction=fa.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==fa.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==fa.MoveScene||(this._wheelYAction=fa.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==fa.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==fa.MoveScene||(this._wheelZAction=fa.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==fa.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(0===this._wheelDeltaX&&0===this._wheelDeltaY&&0==this._wheelDeltaZ)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);const e=G.Zero();this.camera.getViewMatrix().invertToRef(e);const t=B.Zero();B.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(0===e)return;if(null===t||null===i)return;let s=null;switch(t){case fa.MoveRelative:s=this._moveRelative;break;case fa.RotateRelative:s=this._rotateRelative;break;case fa.MoveScene:s=this._moveScene}switch(i){case 0:s.set(e,0,0);break;case 1:s.set(0,e,0);break;case 2:s.set(0,0,e)}}}e([a()],Ea.prototype,"wheelXMoveRelative",null),e([a()],Ea.prototype,"wheelYMoveRelative",null),e([a()],Ea.prototype,"wheelZMoveRelative",null),e([a()],Ea.prototype,"wheelXRotateRelative",null),e([a()],Ea.prototype,"wheelYRotateRelative",null),e([a()],Ea.prototype,"wheelZRotateRelative",null),e([a()],Ea.prototype,"wheelXMoveScene",null),e([a()],Ea.prototype,"wheelYMoveScene",null),e([a()],Ea.prototype,"wheelZMoveScene",null),ks.FreeCameraMouseWheelInput=Ea;class Ta{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=Qt.IsSafari()}attachControl(e){e=Qt.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const s=i.event,n="mouse"===s.pointerType||this._isSafari&&void 0===s.pointerType;if(this.allowMouse||!n)if(i.type===Es.POINTERDOWN){if(e||s.preventDefault(),this._pointerPressed.push(s.pointerId),1!==this._pointerPressed.length)return;t={x:s.clientX,y:s.clientY}}else if(i.type===Es.POINTERUP){e||s.preventDefault();const i=this._pointerPressed.indexOf(s.pointerId);if(-1===i)return;if(this._pointerPressed.splice(i,1),0!=i)return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===Es.POINTERMOVE){if(e||s.preventDefault(),!t)return;if(0!=this._pointerPressed.indexOf(s.pointerId))return;this._offsetX=s.clientX-t.x,this._offsetY=-(s.clientY-t.y)}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Es.POINTERDOWN|Es.POINTERUP|Es.POINTERMOVE),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(null===this._offsetX||null===this._offsetY)return;if(0===this._offsetX&&0===this._offsetY)return;const e=this.camera,t=e._calculateHandednessMultiplier();e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility;if(this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{const t=e._computeLocalCameraSpeed(),i=new B(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);G.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(B.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}e([a()],Ta.prototype,"touchAngularSensibility",void 0),e([a()],Ta.prototype,"touchMoveSensibility",void 0),ks.FreeCameraTouchInput=Ta;class Aa extends Gs{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new ua),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new da(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new Ea,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new Ta),this}clear(){super.clear(),this._mouseInput=null}}class Ra extends Bs{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=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 keysUpward(){const e=this.inputs.attached.keyboard;return e?e.keysUpward:[]}set keysUpward(e){const t=this.inputs.attached.keyboard;t&&(t.keysUpward=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 keysDownward(){const e=this.inputs.attached.keyboard;return e?e.keysDownward:[]}set keysDownward(e){const t=this.inputs.attached.keyboard;t&&(t.keysDownward=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 keysRotateLeft(){const e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]}set keysRotateLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)}get keysRotateRight(){const e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]}set keysRotateRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)}get keysRotateUp(){const e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]}set keysRotateUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)}get keysRotateDown(){const e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]}set keysRotateDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)}constructor(e,t,i,s=!0){super(e,t,i,s),this.ellipsoid=new B(.5,1,.5),this.ellipsoidOffset=new B(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=B.Zero(),this._diffPosition=B.Zero(),this._newPosition=B.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{this._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>Ui.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new Aa(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Qt.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new B(0,0,0),this.cameraRotation=new w(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?B.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=B.Zero(),this._transformedDirection=B.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}e([c()],Ra.prototype,"ellipsoid",void 0),e([c()],Ra.prototype,"ellipsoidOffset",void 0),e([a()],Ra.prototype,"checkCollisions",void 0),e([a()],Ra.prototype,"applyGravity",void 0),C("BABYLON.FreeCamera",Ra);class va{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class Ia{get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))}syncWithMask(e=!1){if(this.mask||e){this._numActiveAnimatables=0;for(let e=0;e<this._animatables.length;++e){const t=this._animatables[e];!this.mask||this.mask.disabled||this.mask.retainsTarget(t.target.name)?(this._numActiveAnimatables++,t.paused&&t.restart()):t.paused||t.pause()}}else this._numActiveAnimatables=this._targetedAnimations.length}removeUnmaskedAnimations(){if(this.mask&&!this.mask.disabled){for(let e=0;e<this._animatables.length;++e){const t=this._animatables[e];this.mask.retainsTarget(t.target.name)||(t.stop(),this._animatables.splice(e,1),--e)}for(let e=0;e<this._targetedAnimations.length;e++){const t=this._targetedAnimations[e];this.mask.retainsTarget(t.target.name)||(this._targetedAnimations.splice(e,1),--e)}}}get from(){return this._from}set from(e){if(this._from!==e){this._from=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].fromFrame=this._from}}}get to(){return this._to}set to(e){if(this._to!==e){this._to=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].toFrame=this._to}}}get isStarted(){return this._isStarted}get isPlaying(){return this._isStarted&&!this._isPaused}get speedRatio(){return this._speedRatio}set speedRatio(e){if(this._speedRatio!==e){this._speedRatio=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].speedRatio=this._speedRatio}}}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){if(this._loopAnimation!==e){this._loopAnimation=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].loopAnimation=this._loopAnimation}}}get isAdditive(){return this._isAdditive}set isAdditive(e){if(this._isAdditive!==e){this._isAdditive=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].isAdditive=this._isAdditive}}}get weight(){return this._weight}set weight(e){this._weight!==e&&(this._weight=e,this.setWeightForAllAnimatables(this._weight))}get targetedAnimations(){return this._targetedAnimations}get animatables(){return this._animatables}get children(){return this._targetedAnimations}get playOrder(){return this._playOrder}set playOrder(e){if(this._playOrder!==e&&(this._playOrder=e,this._animatables.length>0)){for(let e=0;e<this._animatables.length;e++)this._animatables[e].playOrder=this._playOrder;this._scene.sortActiveAnimatables()}}get enableBlending(){return this._enableBlending}set enableBlending(e){if(this._enableBlending!==e&&(this._enableBlending=e,null!==e))for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.enableBlending=e}get blendingSpeed(){return this._blendingSpeed}set blendingSpeed(e){if(this._blendingSpeed!==e&&(this._blendingSpeed=e,null!==e))for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.blendingSpeed=e}getLength(e,t){e=e??this._from;return((t=t??this._to)-e)/(this.targetedAnimations[0].animation.framePerSecond*this._speedRatio)}static MergeAnimationGroups(e,t=!0,i=!1,s){if(0===e.length)return null;s=s??e[0].weight;let n=Number.MAX_VALUE,r=-Number.MAX_VALUE;if(i)for(const t of e)t.from<n&&(n=t.from),t.to>r&&(r=t.to);const a=new Ia(e[0].name+"_merged",e[0]._scene,s);for(const s of e){i&&s.normalize(n,r);for(const e of s.targetedAnimations)a.addTargetedAnimation(e.animation,e.target);t&&s.dispose()}return a}constructor(e,t=null,i=-1,s=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._shouldStart=!0,this._parentContainer=null,this.onAnimationEndObservable=new g,this.onAnimationLoopObservable=new g,this.onAnimationGroupLoopObservable=new g,this.onAnimationGroupEndObservable=new g,this.onAnimationGroupPauseObservable=new g,this.onAnimationGroupPlayObservable=new g,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||M.LastCreatedScene,this._weight=i,this._playOrder=s,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new va;i.animation=e,i.target=t;const s=e.getKeys();return this._from>s[0].frame&&(this._from=s[0].frame),this._to<s[s.length-1].frame&&(this._to=s[s.length-1].frame),null!==this._enableBlending&&(e.enableBlending=this._enableBlending),null!==this._blendingSpeed&&(e.blendingSpeed=this._blendingSpeed),this._targetedAnimations.push(i),this._shouldStart=!0,i}removeTargetedAnimation(e){for(let t=this._targetedAnimations.length-1;t>-1;t--){this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;i<this._targetedAnimations.length;i++){const s=this._targetedAnimations[i].animation.getKeys(),n=s[0],r=s[s.length-1];if(n.frame>e){const t={frame:e,value:n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation};s.splice(0,0,t)}if(r.frame<t){const e={frame:t,value:r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation};s.push(e)}}return this._from=e,this._to=t,this}_processLoop(e,t,i){e.onAnimationLoop=()=>{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,s,n){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._shouldStart=!1,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let r=0;r<this._targetedAnimations.length;r++){const a=this._targetedAnimations[r],o=this._scene.beginDirectAnimation(a.target,[a.animation],void 0!==i?i:this._from,void 0!==s?s:this._to,e,t,void 0,void 0,void 0!==n?n:this._isAdditive);o.weight=this._weight,o.playOrder=this._playOrder,o.onAnimationEnd=()=>{this.onAnimationEndObservable.notifyObservers(a),this._checkAnimationGroupEnded(o)},this._processLoop(o,a,r),this._animatables.push(o)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e<this._animatables.length;e++){this._animatables[e].pause()}return this.onAnimationGroupPauseObservable.notifyObservers(this),this}play(e){return this.isStarted&&this._animatables.length&&!this._shouldStart?(void 0!==e&&(this.loopAnimation=e),this.restart()):(this.stop(),this.start(e,this._speedRatio)),this._isPaused=!1,this}reset(){if(!this._isStarted)return this.play(),this.goToFrame(0),this.stop(!0),this;for(let e=0;e<this._animatables.length;e++){this._animatables[e].reset()}return this}restart(){if(!this._isStarted)return this;for(let e=0;e<this._animatables.length;e++){this._animatables[e].restart()}return this.syncWithMask(),this.onAnimationGroupPlayObservable.notifyObservers(this),this}stop(e=!1){if(!this._isStarted)return this;const t=this._animatables.slice();for(let i=0;i<t.length;i++)t[i].stop(void 0,void 0,!0,e);let i=0;for(let e=0;e<this._scene._activeAnimatables.length;e++){const t=this._scene._activeAnimatables[e];t._runtimeAnimations.length>0&&(this._scene._activeAnimatables[i++]=t)}return this._scene._activeAnimatables.length=i,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t<this._animatables.length;t++){this._animatables[t].weight=e}return this}syncAllAnimationsWith(e){for(let t=0;t<this._animatables.length;t++){this._animatables[t].syncWith(e)}return this}goToFrame(e){if(!this._isStarted)return this;for(let t=0;t<this._animatables.length;t++){this._animatables[t].goToFrame(e)}return this}dispose(){this.isStarted&&this.stop(),this._targetedAnimations.length=0,this._animatables.length=0;const e=this._scene.animationGroups.indexOf(this);if(e>-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const e=this._parentContainer.animationGroups.indexOf(this);e>-1&&this._parentContainer.animationGroups.splice(e,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e){const t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const s=new Ia(e||this.name,this._scene,this._weight,this._playOrder);s._from=this.from,s._to=this.to,s._speedRatio=this.speedRatio,s._loopAnimation=this.loopAnimation,s._isAdditive=this.isAdditive,s._enableBlending=this.enableBlending,s._blendingSpeed=this.blendingSpeed,s.metadata=this.metadata,s.mask=this.mask;for(const e of this._targetedAnimations)s.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return s}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;t<this.targetedAnimations.length;t++){const i=this.targetedAnimations[t];e.targetedAnimations[t]=i.serialize()}return K&&K.HasTags(this)&&(e.tags=K.GetTags(this)),this.metadata&&(e.metadata=this.metadata),e}static Parse(e,t){const i=new Ia(e.name,t,e.weight,e.playOrder);for(let s=0;s<e.targetedAnimations.length;s++){const n=e.targetedAnimations[s],r=Ls.Parse(n.animation),a=n.targetId;if("influence"===n.animation.property){const e=t.getMorphTargetById(a);e&&i.addTargetedAnimation(r,e)}else{const e=t.getNodeById(a);null!=e&&i.addTargetedAnimation(r,e)}}return K&&K.AddTagsTo(i,e.tags),null!==e.from&&null!==e.to&&i.normalize(e.from,e.to),void 0!==e.speedRatio&&(i._speedRatio=e.speedRatio),void 0!==e.loopAnimation&&(i._loopAnimation=e.loopAnimation),void 0!==e.isAdditive&&(i._isAdditive=e.isAdditive),void 0!==e.weight&&(i._weight=e.weight),void 0!==e.playOrder&&(i._playOrder=e.playOrder),void 0!==e.enableBlending&&(i._enableBlending=e.enableBlending),void 0!==e.blendingSpeed&&(i._blendingSpeed=e.blendingSpeed),void 0!==e.metadata&&(i.metadata=e.metadata),i}static MakeAnimationAdditive(e,t,i,s=!1,n){let r;r="object"==typeof t?t:{referenceFrame:t,range:i,cloneOriginalAnimationGroup:s,clonedAnimationName:n};let a=e;r.cloneOriginalAnimationGroup&&(a=e.clone(r.clonedAnimationGroupName||a.name));const o=a.targetedAnimations;for(let e=0;e<o.length;e++){const t=o[e];t.animation=Ls.MakeAnimationAdditive(t.animation,r)}if(a.isAdditive=!0,r.clipKeys){let e=Number.MAX_VALUE,t=-Number.MAX_VALUE;const i=a.targetedAnimations;for(let s=0;s<i.length;s++){const n=i[s].animation.getKeys();e>n[0].frame&&(e=n[0].frame),t<n[n.length-1].frame&&(t=n[n.length-1].frame)}a._from=e,a._to=t}return a}static ClipKeys(e,t,i,s,n){const r=e.clone(s||e.name);return Ia.ClipKeysInPlace(r,t,i,n)}static ClipKeysInPlace(e,t,i,s){return Ia.ClipInPlace(e,t,i,s,!1)}static ClipFrames(e,t,i,s,n){const r=e.clone(s||e.name);return Ia.ClipFramesInPlace(r,t,i,n)}static ClipFramesInPlace(e,t,i,s){return Ia.ClipInPlace(e,t,i,s,!0)}static ClipInPlace(e,t,i,s,n=!1){let r=Number.MAX_VALUE,a=-Number.MAX_VALUE;const o=e.targetedAnimations;for(let e=0;e<o.length;e++){const l=o[e],h=s?l.animation:l.animation.clone();n&&(h.createKeyForFrame(t),h.createKeyForFrame(i));const c=h.getKeys(),u=[];let d=Number.MAX_VALUE;for(let e=0;e<c.length;e++){const s=c[e];if(!n&&e>=t&&e<=i||n&&s.frame>=t&&s.frame<=i){const e={frame:s.frame,value:s.value.clone?s.value.clone():s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation,lockedTangent:s.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,u.push(e)}}0!==u.length?(r>u[0].frame&&(r=u[0].frame),a<u[u.length-1].frame&&(a=u[u.length-1].frame),h.setKeys(u,!0),l.animation=h):(o.splice(e,1),e--)}return e._from=r,e._to=a,e}getClassName(){return"AnimationGroup"}toString(e){let t="Name: "+this.name;return t+=", type: "+this.getClassName(),e&&(t+=", from: "+this._from,t+=", to: "+this._to,t+=", isStarted: "+this._isStarted,t+=", speedRatio: "+this._speedRatio,t+=", targetedAnimations length: "+this._targetedAnimations.length,t+=", animatables length: "+this._animatables),t}}function Sa(e,t,i,s){let n,r=1;s===tt.TEXTURETYPE_FLOAT?n=new Float32Array(t*i*4):s===tt.TEXTURETYPE_HALF_FLOAT?(n=new Uint16Array(t*i*4),r=15360):n=s===tt.TEXTURETYPE_UNSIGNED_INTEGER?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let s=0;s<t;s++)for(let a=0;a<i;a++){const i=3*(a*t+s),o=4*(a*t+s);n[o+0]=e[i+0],n[o+1]=e[i+1],n[o+2]=e[i+2],n[o+3]=r}return n}function Ca(e){return function(t,i,s,n,r,a,o,l,h=null,c=tt.TEXTURETYPE_UNSIGNED_INT){const u=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,d=new vt(this,e?10:11);d.baseWidth=i,d.baseHeight=s,d.baseDepth=n,d.width=i,d.height=s,d.depth=n,d.format=r,d.type=c,d.generateMipMaps=a,d.samplingMode=l,e?d.is3D=!0:d.is2DArray=!0,this._doNotHandleContextLost||(d._bufferView=t),e?this.updateRawTexture3D(d,t,r,o,h,c):this.updateRawTexture2DArray(d,t,r,o,h,c),this._bindTextureDirectly(u,d,!0);const _=this._getSamplingParameters(l,a);return this._gl.texParameteri(u,this._gl.TEXTURE_MAG_FILTER,_.mag),this._gl.texParameteri(u,this._gl.TEXTURE_MIN_FILTER,_.min),a&&this._gl.generateMipmap(u),this._bindTextureDirectly(u,null),this._internalTexturesCache.push(d),d}}function ba(e){return function(t,i,s,n,r=null,a=tt.TEXTURETYPE_UNSIGNED_INT){const o=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,l=this._getWebGLTextureType(a),h=this._getInternalFormat(s),c=this._getRGBABufferInternalSizedFormat(a,s);this._bindTextureDirectly(o,t,!0),this._unpackFlipY(void 0===n||!!n),this._doNotHandleContextLost||(t._bufferView=i,t.format=s,t.invertY=n,t._compression=r),t.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&i?this._gl.compressedTexImage3D(o,0,this.getCaps().s3tc[r],t.width,t.height,t.depth,0,i):this._gl.texImage3D(o,0,c,t.width,t.height,t.depth,0,h,l,i),t.generateMipMaps&&this._gl.generateMipmap(o),this._bindTextureDirectly(o,null),t.isReady=!0}}Pi.prototype.updateRawTexture=function(e,t,i,s,n=null,r=tt.TEXTURETYPE_UNSIGNED_INT,a=!1){if(!e)return;const o=this._getRGBABufferInternalSizedFormat(r,i,a),l=this._getInternalFormat(i),h=this._getWebGLTextureType(r);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=r,e.invertY=s,e._compression=n),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),n&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[n],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},Pi.prototype.createRawTexture=function(e,t,i,s,n,r,a,o=null,l=tt.TEXTURETYPE_UNSIGNED_INT,h=0,c=!1){const u=new vt(this,3);u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=s,u.generateMipMaps=n,u.samplingMode=a,u.invertY=r,u._compression=o,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!n),this._doNotHandleContextLost||(u._bufferView=e),this.updateRawTexture(u,e,s,r,o,l,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);const d=this._getSamplingParameters(a,n);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),n&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u},Pi.prototype.createRawCubeTexture=function(e,t,i,s,n,r,a,o=null){const l=this._gl,h=new vt(this,8);h.isCube=!0,h.format=i,h.type=s,this._doNotHandleContextLost||(h._bufferViewArray=e);const c=this._getWebGLTextureType(s);let u=this._getInternalFormat(i);u===l.RGB&&(u=l.RGBA),c!==l.FLOAT||this._caps.textureFloatLinearFiltering?c!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?c!==l.FLOAT||this._caps.textureFloatRender?c!==l.HALF_FLOAT||this._caps.colorBufferFloat||(n=!1,ce.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(n=!1,ce.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(n=!1,a=tt.TEXTURE_NEAREST_SAMPLINGMODE,ce.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(n=!1,a=tt.TEXTURE_NEAREST_SAMPLINGMODE,ce.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."));const d=t,_=d;h.width=d,h.height=_,h.invertY=r,h._compression=o;if(!this.needPOTTextures||Ht(h.width)&&Ht(h.height)||(n=!1),e)this.updateRawCubeTexture(h,e,i,s,r,o);else{const e=this._getRGBABufferInternalSizedFormat(s),t=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let i=0;i<6;i++)o?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,this.getCaps().s3tc[o],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,e,h.width,h.height,0,u,c,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),e&&n&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const f=this._getSamplingParameters(a,n);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,f.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,f.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),h.generateMipMaps=n,h.samplingMode=a,h.isReady=!0,h},Pi.prototype.updateRawCubeTexture=function(e,t,i,s,n,r=null,a=0){e._bufferViewArray=t,e.format=i,e.type=s,e.invertY=n,e._compression=r;const o=this._gl,l=this._getWebGLTextureType(s);let h=this._getInternalFormat(i);const c=this._getRGBABufferInternalSizedFormat(s);let u=!1;h===o.RGB&&(h=o.RGBA,u=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===n||!!n),e.width%4!=0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let n=t[i];r?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,a,this.getCaps().s3tc[r],e.width,e.height,0,n):(u&&(n=Sa(n,e.width,e.height,s)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,a,c,e.width,e.height,0,h,l,n))}(!this.needPOTTextures||Ht(e.width)&&Ht(e.height))&&e.generateMipMaps&&0===a&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},Pi.prototype.createRawCubeTextureFromUrl=function(e,t,i,s,n,r,a,o,l=null,h=null,c=tt.TEXTURE_TRILINEAR_SAMPLINGMODE,u=!1){const d=this._gl,_=this.createRawCubeTexture(null,i,s,n,!r,u,c,null);t?.addPendingData(_),_.url=e,_.isReady=!1,this._internalTexturesCache.push(_);const f=e=>{const i=_.width,r=a(e);if(r){if(o){const e=this._getWebGLTextureType(n);let t=this._getInternalFormat(s);const a=this._getRGBABufferInternalSizedFormat(n);let l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,_,!0),this._unpackFlipY(!1);const h=o(r);for(let s=0;s<h.length;s++){const r=i>>s;for(let i=0;i<6;i++){let o=h[s][i];l&&(o=Sa(o,r,r,n)),d.texImage2D(i,s,a,r,r,0,t,e,o)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(_,r,s,n,u);_.isReady=!0,t?.removePendingData(_),_.onLoadedObservable.notifyObservers(_),_.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,(e=>{f(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(_),h&&e&&h(e.status+" "+e.statusText,i)})),_},Pi.prototype.createRawTexture2DArray=Ca(!1),Pi.prototype.createRawTexture3D=Ca(!0),Pi.prototype.updateRawTexture2DArray=ba(!1),Pi.prototype.updateRawTexture3D=ba(!0);class ya extends wn{constructor(e,t,i,s,n,r=!0,a=!1,o=tt.TEXTURE_TRILINEAR_SAMPLINGMODE,l=tt.TEXTURETYPE_UNSIGNED_INT,h,c){super(null,n,!r,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=s,this._engine&&(this._engine._caps.textureFloatLinearFiltering||l!==tt.TEXTURETYPE_FLOAT||(o=tt.TEXTURE_NEAREST_SAMPLINGMODE),this._engine._caps.textureHalfFloatLinearFiltering||l!==tt.TEXTURETYPE_HALF_FLOAT||(o=tt.TEXTURE_NEAREST_SAMPLINGMODE),this._texture=this._engine.createRawTexture(e,t,i,s,r,a,o,null,l,h??0,c??!1),this.wrapU=wn.CLAMP_ADDRESSMODE,this.wrapV=wn.CLAMP_ADDRESSMODE)}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}clone(){if(!this._texture)return super.clone();const e=new ya(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}static CreateLuminanceTexture(e,t,i,s,n=!0,r=!1,a=tt.TEXTURE_TRILINEAR_SAMPLINGMODE){return new ya(e,t,i,tt.TEXTUREFORMAT_LUMINANCE,s,n,r,a)}static CreateLuminanceAlphaTexture(e,t,i,s,n=!0,r=!1,a=tt.TEXTURE_TRILINEAR_SAMPLINGMODE){return new ya(e,t,i,tt.TEXTUREFORMAT_LUMINANCE_ALPHA,s,n,r,a)}static CreateAlphaTexture(e,t,i,s,n=!0,r=!1,a=tt.TEXTURE_TRILINEAR_SAMPLINGMODE){return new ya(e,t,i,tt.TEXTUREFORMAT_ALPHA,s,n,r,a)}static CreateRGBTexture(e,t,i,s,n=!0,r=!1,a=tt.TEXTURE_TRILINEAR_SAMPLINGMODE,o=tt.TEXTURETYPE_UNSIGNED_INT,l=0,h=!1){return new ya(e,t,i,tt.TEXTUREFORMAT_RGB,s,n,r,a,o,l,h)}static CreateRGBATexture(e,t,i,s,n=!0,r=!1,a=tt.TEXTURE_TRILINEAR_SAMPLINGMODE,o=tt.TEXTURETYPE_UNSIGNED_INT,l=0,h=!1){return new ya(e,t,i,tt.TEXTUREFORMAT_RGBA,s,n,r,a,o,l,h)}static CreateRGBAStorageTexture(e,t,i,s,n=!0,r=!1,a=tt.TEXTURE_TRILINEAR_SAMPLINGMODE,o=tt.TEXTURETYPE_UNSIGNED_INT,l=!1){return new ya(e,t,i,tt.TEXTUREFORMAT_RGBA,s,n,r,a,o,tt.TEXTURE_CREATIONFLAG_STORAGE,l)}static CreateRTexture(e,t,i,s,n=!0,r=!1,a=wn.TRILINEAR_SAMPLINGMODE,o=tt.TEXTURETYPE_FLOAT){return new ya(e,t,i,tt.TEXTUREFORMAT_R,s,n,r,a,o)}static CreateRStorageTexture(e,t,i,s,n=!0,r=!1,a=wn.TRILINEAR_SAMPLINGMODE,o=tt.TEXTURETYPE_FLOAT){return new ya(e,t,i,tt.TEXTUREFORMAT_R,s,n,r,a,o,tt.TEXTURE_CREATIONFLAG_STORAGE)}}class Ma{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=G.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new g,this.bones=[],this._scene=i||M.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const s=this._scene.getEngine().getCaps();this._canUseTextureForBones=s.textureFloat&&s.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter((e=>!e.getParent()))}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return this._transformMatrices&&!this._isDirty||this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].name===e)return t;return-1}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=new Cs(e,t,i);for(let s=0,n=this.bones.length;s<n;s++)this.bones[s].animations[0]&&this.bones[s].animations[0].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,s=this.bones.length;i<s;i++)this.bones[i].animations[0]&&this.bones[i].animations[0].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}getAnimationRanges(){const e=[];let t;for(t in this._ranges)e.push(this._ranges[t]);return e}copyAnimationRange(e,t,i=!1){if(this._ranges[t]||!e.getAnimationRange(t))return!1;let s=!0;const n=this._getHighestAnimationFrame()+1,r={},a=e.bones;let o,l;for(l=0,o=a.length;l<o;l++)r[a[l].name]=a[l];this.bones.length!==a.length&&(ce.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${a.length}`),s=!1);const h=i&&this.dimensionsAtRest&&e.dimensionsAtRest?this.dimensionsAtRest.divide(e.dimensionsAtRest):null;for(l=0,o=this.bones.length;l<o;l++){const e=this.bones[l].name,a=r[e];a?s=s&&this.bones[l].copyAnimationRange(a,t,n,i,h):(ce.Warn("copyAnimationRange: not same rig, missing source bone "+e),s=!1)}const c=e.getAnimationRange(t);return c&&(this._ranges[t]=new Cs(t,c.from+n,c.to+n)),s}returnToRest(){for(const e of this.bones)-1!==e._index&&e.returnToRest()}_getHighestAnimationFrame(){let e=0;for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].animations[0]){const i=this.bones[t].animations[0].getHighestFrame();e<i&&(e=i)}return e}beginAnimation(e,t,i,s){const n=this.getAnimationRange(e);return n?this._scene.beginAnimation(this,n.from,n.to,t,i,s):null}static MakeAnimationAdditive(e,t=0,i){const s=e.getAnimationRange(i);if(!s)return null;const n=e._scene.getAllAnimatablesByTarget(e);let r=null;for(let e=0;e<n.length;e++){const t=n[e];if(t.fromFrame===s?.from&&t.toFrame===s?.to){r=t;break}}const a=e.getAnimatables();for(let e=0;e<a.length;e++){const s=a[e].animations;if(s)for(let e=0;e<s.length;e++)Ls.MakeAnimationAdditive(s[e],t,i)}return r&&(r.isAdditive=!0),e}_markAsDirty(){this._isDirty=!0,this._absoluteTransformIsDirty=!0}_registerMeshWithPoseMatrix(e){this._meshesWithPoseMatrix.push(e)}_unregisterMeshWithPoseMatrix(e){const t=this._meshesWithPoseMatrix.indexOf(e);t>-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i<this.bones.length;i++){const s=this.bones[i];s._childUpdateId++;const n=s.getParent();if(n?s.getLocalMatrix().multiplyToRef(n.getFinalMatrix(),s.getFinalMatrix()):t?s.getLocalMatrix().multiplyToRef(t,s.getFinalMatrix()):s.getFinalMatrix().copyFrom(s.getLocalMatrix()),-1!==s._index){const t=null===s._index?i:s._index;s.getAbsoluteInverseBindMatrix().multiplyToArray(s.getFinalMatrix(),e,16*t)}}this._identity.copyToArray(e,16*this.bones.length)}prepare(e=!1){if(!e){const e=this.getScene().getRenderId();if(this._currentRenderId===e)return;this._currentRenderId=e}if(this._numBonesWithLinkedTransformNode>0)for(const e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)if(!e.getParent()){e.getBindMatrix().multiplyToRef(t,X.Matrix[1]),e._updateAbsoluteBindMatrices(X.Matrix[1])}if(this.isUsingTextureForMatrices){const t=4*(this.bones.length+1);e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=ya.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,tt.TEXTURE_NEAREST_SAMPLINGMODE,tt.TEXTURETYPE_FLOAT))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._bonesTransformMatrices)}}else{if(!this._isDirty)return;this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=ya.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,tt.TEXTURE_NEAREST_SAMPLINGMODE,tt.TEXTURETYPE_FLOAT))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e<this.bones.length;e++)this._animatables.push(this.bones[e])}return this._animatables}clone(e,t){const i=new Ma(e,t||e,this._scene);i.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let e=0;e<this.bones.length;e++){const t=this.bones[e];let s=null;const n=t.getParent();if(n){const e=this.bones.indexOf(n);s=i.bones[e]}const r=new ia(t.name,i,s,t.getBindMatrix().clone(),t.getRestMatrix().clone());r._index=t._index,t._linkedTransformNode&&r.linkTransformNode(t._linkedTransformNode),de.DeepCopy(t.animations,r.animations)}if(this._ranges){i._ranges={};for(const e in this._ranges){const t=this._ranges[e];t&&(i._ranges[e]=t.clone())}}return this._isDirty=!0,i.prepare(!0),i}enableBlending(e=.01){this.bones.forEach((t=>{t.animations.forEach((t=>{t.enableBlending=!0,t.blendingSpeed=e}))}))}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){const e={};e.name=this.name,e.id=this.id,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let t=0;t<this.bones.length;t++){const i=this.bones[t],s=i.getParent(),n={parentBoneIndex:s?this.bones.indexOf(s):-1,index:i.getIndex(),name:i.name,id:i.id,matrix:i.getBindMatrix().asArray(),rest:i.getRestMatrix().asArray(),linkedTransformNodeId:i.getTransformNode()?.id};e.bones.push(n),i.length&&(n.length=i.length),i.metadata&&(n.metadata=i.metadata),i.animations&&i.animations.length>0&&(n.animation=i.animations[0].serialize()),e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const s={};s.name=t,s.from=i.from,s.to=i.to,e.ranges.push(s)}}return e}static Parse(e,t){const i=new Ma(e.name,e.id,t);let s;for(e.dimensionsAtRest&&(i.dimensionsAtRest=B.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,s=0;s<e.bones.length;s++){const t=e.bones[s],n=e.bones[s].index;let r=null;t.parentBoneIndex>-1&&(r=i.bones[t.parentBoneIndex]);const a=t.rest?G.FromArray(t.rest):null,o=new ia(t.name,i,r,G.FromArray(t.matrix),a,null,n);void 0!==t.id&&null!==t.id&&(o.id=t.id),t.length&&(o.length=t.length),t.metadata&&(o.metadata=t.metadata),t.animation&&o.animations.push(Ls.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,o._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(s=0;s<e.ranges.length;s++){const t=e.ranges[s];i.createAnimationRange(t.name,t.from,t.to)}return i}computeAbsoluteMatrices(e=!1){(this._absoluteTransformIsDirty||e)&&(this.bones[0].computeAbsoluteMatrices(),this._absoluteTransformIsDirty=!1)}computeAbsoluteTransforms(e=!1){this.computeAbsoluteMatrices(e)}getPoseMatrix(){let e=null;return this._meshesWithPoseMatrix.length>0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i<this.bones.length;i++)this._sortBones(i,e,t);this.bones=e}_sortBones(e,t,i){if(i[e])return;i[e]=!0;const s=this.bones[e];if(!s)return;void 0===s._index&&(s._index=e);const n=s.getParent();n&&this._sortBones(this.bones.indexOf(n),t,i),t.push(s)}setCurrentPoseAsRest(){this.bones.forEach((e=>{e.setCurrentPoseAsRest()}))}}class xa{get influence(){return this._influence}set influence(e){if(this._influence===e)return;const t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new g,this._onDataLayoutChanged=new g,this._animationPropertiesOverride=null,this._scene=i||M.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}setPositions(e){const t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){const t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){const t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){const t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){const e=se.Clone((()=>new xa(this.name,this.influence,this._scene)),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e}serialize(){const e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),null!=this.id&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),se.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new xa(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t<e.animations.length;t++){const s=e.animations[t],n=b("BABYLON.Animation");n&&i.animations.push(n.Parse(s))}e.autoAnimate&&t&&t.beginAnimation(i,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1)}return i}static FromMesh(e,t,i){t||(t=e.name);const s=new xa(t,i,e.getScene());return s.setPositions(e.getVerticesData(li.PositionKind)),e.isVerticesDataPresent(li.NormalKind)&&s.setNormals(e.getVerticesData(li.NormalKind)),e.isVerticesDataPresent(li.TangentKind)&&s.setTangents(e.getVerticesData(li.TangentKind)),e.isVerticesDataPresent(li.UVKind)&&s.setUVs(e.getVerticesData(li.UVKind)),s}}e([a()],xa.prototype,"id",void 0);class Oa extends wn{get depth(){return this._depth}constructor(e,t,i,s,n,r,a=!0,o=!1,l=wn.TRILINEAR_SAMPLINGMODE,h=tt.TEXTURETYPE_UNSIGNED_INT,c){super(null,r,!a,o),this.format=n,this._texture=r.getEngine().createRawTexture2DArray(e,t,i,s,n,a,o,l,null,h,c),this._depth=s,this.is2DArray=!0}update(e){this._texture&&this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}static CreateRGBATexture(e,t,i,s,n,r=!0,a=!1,o=tt.TEXTURE_TRILINEAR_SAMPLINGMODE,l=tt.TEXTURETYPE_UNSIGNED_INT){return new Oa(e,t,i,s,tt.TEXTUREFORMAT_RGBA,n,r,a,o,l)}}class Da{set areUpdatesFrozen(e){e?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(!0)))}get areUpdatesFrozen(){return this._blockCounter>0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new ei(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=M.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._syncActiveTargets(!0))}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){return Da.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!this._scene?.getEngine().getCaps().disableMorphTargetTexture}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}getTargetByName(e){for(const t of this._targets)if(t.name===e)return t;return null}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((e=>{this._syncActiveTargets(e)}))),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add((()=>{this._syncActiveTargets(!0)}))),this._syncActiveTargets(!0)}removeTarget(e){const t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0)),this._scene&&this._scene.stopAnimation(e)}_bind(e){e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setInt("morphTargetCount",this.numInfluencers)}clone(){const e=new Da(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),this._morphTargetTextureIndices&&this._morphTargetTextureIndices.length===this._targets.length||(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let i=-1;for(const e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=Da.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;const s=e.getPositions();if(s){const e=s.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void ce.Error("Incompatible target. Targets must all have the same vertices count.")}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e<t;e++)this._influences[e]=this._tempInfluences[e];e&&this.synchronize()}synchronize(){if(this._scene&&!this.areUpdatesFrozen){if(this.isUsingTextureForTargets&&(this._vertexCount||this.numMaxInfluencers>0)){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;const e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){const e=this._targetStoreTexture.getSize();e.width===this._textureWidth&&e.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4);let i=0;for(let s=0;s<e;s++){const e=this._targets[s],n=e.getPositions(),r=e.getNormals(),a=e.getUVs(),o=e.getTangents();if(!n)return void(0===s&&ce.Error("Invalid morph target. Target must have positions."));i=s*this._textureWidth*this._textureHeight*4;for(let e=0;e<this._vertexCount;e++)t[i]=n[3*e],t[i+1]=n[3*e+1],t[i+2]=n[3*e+2],i+=4,this._supportsNormals&&r&&(t[i]=r[3*e],t[i+1]=r[3*e+1],t[i+2]=r[3*e+2],i+=4),this._supportsUVs&&a&&(t[i]=a[2*e],t[i+1]=a[2*e+1],i+=4),this._supportsTangents&&o&&(t[i]=o[3*e],t[i+1]=o[3*e+1],t[i+2]=o[3*e+2],i+=4)}this._targetStoreTexture=Oa.CreateRGBATexture(t,this._textureWidth,this._textureHeight,e,this._scene,!1,!1,tt.TEXTURE_NEAREST_SAMPLINGMODE,tt.TEXTURETYPE_FLOAT)}}for(const e of this._scene.meshes)e.morphTargetManager===this&&e._syncGeometryWithMorphTargetManager()}}dispose(){if(this._targetStoreTexture&&this._targetStoreTexture.dispose(),this._targetStoreTexture=null,this._scene){if(this._scene.removeMorphTargetManager(this),this._parentContainer){const e=this._parentContainer.morphTargetManagers.indexOf(this);e>-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(const e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){const i=new Da(t);i._uniqueId=e.id;for(const s of e.targets)i.addTarget(xa.Parse(s,t));return i}}Da.EnableTextureStorage=!0,Da.MaxActiveMorphTargetsInVertexAttributeMode=8,gs._instancedMeshFactory=(e,t)=>{const i=new Pa(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class Pa extends ji{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const e of t.getAnimationRanges())null!=e&&this.createAnimationRange(e.name,e.from,e.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){this._sourceMesh?.receiveShadows!==e&&Qt.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){this._sourceMesh?.material!==e&&Qt.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){this._sourceMesh?.visibility!==e&&Qt.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){this._sourceMesh?.skeleton!==e&&Qt.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){this._sourceMesh&&e!==this._sourceMesh.renderingGroupId&&ce.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}copyVerticesData(e,t){this._sourceMesh.copyVerticesData(e,t)}setVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,s),this.sourceMesh}updateVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,s),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i;i="object"==typeof e?e:{applySkeleton:e,applyMorph:t};const s=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getData(i,null,li.PositionKind),s),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||ce.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD.billboardMode!==Gi.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new G);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,X.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(X.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh);return this}_generatePointsArray(){return this._sourceMesh._generatePointsArray()}_updateBoundingInfo(){return this.hasBoundingInfo?this.getBoundingInfo().update(this.worldMatrixFromCache):this.buildBoundingInfo(this.absolutePosition,this.absolutePosition,this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}clone(e,t=null,i,s){const n=(s||this._sourceMesh).createInstance(e);if(de.DeepCopy(this,n,["name","subMeshes","uniqueId","parent","lightSources","receiveShadows","material","visibility","skeleton","sourceMesh","isAnInstance","facetNb","isFacetDataEnabled","isBlocked","useBones","hasInstances","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","hasBoundingInfo"],[]),this.refreshBoundingInfo(),t&&(n.parent=t),!i)for(let e=0;e<this.getScene().meshes.length;e++){const t=this.getScene().meshes[e];t.parent===this&&t.clone(t.name,n)}return n.computeWorldMatrix(!0),this.onClonedObservable.notifyObservers(n),n}dispose(e,t=!1){this._sourceMesh.removeInstance(this),super.dispose(e,t)}_serializeAsParent(e){super._serializeAsParent(e),e.parentId=this._sourceMesh.uniqueId,e.parentInstanceIndex=this._indexInSourceMeshInstanceArray}instantiateHierarchy(e=null,t,i){const s=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0,t&&t.newSourcedMesh);s&&i&&i(this,s);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(s,t,i);return s}}gs.prototype.registerInstancedBuffer=function(e,t){if(this._userInstancedBuffersStorage?.vertexBuffers[e]?.dispose(),!this.instancedBuffers){this.instancedBuffers={};for(const e of this.instances)e.instancedBuffers={}}this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this.instancedBuffers[e]=null,this._userInstancedBuffersStorage.strides[e]=t,this._userInstancedBuffersStorage.sizes[e]=32*t,this._userInstancedBuffersStorage.data[e]=new Float32Array(this._userInstancedBuffersStorage.sizes[e]),this._userInstancedBuffersStorage.vertexBuffers[e]=new li(this.getEngine(),this._userInstancedBuffersStorage.data[e],e,!0,!1,t,!0);for(const t of this.instances)t.instancedBuffers[e]=null;this._invalidateInstanceVertexArrayObject(),this._markSubMeshesAsAttributesDirty()},gs.prototype._processInstancedBuffers=function(e,t){const i=e?e.length:0;for(const s in this.instancedBuffers){let n=this._userInstancedBuffersStorage.sizes[s];const r=this._userInstancedBuffersStorage.strides[s],a=(i+1)*r;for(;n<a;)n*=2;this._userInstancedBuffersStorage.data[s].length!=n&&(this._userInstancedBuffersStorage.data[s]=new Float32Array(n),this._userInstancedBuffersStorage.sizes[s]=n,this._userInstancedBuffersStorage.vertexBuffers[s]&&(this._userInstancedBuffersStorage.vertexBuffers[s].dispose(),this._userInstancedBuffersStorage.vertexBuffers[s]=null));const o=this._userInstancedBuffersStorage.data[s];let l=0;if(t){const e=this.instancedBuffers[s];e.toArray?e.toArray(o,l):e.copyToArray?e.copyToArray(o,l):o[l]=e,l+=r}for(let t=0;t<i;t++){const i=e[t].instancedBuffers[s];i.toArray?i.toArray(o,l):i.copyToArray?i.copyToArray(o,l):o[l]=i,l+=r}this._userInstancedBuffersStorage.vertexBuffers[s]?this._userInstancedBuffersStorage.vertexBuffers[s].updateDirectly(o,0):(this._userInstancedBuffersStorage.vertexBuffers[s]=new li(this.getEngine(),this._userInstancedBuffersStorage.data[s],s,!0,!1,r,!0),this._invalidateInstanceVertexArrayObject())}},gs.prototype._invalidateInstanceVertexArrayObject=function(){if(this._userInstancedBuffersStorage&&void 0!==this._userInstancedBuffersStorage.vertexArrayObjects){for(const e in this._userInstancedBuffersStorage.vertexArrayObjects)this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[e]);this._userInstancedBuffersStorage.vertexArrayObjects={}}},gs.prototype._disposeInstanceSpecificData=function(){for(this._instanceDataStorage.instancesBuffer&&(this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null);this.instances.length;)this.instances[0].dispose();for(const e in this.instancedBuffers)this._userInstancedBuffersStorage.vertexBuffers[e]&&this._userInstancedBuffersStorage.vertexBuffers[e].dispose();this._invalidateInstanceVertexArrayObject(),this.instancedBuffers={}},C("BABYLON.InstancedMesh",Pa);class Na extends en{}class La{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){this.rootNodes.slice(0).forEach((e=>{e.dispose()})),this.rootNodes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0}}class Fa extends en{constructor(e){super(),this._wasAddedToScene=!1,(e=e||M.LastCreatedScene)&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add((()=>{this._wasAddedToScene||this.dispose()})),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();for(const e of this.particleSystems)e.rebuild();for(const e of this.textures)e._rebuild()})))}_topologicalSort(e){const t=new Map;for(const i of e)t.set(i.uniqueId,i);const i={dependsOn:new Map,dependedBy:new Map};for(const t of e){const e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(const s of e){const e=s.uniqueId,n=i.dependsOn.get(e);if(s instanceof Pa){const r=s.sourceMesh;t.has(r.uniqueId)&&(n.add(r.uniqueId),i.dependedBy.get(r.uniqueId).add(e))}const r=i.dependedBy.get(e);for(const n of s.getDescendants()){const s=n.uniqueId;if(t.has(s)){r.add(s);i.dependsOn.get(s).add(e)}}}const s=[],n=[];for(const s of e){const e=s.uniqueId;0===i.dependsOn.get(e).size&&(n.push(s),t.delete(e))}const r=n;for(;r.length>0;){const e=r.shift();s.push(e);const n=i.dependedBy.get(e.uniqueId);for(const s of Array.from(n.values())){const n=i.dependsOn.get(s);n.delete(e.uniqueId),0===n.size&&t.get(s)&&(r.push(t.get(s)),t.delete(s))}}return t.size>0&&(ce.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>ce.Error(e.name)))),s}_addNodeAndDescendantsToList(e,t,i,s){if(i&&(!s||s(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(const n of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,n,s)}}_isNodeInContainer(e){return e instanceof ji&&-1!==this.meshes.indexOf(e)||(e instanceof Gi&&-1!==this.transformNodes.indexOf(e)||(e instanceof Zs&&-1!==this.lights.indexOf(e)||e instanceof ri&&-1!==this.cameras.indexOf(e)))}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return ce.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return ce.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return ce.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return ce.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Qt.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},n={},r=new La,a=[],o=[],l={doNotInstantiate:!0,...i},h=[],c=new Set;for(const e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);for(const e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);const u=this._topologicalSort(h),d=(i,a)=>{if(((t,i)=>{if(s[t.uniqueId]=i.uniqueId,n[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof gs){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;t<i.numTargets;t++){const r=i.getTarget(t),a=e.morphTargetManager.getTarget(t);s[r.uniqueId]=a.uniqueId,n[a.uniqueId]=a}}}})(i,a),i.parent){const e=s[i.parent.uniqueId],t=n[e];a.parent=t||i.parent}if(a.position&&i.position&&a.position.copyFrom(i.position),a.rotationQuaternion&&i.rotationQuaternion&&a.rotationQuaternion.copyFrom(i.rotationQuaternion),a.rotation&&i.rotation&&a.rotation.copyFrom(i.rotation),a.scaling&&i.scaling&&a.scaling.copyFrom(i.scaling),a.material){const r=a;if(r.material)if(t){const t=i.material;if(-1===o.indexOf(t)){let i=t.clone(e?e(t.name):"Clone of "+t.name);if(o.push(t),s[t.uniqueId]=i.uniqueId,n[i.uniqueId]=i,"MultiMaterial"===t.getClassName()){const r=t;for(const t of r.subMaterials)t&&(i=t.clone(e?e(t.name):"Clone of "+t.name),o.push(t),s[t.uniqueId]=i.uniqueId,n[i.uniqueId]=i);r.subMaterials=r.subMaterials.map((e=>e&&n[s[e.uniqueId]]))}}"InstancedMesh"!==r.getClassName()&&(r.material=n[s[t.uniqueId]])}else"MultiMaterial"===r.material.getClassName()?-1===this.scene.multiMaterials.indexOf(r.material)&&this.scene.addMultiMaterial(r.material):-1===this.scene.materials.indexOf(r.material)&&this.scene.addMaterial(r.material)}null===a.parent&&r.rootNodes.push(a)};return u.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,r=s[i.uniqueId],a=("number"==typeof r?n[r]:i).createInstance(t.name);d(t,a)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);const i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);d(e,i)}})),this.skeletons.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name);for(const e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){const t=n[s[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==a.indexOf(i))continue;a.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=n[s[e._linkedTransformNode.uniqueId]])}r.skeletons.push(i)})),this.animationGroups.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name,(e=>n[s[e.uniqueId]]||e));r.animationGroups.push(i)})),r}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Qt.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(const e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){const t=[];this.cameras.forEach((i=>{e&&!e(i)||(this.scene.addCamera(i),t.push(i))})),this.lights.forEach((i=>{e&&!e(i)||(this.scene.addLight(i),t.push(i))})),this.meshes.forEach((i=>{e&&!e(i)||(this.scene.addMesh(i),t.push(i))})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.addSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.addAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.addAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.addMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.addMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.addMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.addGeometry(t)})),this.transformNodes.forEach((i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.addActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.addTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.addReflectionProbe(t)}));for(const e of t)e.parent&&-1===this.scene.getNodes().indexOf(e.parent)&&(e.setParent?e.setParent(null):e.parent=null)}removeAllFromScene(){this._isValidHierarchy()||Qt.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach((t=>{e&&!e(t)||this.scene.removeCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.removeLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.removeMesh(t,!0)})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.removeSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.removeAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.removeMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.removeGeometry(t)})),this.transformNodes.forEach((t=>{e&&!e(t)||this.scene.removeTransformNode(t)})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.removeActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.removeTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)}))}dispose(){this.cameras.slice(0).forEach((e=>{e.dispose()})),this.cameras.length=0,this.lights.slice(0).forEach((e=>{e.dispose()})),this.lights.length=0,this.meshes.slice(0).forEach((e=>{e.dispose()})),this.meshes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach((e=>{e.dispose()})),this.multiMaterials.length=0,this.materials.slice(0).forEach((e=>{e.dispose()})),this.materials.length=0,this.geometries.slice(0).forEach((e=>{e.dispose()})),this.geometries.length=0,this.transformNodes.slice(0).forEach((e=>{e.dispose()})),this.transformNodes.length=0,this.actionManagers.slice(0).forEach((e=>{e.dispose()})),this.actionManagers.length=0,this.textures.slice(0).forEach((e=>{e.dispose()})),this.textures.length=0,this.reflectionProbes.slice(0).forEach((e=>{e.dispose()})),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach((e=>{e.dispose()})),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(e&&t)for(const s of e){let e=!0;if(i)for(const t of i)if(s===t){e=!1;break}e&&(t.push(s),s._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new Na);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||("_environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new gs("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=M.LastCreatedScene,t,i=null){if(!e)return ce.Error("No scene available to merge animations to"),[];const s=i||(t=>{let i=null;const s=t.animations.length?t.animations[0].targetProperty:"",n=t.name.split(".").join("").split("_primitive")[0];switch(s){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(n);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(n);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(n)}return i});this.getNodes().forEach((e=>{const t=s(e);if(null!==t){for(const i of e.animations){const e=t.animations.filter((e=>e.targetProperty===i.targetProperty));for(const i of e){const e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}}));const n=[];return this.animationGroups.slice().forEach((e=>{n.push(e.clone(e.name,s)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const i=s(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})),n}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.transformNodes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.lights.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.cameras.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}))}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const e=t.pop();if(e instanceof gs?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof Gi?this.transformNodes.push(e):e instanceof Zs?this.lights.push(e):e instanceof ri&&this.cameras.push(e),e instanceof ji){if(e.material&&-1===this.materials.indexOf(e.material)){this.materials.push(e.material);for(const t of e.material.getActiveTextures())-1===this.textures.indexOf(t)&&this.textures.push(t)}e.skeleton&&-1===this.skeletons.indexOf(e.skeleton)&&this.skeletons.push(e.skeleton),e.morphTargetManager&&-1===this.morphTargetManagers.indexOf(e.morphTargetManager)&&this.morphTargetManagers.push(e.morphTargetManager)}for(const s of e.getChildren())i.has(s)||t.push(s);i.add(e)}this.populateRootNodes()}}class wa{constructor(e){this.byteOffset=0,this.buffer=e}loadAsync(e){return this.buffer.readAsync(this.byteOffset,e).then((e=>{this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._dataByteOffset=0}))}readUint32(){const e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return(e=>{if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0;i<e.byteLength;i++)t+=String.fromCharCode(e[i]);return t})(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}function Ba(e,t,i,s){const n={externalResourceFunction:s};return i&&(n.uri="file:"===t?i:t+i),ArrayBuffer.isView(e)?GLTFValidator.validateBytes(e,n):GLTFValidator.validateString(e,n)}function Ua(){const e=[];onmessage=t=>{const i=t.data;switch(i.id){case"init":importScripts(i.url);break;case"validate":Ba(i.data,i.rootUrl,i.fileName,(t=>new Promise(((i,s)=>{const n=e.length;e.push({resolve:i,reject:s}),postMessage({id:"getExternalResource",index:n,uri:t})})))).then((e=>{postMessage({id:"validate.resolve",value:e})}),(e=>{postMessage({id:"validate.reject",reason:e})}));break;case"getExternalResource.resolve":e[i.index].resolve(i.value);break;case"getExternalResource.reject":e[i.index].reject(i.reason)}}}class ka{static ValidateAsync(e,t,i,s){return"function"==typeof Worker?new Promise(((n,r)=>{const a=`${Ba}(${Ua})()`,o=URL.createObjectURL(new Blob([a],{type:"application/javascript"})),l=new Worker(o),h=e=>{l.removeEventListener("error",h),l.removeEventListener("message",c),r(e)},c=e=>{const t=e.data;switch(t.id){case"getExternalResource":s(t.uri).then((e=>{l.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e.buffer])}),(e=>{l.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})}));break;case"validate.resolve":l.removeEventListener("error",h),l.removeEventListener("message",c),n(t.value),l.terminate();break;case"validate.reject":l.removeEventListener("error",h),l.removeEventListener("message",c),r(t.reason),l.terminate()}};if(l.addEventListener("error",h),l.addEventListener("message",c),l.postMessage({id:"init",url:Qt.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const s=e.slice();l.postMessage({id:"validate",data:s,rootUrl:t,fileName:i},[s.buffer])}else l.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})})):(this._LoadScriptPromise||(this._LoadScriptPromise=Qt.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then((()=>Ba(e,t,i,s))))}}function Ga(e,t,i){try{return Promise.resolve(new Uint8Array(e,t,i))}catch(e){return Promise.reject(e)}}ka.Configuration={url:`${Qt._DefaultCdnUrl}/gltf_validator.js`},function(e){e[e.AUTO=0]="AUTO",e[e.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"}(ma||(ma={})),function(e){e[e.NONE=0]="NONE",e[e.FIRST=1]="FIRST",e[e.ALL=2]="ALL"}(pa||(pa={})),function(e){e[e.LOADING=0]="LOADING",e[e.READY=1]="READY",e[e.COMPLETE=2]="COMPLETE"}(ga||(ga={}));class Va{constructor(){this.onParsedObservable=new g,this.coordinateSystemMode=ma.AUTO,this.animationStartMode=pa.FIRST,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.alwaysComputeBoundingBox=!1,this.loadAllMaterials=!1,this.loadOnlyMaterials=!1,this.skipMaterials=!1,this.useSRGBBuffers=!0,this.targetFps=60,this.alwaysComputeSkeletonRootNode=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable=new g,this.onSkinLoadedObservable=new g,this.onTextureLoadedObservable=new g,this.onMaterialLoadedObservable=new g,this.onCameraLoadedObservable=new g,this.onCompleteObservable=new g,this.onErrorObservable=new g,this.onDisposeObservable=new g,this.onExtensionLoadedObservable=new g,this.validate=!1,this.onValidatedObservable=new g,this._loader=null,this._state=null,this._requests=new Array,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new g,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),this._onParsedObserver=this.onParsedObservable.add(e)}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e)}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e)}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e)}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e)}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,s,n,r,a,o){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,s,a,o),null;this._progressCallback=n;const l=t.name||Qt.GetFilename(t);if(r){if(this.useRangeRequests){this.validate&&ce.Warn("glTF validation is not supported when range requests are enabled");const i={abort:()=>{},onCompleteObservable:new g},n={readAsync:(i,s)=>new Promise(((n,r)=>{this._loadFile(e,t,(e=>{n(new Uint8Array(e))}),!0,(e=>{r(e)}),(e=>{e.setRequestHeader("Range",`bytes=${i}-${i+s-1}`)}))})),byteLength:0};return this._unpackBinaryAsync(new wa(n)).then((e=>{i.onCompleteObservable.notifyObservers(i),s(e)}),a?e=>a(void 0,e):void 0),i}return this._loadFile(e,t,(t=>{this._validate(e,new Uint8Array(t,0,t.byteLength),i,l),this._unpackBinaryAsync(new wa({readAsync:(e,i)=>Ga(t,e,i),byteLength:t.byteLength})).then((e=>{s(e)}),a?e=>a(void 0,e):void 0)}),!0,a)}return this._loadFile(e,t,(t=>{try{this._validate(e,t,i,l),s({json:this._parseJson(t)})}catch{a&&a()}}),!1,a)}_loadBinary(e,t,i,s,n,r){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,r),this._unpackBinaryAsync(new wa({readAsync:(e,i)=>function(e,t,i){try{if(t<0||t>=e.byteLength)throw new RangeError("Offset is out of range.");if(t+i>e.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(e.buffer,e.byteOffset+t,i))}catch(e){return Promise.reject(e)}}(t,e,i),byteLength:t.byteLength})).then((e=>{s(e)}),n?e=>n(void 0,e):void 0)}importMeshAsync(e,t,i,s,n,r){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,s,n,r))))}loadAsync(e,t,i,s,n){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${n||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,s,n))))}loadAssetContainerAsync(e,t,i,s,n){return Promise.resolve().then((()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${n||""}`),this._loader=this._getLoader(t);const r=new Fa(e),a=[];this.onMaterialLoadedObservable.add((e=>{a.push(e)}));const o=[];this.onTextureLoadedObservable.add((e=>{o.push(e)}));const l=[];this.onCameraLoadedObservable.add((e=>{l.push(e)}));const h=[];return this.onMeshLoadedObservable.add((e=>{e.morphTargetManager&&h.push(e.morphTargetManager)})),this._loader.importMeshAsync(null,e,r,t,i,s,n).then((e=>(Array.prototype.push.apply(r.geometries,e.geometries),Array.prototype.push.apply(r.meshes,e.meshes),Array.prototype.push.apply(r.particleSystems,e.particleSystems),Array.prototype.push.apply(r.skeletons,e.skeletons),Array.prototype.push.apply(r.animationGroups,e.animationGroups),Array.prototype.push.apply(r.materials,a),Array.prototype.push.apply(r.textures,o),Array.prototype.push.apply(r.lights,e.lights),Array.prototype.push.apply(r.transformNodes,e.transformNodes),Array.prototype.push.apply(r.cameras,l),Array.prototype.push.apply(r.morphTargetManagers,h),r)))}))}canDirectLoad(e){return-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+Va._MagicBase64Encoded)||e.startsWith("data:;base64,"+Va._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+Va._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+Va._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+Va._MagicBase64Encoded)||t.startsWith(";base64,"+Va._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+Va._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+Va._MagicBase64Encoded)){const i=Ut(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new wa({readAsync:(e,t)=>Ga(i,e,t),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(){return new Va}get loaderState(){return this._state}whenCompleteAsync(){return new Promise(((e,t)=>{this.onCompleteObservable.addOnce((()=>{e()})),this.onErrorObservable.addOnce((e=>{t(e)}))}))}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(ga[this._state]))}_loadFile(e,t,i,s,n,r){const a=e._loadFile(t,i,(e=>{this._onProgress(e,a)}),!0,s,n,r);return a.onCompleteObservable.add((()=>{a._lengthComputable=!0,a._total=a._loaded})),this._requests.push(a),a}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,s=0,n=0;for(const e of this._requests){if(void 0===e._lengthComputable||void 0===e._loaded||void 0===e._total)return;i=i&&e._lengthComputable,s+=e._loaded,n+=e._total}this._progressCallback({lengthComputable:i,loaded:s,total:i?n:0})}_validate(e,t,i="",s=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),ka.ValidateAsync(t,i,s,(t=>this.preprocessUrlAsync(i+t).then((t=>e._loadFileAsync(t,void 0,!0,!0).then((e=>new Uint8Array(e,0,e.byteLength))))))).then((e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()}),(e=>{this._endPerformanceCounter("Validate JSON"),Qt.Warn(`Failed to validate: ${e.message}`),this.onValidatedObservable.clear()})))}_getLoader(e){const t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);const i=Va._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=Va._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(Va._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const s={1:Va._CreateGLTF1Loader,2:Va._CreateGLTF2Loader}[i.major];if(!s)throw new Error("Unsupported version: "+t.version);return s(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);const t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then((()=>{const t=e.readUint32();if(1179937895!==t)throw new Ie("Unexpected magic: "+t,Ee);const i=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${i}`);const s=e.readUint32();let n;switch(this.useRangeRequests||s===e.buffer.byteLength||ce.Warn(`Length in header does not match actual data length: ${s} != ${e.buffer.byteLength}`),i){case 1:n=this._unpackBinaryV1Async(e,s);break;case 2:n=this._unpackBinaryV2Async(e,s);break;default:throw new Error("Unsupported version: "+i)}return this._endPerformanceCounter("Unpack Binary"),n}))}_unpackBinaryV1Async(e,t){const i=e.readUint32(),s=e.readUint32();if(0!==s)throw new Error(`Unexpected content format: ${s}`);const n=t-e.byteOffset,r={json:this._parseJson(e.readString(i)),bin:null};if(0!==n){const t=e.byteOffset;r.bin={readAsync:(i,s)=>e.buffer.readAsync(t+i,s),byteLength:n}}return Promise.resolve(r)}_unpackBinaryV2Async(e,t){const i=1313821514,s=5130562,n=e.readUint32();if(e.readUint32()!==i)throw new Error("First chunk format is not JSON");return e.byteOffset+n===t?e.loadAsync(n).then((()=>({json:this._parseJson(e.readString(n)),bin:null}))):e.loadAsync(n+8).then((()=>{const r={json:this._parseJson(e.readString(n)),bin:null},a=()=>{const n=e.readUint32();switch(e.readUint32()){case i:throw new Error("Unexpected JSON chunk");case s:{const t=e.byteOffset;r.bin={readAsync:(i,s)=>e.buffer.readAsync(t+i,s),byteLength:n},e.skipBytes(n);break}default:e.skipBytes(n)}return e.byteOffset!==t?e.loadAsync(8).then(a):Promise.resolve(r)};return a()}))}static _parseVersion(e){if("1.0"===e||"1.0.1"===e)return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.major<t.major?-1:e.minor>t.minor?1:e.minor<t.minor?-1:0}_logOpen(e){this._log(e),this._logIndentLevel++}_logClose(){--this._logIndentLevel}_logEnabled(e){const t=Va._logSpaces.substr(0,2*this._logIndentLevel);ce.Log(`${t}${e}`)}_logDisabled(e){}_startPerformanceCounterEnabled(e){Qt.StartPerformanceCounter(e)}_startPerformanceCounterDisabled(e){}_endPerformanceCounterEnabled(e){Qt.EndPerformanceCounter(e)}_endPerformanceCounterDisabled(e){}}function Xa(e,t,i,s){return B.FromArray(t,i).scaleInPlace(s)}Va.IncrementalLoading=!0,Va.HomogeneousCoordinates=!1,Va._MagicBase64Encoded="Z2xURg",Va._logSpaces=" ",Pn&&Pn.RegisterPlugin(new Va);class Ha{constructor(e,t,i,s){this.type=e,this.name=t,this.getValue=i,this.getStride=s}_buildAnimation(e,t,i){const s=new Ls(e,this.name,t,this.type);return s.setKeys(i),s}}class za extends Ha{buildAnimations(e,t,i,s,n){n(e._babylonTransformNode,this._buildAnimation(t,i,s))}}const Wa={translation:[new za(Ls.ANIMATIONTYPE_VECTOR3,"position",Xa,(()=>3))],rotation:[new za(Ls.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",(function(e,t,i,s){return k.FromArray(t,i).scaleInPlace(s)}),(()=>4))],scale:[new za(Ls.ANIMATIONTYPE_VECTOR3,"scaling",Xa,(()=>3))],weights:[new class extends Ha{buildAnimations(e,t,i,s,n){if(e._numMorphTargets)for(let r=0;r<e._numMorphTargets;r++){const a=new Ls(`${t}_${r}`,this.name,i,this.type);if(a.setKeys(s.map((e=>({frame:e.frame,inTangent:e.inTangent?e.inTangent[r]:void 0,value:e.value[r],outTangent:e.outTangent?e.outTangent[r]:void 0,interpolation:e.interpolation})))),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(r),i=a.clone();e.animations.push(i),n(e,i)}}}}(Ls.ANIMATIONTYPE_FLOAT,"influence",(function(e,t,i,s){const n=new Array(e._numMorphTargets);for(let e=0;e<n.length;e++)n[e]=t[i++]*s;return n}),(e=>e._numMorphTargets))]};function Ya(...e){const t=e=>e&&"object"==typeof e;return e.reduce(((e,i)=>(Object.keys(i).forEach((s=>{const n=e[s],r=i[s];Array.isArray(n)&&Array.isArray(r)?e[s]=n.concat(...r):t(n)&&t(r)?e[s]=Ya(n,r):e[s]=r})),e)),{})}class Ka{static Get(e,t,i){if(!t||null==i||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return e&&null!=t&&e[t]?e[t]:null}static Assign(e){if(e)for(let t=0;t<e.length;t++)e[t].index=t}}class qa{static RegisterExtension(e,t){qa.UnregisterExtension(e)&&ce.Warn(`Extension with the name '${e}' already exists`),qa._RegisteredExtensions[e]={factory:t}}static UnregisterExtension(e){return!!qa._RegisteredExtensions[e]&&(delete qa._RegisteredExtensions[e],!0)}get gltf(){if(!this._gltf)throw new Error("glTF JSON is not available");return this._gltf}get bin(){return this._bin}get parent(){return this._parent}get babylonScene(){if(!this._babylonScene)throw new Error("Scene is not available");return this._babylonScene}get rootBabylonMesh(){return this._rootBabylonMesh}get rootUrl(){return this._rootUrl}constructor(e){this._completePromises=new Array,this._assetContainer=null,this._babylonLights=[],this._disableInstancedMesh=0,this._allMaterialsDirtyRequired=!1,this._extensions=new Array,this._disposed=!1,this._rootUrl=null,this._fileName=null,this._uniqueRootUrl=null,this._bin=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions=new Array,this._parent=e}dispose(){this._disposed||(this._disposed=!0,this._completePromises.length=0,this._extensions.forEach((e=>e.dispose&&e.dispose())),this._extensions.length=0,this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,i,s,n,r,a=""){return Promise.resolve().then((()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(s);let r=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);r=(e instanceof Array?e:[e]).map((e=>{const i=t[e];if(void 0===i)throw new Error(`Failed to find node '${e}'`);return i}))}return this._loadAsync(n,a,r,(()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]})))}))}loadAsync(e,t,i,s,n=""){return Promise.resolve().then((()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,n,null,(()=>{})))))}_loadAsync(e,t,i,s){return Promise.resolve().then((()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,this._loadExtensions(),this._checkExtensions();const n=`${ga[ga.LOADING]} => ${ga[ga.READY]}`,r=`${ga[ga.LOADING]} => ${ga[ga.COMPLETE]}`;this._parent._startPerformanceCounter(n),this._parent._startPerformanceCounter(r),this._parent._setState(ga.LOADING),this._extensionsOnLoading();const a=new Array,o=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(i)a.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=Ka.Get("/scene",this._gltf.scenes,this._gltf.scene||0);a.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e<this._gltf.materials.length;++e){const t=this._gltf.materials[e],i="/materials/"+e,s=ls.TriangleFillMode;a.push(this._loadMaterialAsync(i,t,null,s,(()=>{})))}this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=o:this._babylonScene._forceBlockMaterialDirtyMechanism(o),this._parent.compileMaterials&&a.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&a.push(this._compileShadowGeneratorsAsync());return Promise.all(a).then((()=>(this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(ga.READY),this._startAnimations(),s()))).then((e=>(this._parent._endPerformanceCounter(n),Qt.SetImmediate((()=>{this._disposed||Promise.all(this._completePromises).then((()=>{this._parent._endPerformanceCounter(r),this._parent._setState(ga.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()}),(e=>{this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()}))})),e)))})).catch((e=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()),e}))}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){const i=t[0];(i.byteLength<e.bin.byteLength-3||i.byteLength>e.bin.byteLength)&&ce.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else ce.Warn("Unexpected BIN chunk")}}_setupData(){if(Ka.Assign(this._gltf.accessors),Ka.Assign(this._gltf.animations),Ka.Assign(this._gltf.buffers),Ka.Assign(this._gltf.bufferViews),Ka.Assign(this._gltf.cameras),Ka.Assign(this._gltf.images),Ka.Assign(this._gltf.materials),Ka.Assign(this._gltf.meshes),Ka.Assign(this._gltf.nodes),Ka.Assign(this._gltf.samplers),Ka.Assign(this._gltf.scenes),Ka.Assign(this._gltf.skins),Ka.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const t of this._gltf.nodes)if(t.children)for(const i of t.children)e[i]=t.index;const t=this._createRootNode();for(const i of this._gltf.nodes){const s=e[i.index];i.parent=void 0===s?t:this._gltf.nodes[s]}}}_loadExtensions(){for(const e in qa._RegisteredExtensions){const t=qa._RegisteredExtensions[e].factory(this);t.name!==e&&ce.Warn(`The name of the glTF loader extension instance does not match the registered name: ${t.name} !== ${e}`),this._extensions.push(t),this._parent.onExtensionLoadedObservable.notifyObservers(t)}this._extensions.sort(((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE))),this._parent.onExtensionLoadedObservable.clear()}_checkExtensions(){if(this._gltf.extensionsRequired)for(const e of this._gltf.extensionsRequired){if(!this._extensions.some((t=>t.name===e&&t.enabled)))throw new Error(`Required extension ${e} is not available`)}}_createRootNode(){if(void 0!==this._parent.customRootNode)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:null===this._rootBabylonMesh?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const e=new gs("__root__",this._babylonScene);this._rootBabylonMesh=e,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case ma.AUTO:this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],qa._LoadTransform(t,this._rootBabylonMesh));break;case ma.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(e),t}loadSceneAsync(e,t){const i=this._extensionsLoadSceneAsync(e,t);if(i)return i;const s=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const i of t.nodes){const t=Ka.Get(`${e}/nodes/${i}`,this._gltf.nodes,i);s.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=this._rootBabylonMesh})))}for(const e of this._postSceneLoadActions)e();return s.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(s).then((()=>{}))}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,(t=>{const i=t.geometry;i&&-1===e.indexOf(i)&&e.push(i)}));return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof ji&&e.push(this._rootBabylonMesh);const t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,(t=>{e.push(t)}));return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)i._babylonTransformNode&&"TransformNode"===i._babylonTransformNode.getClassName()&&e.push(i._babylonTransformNode),i._babylonTransformNodeForSkin&&e.push(i._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const i of t)i._babylonAnimationGroup&&e.push(i._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case pa.NONE:break;case pa.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case pa.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void ce.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,t,i=()=>{}){const s=this._extensionsLoadNodeAsync(e,t,i);if(s)return s;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const n=new Array;this.logOpen(`${e} ${t.name||""}`);const r=s=>{if(qa.AddPointerMetadata(s,e),qa._LoadTransform(t,s),null!=t.camera){const i=Ka.Get(`${e}/camera`,this._gltf.cameras,t.camera);n.push(this.loadCameraAsync(`/cameras/${i.index}`,i,(e=>{e.parent=s})))}if(t.children)for(const i of t.children){const t=Ka.Get(`${e}/children/${i}`,this._gltf.nodes,i);n.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=s})))}i(s)};if(null==t.mesh||null!=t.skin){const e=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Gi(e,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==t.mesh?t._babylonTransformNode=i:t._babylonTransformNodeForSkin=i,r(i)}if(null!=t.mesh)if(null==t.skin){const i=Ka.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);n.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,r))}else{const i=Ka.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);n.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,(i=>{const s=t._babylonTransformNodeForSkin;i.metadata=Ya(s.metadata,i.metadata||{});const r=Ka.Get(`${e}/skin`,this._gltf.skins,t.skin);n.push(this._loadSkinAsync(`/skins/${r.index}`,t,r,(e=>{this._forEachPrimitive(t,(t=>{t.skeleton=e})),this._postSceneLoadActions.push((()=>{if(null!=r.skeleton){const e=Ka.Get(`/skins/${r.index}/skeleton`,this._gltf.nodes,r.skeleton).parent;t.index===e.index?i.parent=s.parent:i.parent=e._babylonTransformNode}else i.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:s,skinnedNode:i})}))})))})))}return this.logClose(),Promise.all(n).then((()=>(this._forEachPrimitive(t,(e=>{e.geometry&&e.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0,!0)})),t._babylonTransformNode)))}_loadMeshAsync(e,t,i,s){const n=i.primitives;if(!n||!n.length)throw new Error(`${e}: Primitives are missing`);null==n[0].index&&Ka.Assign(n);const r=new Array;this.logOpen(`${e} ${i.name||""}`);const a=t.name||`node${t.index}`;if(1===n.length){const s=i.primitives[0];r.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${s.index}`,a,t,i,s,(e=>{t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]})))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new Gi(a,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const s of n)r.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${s.index}`,`${a}_primitive${s.index}`,t,i,s,(e=>{e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)})))}return s(t._babylonTransformNode),this.logClose(),Promise.all(r).then((()=>t._babylonTransformNode))}_loadMeshPrimitiveAsync(e,t,i,s,n,r){const a=this._extensionsLoadMeshPrimitiveAsync(e,t,i,s,n,r);if(a)return a;this.logOpen(`${e}`);const o=0===this._disableInstancedMesh&&this._parent.createInstances&&null==i.skin&&!s.primitives[0].targets;let l,h;if(o&&n._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,l=n._instanceData.babylonSourceMesh.createInstance(t),l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,h=n._instanceData.promise;else{const r=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new gs(t,this._babylonScene);a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.sideOrientation=this._babylonScene.useRightHandedSystem?ls.CounterClockWiseSideOrientation:ls.ClockWiseSideOrientation,this._createMorphTargets(e,i,s,n,a),r.push(this._loadVertexDataAsync(e,n,a).then((t=>this._loadMorphTargetsAsync(e,n,a,t).then((()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(a),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})))));const c=qa._GetDrawMode(e,n.mode);if(null==n.material){let e=this._defaultBabylonMaterialData[c];e||(e=this._createDefaultMaterial("__GLTFLoader._default",c),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[c]=e),a.material=e}else if(!this.parent.skipMaterials){const t=Ka.Get(`${e}/material`,this._gltf.materials,n.material);r.push(this._loadMaterialAsync(`/materials/${t.index}`,t,a,c,(e=>{a.material=e})))}h=Promise.all(r),o&&(n._instanceData={babylonSourceMesh:a,promise:h}),l=a}return qa.AddPointerMetadata(l,e),this._parent.onMeshLoadedObservable.notifyObservers(l),r(l),this.logClose(),h.then((()=>l))}_loadVertexDataAsync(e,t,i){const s=this._extensionsLoadVertexDataAsync(e,t,i);if(s)return s;const n=t.attributes;if(!n)throw new Error(`${e}: Attributes are missing`);const r=new Array,a=new Ci(i.name,this._babylonScene);if(null==t.indices)i.isUnIndexed=!0;else{const i=Ka.Get(`${e}/indices`,this._gltf.accessors,t.indices);r.push(this._loadIndicesAccessorAsync(`/accessors/${i.index}`,i).then((e=>{a.setIndices(e)})))}const o=(t,s,o)=>{if(null==n[t])return;i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(s)&&i._delayInfo.push(s);const l=Ka.Get(`${e}/attributes/${t}`,this._gltf.accessors,n[t]);r.push(this._loadVertexAccessorAsync(`/accessors/${l.index}`,l,s).then((e=>{if(e.getKind()===li.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&l.min&&l.max){const e=X.Vector3[0].copyFromFloats(...l.min),t=X.Vector3[1].copyFromFloats(...l.max);if(l.normalized&&5126!==l.componentType){let i=1;switch(l.componentType){case 5120:i=127;break;case 5121:i=255;break;case 5122:i=32767;break;case 5123:i=65535}const s=1/i;e.scaleInPlace(s),t.scaleInPlace(s)}a._boundingInfo=new pi(e,t),a.useBoundingInfoFromGeometry=!0}a.setVerticesBuffer(e,l.count)}))),s==li.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),o&&o(l)};return o("POSITION",li.PositionKind),o("NORMAL",li.NormalKind),o("TANGENT",li.TangentKind),o("TEXCOORD_0",li.UVKind),o("TEXCOORD_1",li.UV2Kind),o("TEXCOORD_2",li.UV3Kind),o("TEXCOORD_3",li.UV4Kind),o("TEXCOORD_4",li.UV5Kind),o("TEXCOORD_5",li.UV6Kind),o("JOINTS_0",li.MatricesIndicesKind),o("WEIGHTS_0",li.MatricesWeightsKind),o("JOINTS_1",li.MatricesIndicesExtraKind),o("WEIGHTS_1",li.MatricesWeightsExtraKind),o("COLOR_0",li.ColorKind,(e=>{"VEC4"===e.type&&(i.hasVertexAlpha=!0)})),Promise.all(r).then((()=>a))}_createMorphTargets(e,t,i,s,n){if(!s.targets)return;if(null==t._numMorphTargets)t._numMorphTargets=s.targets.length;else if(s.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const r=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,n.morphTargetManager=new Da(this._babylonScene),n.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e<s.targets.length;e++){const s=t.weights?t.weights[e]:i.weights?i.weights[e]:0,a=r?r[e]:`morphTarget${e}`;n.morphTargetManager.addTarget(new xa(a,s,n.getScene()))}}_loadMorphTargetsAsync(e,t,i,s){if(!t.targets)return Promise.resolve();const n=new Array,r=i.morphTargetManager;for(let i=0;i<r.numTargets;i++){const a=r.getTarget(i);n.push(this._loadMorphTargetVertexDataAsync(`${e}/targets/${i}`,s,t.targets[i],a))}return Promise.all(n).then((()=>{r.areUpdatesFrozen=!1}))}_loadMorphTargetVertexDataAsync(e,t,i,s){const n=new Array,r=(s,r,a)=>{if(null==i[s])return;const o=t.getVertexBuffer(r);if(!o)return;const l=Ka.Get(`${e}/${s}`,this._gltf.accessors,i[s]);n.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then((e=>{a(o,e)})))};return r("POSITION",li.PositionKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(t.length,((e,s)=>{i[s]=t[s]+e})),s.setPositions(i)})),r("NORMAL",li.NormalKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(i.length,((e,s)=>{i[s]=t[s]+e})),s.setNormals(i)})),r("TANGENT",li.TangentKind,((e,t)=>{const i=new Float32Array(t.length/3*4);let n=0;e.forEach(t.length/3*4,((e,s)=>{(s+1)%4!=0&&(i[n]=t[n]+e,n++)})),s.setTangents(i)})),Promise.all(n).then((()=>{}))}static _LoadTransform(e,t){if(null!=e.skin)return;let i=B.Zero(),s=k.Identity(),n=B.One();if(e.matrix){G.FromArray(e.matrix).decompose(n,s,i)}else e.translation&&(i=B.FromArray(e.translation)),e.rotation&&(s=k.FromArray(e.rotation)),e.scale&&(n=B.FromArray(e.scale));t.position=i,t.rotationQuaternion=s,t.scaling=n}_loadSkinAsync(e,t,i,s){const n=this._extensionsLoadSkinAsync(e,t,i);if(n)return n;if(i._data)return s(i._data.babylonSkeleton),i._data.promise;const r=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new Ma(i.name||r,r,this._babylonScene);a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,a);const o=this._loadSkinInverseBindMatricesDataAsync(e,i).then((e=>{this._updateBoneMatrices(a,e)}));return i._data={babylonSkeleton:a,promise:o},s(a),o}_loadBones(e,t,i){if(null==t.skeleton||this._parent.alwaysComputeSkeletonRootNode){const i=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(i)if(void 0===t.skeleton)t.skeleton=i.index;else{const s=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},n=Ka.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);n===i||s(n,i)||(ce.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=i.index)}else ce.Warn(`${e}: Failed to find common root`)}const s={};for(const n of t.joints){const r=Ka.Get(`${e}/joints/${n}`,this._gltf.nodes,n);this._loadBone(r,t,i,s)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const i={};for(const s of t){const t=[];let n=Ka.Get(`${e}/${s}`,this._gltf.nodes,s);for(;-1!==n.index;)t.unshift(n),n=n.parent;i[s]=t}let s=null;for(let e=0;;++e){let n=i[t[0]];if(e>=n.length)return s;const r=n[e];for(let a=1;a<t.length;++a)if(n=i[t[a]],e>=n.length||r!==n[e])return s;s=r}}_loadBone(e,t,i,s){let n=s[e.index];if(n)return n;let r=null;e.index!==t.skeleton&&(e.parent&&-1!==e.parent.index?r=this._loadBone(e.parent,t,i,s):void 0!==t.skeleton&&ce.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const a=t.joints.indexOf(e.index);return n=new ia(e.name||`joint${e.index}`,i,r,this._getNodeMatrix(e),null,null,a),s[e.index]=n,this._postSceneLoadActions.push((()=>{n.linkTransformNode(e._babylonTransformNode)})),n}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const i=Ka.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)}_updateBoneMatrices(e,t){for(const i of e.bones){const e=G.Identity(),s=i._index;t&&-1!==s&&(G.FromArrayToRef(t,16*s,e),e.invertToRef(e));const n=i.getParent();n&&e.multiplyToRef(n.getAbsoluteInverseBindMatrix(),e),i.updateMatrix(e,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?G.FromArray(e.matrix):G.Compose(e.scale?B.FromArray(e.scale):B.One(),e.rotation?k.FromArray(e.rotation):k.Identity(),e.translation?B.FromArray(e.translation):B.Zero())}loadCameraAsync(e,t,i=()=>{}){const s=this._extensionsLoadCameraAsync(e,t,i);if(s)return s;const n=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const r=new Ra(t.name||`camera${t.index}`,B.Zero(),this._babylonScene,!1);switch(r._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.ignoreParentScaling=!0,t._babylonCamera=r,r.rotation.set(0,Math.PI,0),t.type){case"perspective":{const i=t.perspective;if(!i)throw new Error(`${e}: Camera perspective properties are missing`);r.fov=i.yfov,r.minZ=i.znear,r.maxZ=i.zfar||0;break}case"orthographic":if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);r.mode=ri.ORTHOGRAPHIC_CAMERA,r.orthoLeft=-t.orthographic.xmag,r.orthoRight=t.orthographic.xmag,r.orthoBottom=-t.orthographic.ymag,r.orthoTop=t.orthographic.ymag,r.minZ=t.orthographic.znear,r.maxZ=t.orthographic.zfar;break;default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return qa.AddPointerMetadata(r,e),this._parent.onCameraLoadedObservable.notifyObservers(r),i(r),this.logClose(),Promise.all(n).then((()=>r))}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i<e.length;i++){const s=e[i];t.push(this.loadAnimationAsync(`/animations/${s.index}`,s).then((e=>{0===e.targetedAnimations.length&&e.dispose()})))}return Promise.all(t).then((()=>{}))}loadAnimationAsync(e,t){const i=this._extensionsLoadAnimationAsync(e,t);if(i)return i;this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new Ia(t.name||`animation${t.index}`,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=s;const n=new Array;Ka.Assign(t.channels),Ka.Assign(t.samplers);for(const i of t.channels)n.push(this._loadAnimationChannelAsync(`${e}/channels/${i.index}`,e,t,i,((e,t)=>{e.animations=e.animations||[],e.animations.push(t),s.addTargetedAnimation(t,e)})));return Promise.all(n).then((()=>(s.normalize(0),s)))}_loadAnimationChannelAsync(e,t,i,s,n){const r=this._extensionsLoadAnimationChannelAsync(e,t,i,s,n);if(r)return r;if(null==s.target.node)return Promise.resolve();const a=Ka.Get(`${e}/target/node`,this._gltf.nodes,s.target.node);if("weights"===s.target.path&&!a._numMorphTargets||"weights"!==s.target.path&&!a._babylonTransformNode)return Promise.resolve();let o;switch(s.target.path){case"translation":o=Wa.translation;break;case"rotation":o=Wa.rotation;break;case"scale":o=Wa.scale;break;case"weights":o=Wa.weights;break;default:throw new Error(`${e}/target/path: Invalid value (${s.target.path})`)}const l={object:a,info:o};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,l,n)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,s,n,r){const a=this.parent.targetFps,o=1/a,l=Ka.Get(`${e}/sampler`,i.samplers,s.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${s.sampler}`,l).then((e=>{let t=0;const l=n.object,h=n.info;for(const n of h){const h=n.getStride(l),c=e.input,u=e.output,d=new Array(c.length);let _=0;switch(e.interpolation){case"STEP":for(let e=0;e<c.length;e++){const t=n.getValue(l,u,_,1);_+=h,d[e]={frame:c[e]*a,value:t,interpolation:1}}break;case"CUBICSPLINE":for(let e=0;e<c.length;e++){const t=n.getValue(l,u,_,o);_+=h;const i=n.getValue(l,u,_,1);_+=h;const s=n.getValue(l,u,_,o);_+=h,d[e]={frame:c[e]*a,inTangent:t,value:i,outTangent:s}}break;case"LINEAR":for(let e=0;e<c.length;e++){const t=n.getValue(l,u,_,1);_+=h,d[e]={frame:c[e]*a,value:t}}}if(_>0){const e=`${i.name||`animation${i.index}`}_channel${s.index}_${t}`;n.buildAnimations(l,e,a,d,((e,i)=>{++t,r(e,i)}))}}}))}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const i=t.interpolation||"LINEAR";switch(i){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const s=Ka.Get(`${e}/input`,this._gltf.accessors,t.input),n=Ka.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${s.index}`,s),this._loadFloatAccessorAsync(`/accessors/${n.index}`,n)]).then((([e,t])=>({input:e,interpolation:i,output:t}))),t._data}loadBufferAsync(e,t,i,s){const n=this._extensionsLoadBufferAsync(e,t,i,s);if(n)return n;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then((t=>{try{return new Uint8Array(t.buffer,t.byteOffset+i,s)}catch(t){throw new Error(`${e}: ${t.message}`)}}))}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const s=Ka.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${s.index}`,s,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;const s=qa._GetNumComponents(e,t.type),n=s*li.GetTypeByteLength(t.componentType),r=s*t.count;if(null==t.bufferView)t._data=Promise.resolve(new i(r));else{const a=Ka.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${a.index}`,a).then((o=>{if(5126!==t.componentType||t.normalized||a.byteStride&&a.byteStride!==n){const e=new i(r);return li.ForEach(o,t.byteOffset||0,a.byteStride||n,s,t.componentType,e.length,t.normalized||!1,((t,i)=>{e[i]=t})),e}return qa._GetTypedArray(e,t.componentType,o,t.byteOffset,r)}))}if(t.sparse){const r=t.sparse;t._data=t._data.then((a=>{const o=a,l=Ka.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,r.indices.bufferView),h=Ka.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,r.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${l.index}`,l),this.loadBufferViewAsync(`/bufferViews/${h.index}`,h)]).then((([a,l])=>{const h=qa._GetTypedArray(`${e}/sparse/indices`,r.indices.componentType,a,r.indices.byteOffset,r.count),c=s*r.count;let u;if(5126!==t.componentType||t.normalized){const a=qa._GetTypedArray(`${e}/sparse/values`,t.componentType,l,r.values.byteOffset,c);u=new i(c),li.ForEach(a,0,n,s,t.componentType,u.length,t.normalized||!1,((e,t)=>{u[t]=e}))}else u=qa._GetTypedArray(`${e}/sparse/values`,t.componentType,l,r.values.byteOffset,c);let d=0;for(let e=0;e<h.length;e++){let t=h[e]*s;for(let e=0;e<s;e++)o[t++]=u[d++]}return o}))}))}return t._data}_loadFloatAccessorAsync(e,t){return this._loadAccessorAsync(e,t,Float32Array)}_loadIndicesAccessorAsync(e,t){if("SCALAR"!==t.type)throw new Error(`${e}/type: Invalid value ${t.type}`);if(5121!==t.componentType&&5123!==t.componentType&&5125!==t.componentType)throw new Error(`${e}/componentType: Invalid value ${t.componentType}`);if(t._data)return t._data;if(t.sparse){const i=qa._GetTypedArrayConstructor(`${e}/componentType`,t.componentType);t._data=this._loadAccessorAsync(e,t,i)}else{const i=Ka.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i).then((i=>qa._GetTypedArray(e,t.componentType,i,t.byteOffset,t.count)))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then((e=>new oi(t,e,!1))),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){if(t._babylonVertexBuffer?.[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const s=this._babylonScene.getEngine();if(t.sparse||null==t.bufferView)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new li(s,e,i,!1)));else{const n=Ka.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(n).then((r=>{const a=qa._GetNumComponents(e,t.type);return new li(s,r,i,!1,void 0,n.byteStride,void 0,t.byteOffset,a,t.componentType,t.normalized,!0,void 0,!0)}))}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);const s=new Array;return t&&(t.baseColorFactor?(i.albedoColor=J.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=J.White(),i.metallic=null==t.metallicFactor?1:t.metallicFactor,i.roughness=null==t.roughnessFactor?1:t.roughnessFactor,t.baseColorTexture&&s.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e}))),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,(e=>{e.name=`${i.name} (Metallic Roughness)`,i.metallicTexture=e}))),i.useMetallnessFromMetallicTextureBlue=!0,i.useRoughnessFromMetallicTextureGreen=!0,i.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(s).then((()=>{}))}_loadMaterialAsync(e,t,i,s,n=()=>{}){const r=this._extensionsLoadMaterialAsync(e,t,i,s,n);if(r)return r;t._data=t._data||{};let a=t._data[s];if(!a){this.logOpen(`${e} ${t.name||""}`);const i=this.createMaterial(e,t,s);a={babylonMaterial:i,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,i)},t._data[s]=a,qa.AddPointerMetadata(i,e),this._parent.onMaterialLoadedObservable.notifyObservers(i),this.logClose()}return i&&(a.babylonMeshes.push(i),i.onDisposeObservable.addOnce((()=>{const e=a.babylonMeshes.indexOf(i);-1!==e&&a.babylonMeshes.splice(e,1)}))),n(a.babylonMaterial),a.promise.then((()=>a.babylonMaterial))}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Br(e,this._babylonScene);return i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.fillMode=t,i.enableSpecularAntiAliasing=!0,i.useRadianceOverAlpha=!this._parent.transparencyAsCoverage,i.useSpecularOverAlpha=!this._parent.transparencyAsCoverage,i.transparencyMode=Br.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const s=this._extensionsCreateMaterial(e,t,i);if(s)return s;const n=t.name||`material${t.index}`;return this._createDefaultMaterial(n,i)}loadMaterialPropertiesAsync(e,t,i){const s=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(s)return s;const n=new Array;return n.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&n.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(n).then((()=>{}))}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.emissiveColor=t.emissiveFactor?J.FromArray(t.emissiveFactor):new J(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,(e=>{e.name=`${i.name} (Normal)`,i.bumpTexture=e}))),i.invertNormalMapX=!this._babylonScene.useRightHandedSystem,i.invertNormalMapY=this._babylonScene.useRightHandedSystem,null!=t.normalTexture.scale&&i.bumpTexture&&(i.bumpTexture.level=t.normalTexture.scale),i.forceIrradianceInFragment=!0),t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,(e=>{e.name=`${i.name} (Occlusion)`,i.ambientTexture=e}))),i.useAmbientInGrayScale=!0,null!=t.occlusionTexture.strength&&(i.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&s.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,(e=>{e.name=`${i.name} (Emissive)`,i.emissiveTexture=e}))),Promise.all(s).then((()=>{}))}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":i.transparencyMode=Br.PBRMATERIAL_OPAQUE,i.alpha=1;break;case"MASK":i.transparencyMode=Br.PBRMATERIAL_ALPHATEST,i.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break;case"BLEND":i.transparencyMode=Br.PBRMATERIAL_ALPHABLEND,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0,i.useAlphaFromAlbedoTexture=!0);break;default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,i=()=>{}){const s=this._extensionsLoadTextureInfoAsync(e,t,i);if(s)return s;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const n=Ka.Get(`${e}/index`,this._gltf.textures,t.index);n._textureInfo=t;const r=this._loadTextureAsync(`/textures/${t.index}`,n,(s=>{s.coordinatesIndex=t.texCoord||0,qa.AddPointerMetadata(s,e),this._parent.onTextureLoadedObservable.notifyObservers(s),i(s)}));return this.logClose(),r}_loadTextureAsync(e,t,i=()=>{}){const s=this._extensionsLoadTextureAsync(e,t,i);if(s)return s;this.logOpen(`${e} ${t.name||""}`);const n=null==t.sampler?qa.DefaultSampler:Ka.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),r=Ka.Get(`${e}/source`,this._gltf.images,t.source),a=this._createTextureAsync(e,n,r,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),a}_createTextureAsync(e,t,i,s=()=>{},n,r){const a=this._loadSampler(`/samplers/${t.index}`,t),o=new Array,l=new Jr;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:a.noMipMaps,invertY:!1,samplingMode:a.samplingMode,onLoad:()=>{this._disposed||l.resolve()},onError:(t,i)=>{this._disposed||l.reject(new Error(`${e}: ${i&&i.message?i.message:t||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:n,useSRGBBuffer:!!r&&this._parent.useSRGBBuffers},c=new wn(null,this._babylonScene,h);return c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.push(l.promise),o.push(this.loadImageAsync(`/images/${i.index}`,i).then((e=>{const t=i.uri||`${this._fileName}#image${i.index}`,s=`data:${this._uniqueRootUrl}${t}`;c.updateURL(s,e)}))),c.wrapU=a.wrapU,c.wrapV=a.wrapV,s(c),Promise.all(o).then((()=>c))}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:qa._GetTextureSamplingMode(e,t),wrapU:qa._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:qa._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{const i=Ka.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}this.logClose()}return t._data}loadUriAsync(e,t,i){const s=this._extensionsLoadUriAsync(e,t,i);if(s)return s;if(!qa._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(wt(i)){const t=new Uint8Array(Ut(i));return this.log(`${e}: Decoded ${i.substr(0,64)}... (${t.length} bytes)`),Promise.resolve(t)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then((t=>new Promise(((s,n)=>{this._parent._loadFile(this._babylonScene,t,(t=>{this._disposed||(this.log(`${e}: Loaded ${i} (${t.byteLength} bytes)`),s(new Uint8Array(t)))}),!0,(t=>{n(new bt(`${e}: Failed to load '${i}'${t?": "+t.status+" "+t.statusText:""}`,t))}))}))))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const i=e._internalMetadata=e._internalMetadata||{},s=i.gltf=i.gltf||{};(s.pointers=s.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=null==t?10497:t){case 33071:return wn.CLAMP_ADDRESSMODE;case 33648:return wn.MIRROR_ADDRESSMODE;case 10497:return wn.WRAP_ADDRESSMODE;default:return ce.Warn(`${e}: Invalid value (${t})`),wn.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=null==t.magFilter?9729:t.magFilter,s=null==t.minFilter?9987:t.minFilter;if(9729===i)switch(s){case 9728:return wn.LINEAR_NEAREST;case 9729:return wn.LINEAR_LINEAR;case 9984:return wn.LINEAR_NEAREST_MIPNEAREST;case 9985:return wn.LINEAR_LINEAR_MIPNEAREST;case 9986:return wn.LINEAR_NEAREST_MIPLINEAR;case 9987:return wn.LINEAR_LINEAR_MIPLINEAR;default:return ce.Warn(`${e}/minFilter: Invalid value (${s})`),wn.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==i&&ce.Warn(`${e}/magFilter: Invalid value (${i})`),s){case 9728:return wn.NEAREST_NEAREST;case 9729:return wn.NEAREST_LINEAR;case 9984:return wn.NEAREST_NEAREST_MIPNEAREST;case 9985:return wn.NEAREST_LINEAR_MIPNEAREST;case 9986:return wn.NEAREST_NEAREST_MIPLINEAR;case 9987:return wn.NEAREST_LINEAR_MIPLINEAR;default:return ce.Warn(`${e}/minFilter: Invalid value (${s})`),wn.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`${e}: Invalid component type ${t}`)}}static _GetTypedArray(e,t,i,s,n){const r=i.buffer;s=i.byteOffset+(s||0);const a=qa._GetTypedArrayConstructor(`${e}/componentType`,t),o=li.GetTypeByteLength(t);return s%o!=0?(ce.Warn(`${e}: Copying buffer as byte offset (${s}) is not a multiple of component type byte length (${o})`),new a(r.slice(s,s+n*o),0)):new a(r,s,n)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return Qt.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,t){switch(null==t&&(t=4),t){case 0:return ls.PointListDrawMode;case 1:return ls.LineListDrawMode;case 2:return ls.LineLoopDrawMode;case 3:return ls.LineStripDrawMode;case 4:return ls.TriangleFillMode;case 5:return ls.TriangleStripDrawMode;case 6:return ls.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");const e=new Array;if(this._gltf.materials)for(const t of this._gltf.materials)if(t._data)for(const i in t._data){const s=t._data[i];for(const t of s.babylonMeshes){t.computeWorldMatrix(!0);const i=s.babylonMaterial;e.push(i.forceCompilationAsync(t)),e.push(i.forceCompilationAsync(t,{useInstances:!0})),this._parent.useClipPlane&&(e.push(i.forceCompilationAsync(t,{clipPlane:!0})),e.push(i.forceCompilationAsync(t,{clipPlane:!0,useInstances:!0})))}}return Promise.all(e).then((()=>{this._parent._endPerformanceCounter("Compile materials")}))}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");const e=new Array,t=this._babylonScene.lights;for(const i of t){const t=i.getShadowGenerator();t&&e.push(t.forceCompilationAsync())}return Promise.all(e).then((()=>{this._parent._endPerformanceCounter("Compile shadow generators")}))}_forEachExtensions(e){for(const t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,i){for(const s of this._extensions)if(s.enabled){const n=`${s.name}.${t}`,r=e;r._activeLoaderExtensionFunctions=r._activeLoaderExtensionFunctions||{};const a=r._activeLoaderExtensionFunctions;if(!a[n]){a[n]=!0;try{const e=i(s);if(e)return e}finally{delete a[n]}}}return null}_extensionsOnLoading(){this._forEachExtensions((e=>e.onLoading&&e.onLoading()))}_extensionsOnReady(){this._forEachExtensions((e=>e.onReady&&e.onReady()))}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",(i=>i.loadSceneAsync&&i.loadSceneAsync(e,t)))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",(s=>s.loadNodeAsync&&s.loadNodeAsync(e,t,i)))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",(s=>s.loadCameraAsync&&s.loadCameraAsync(e,t,i)))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",(s=>s._loadVertexDataAsync&&s._loadVertexDataAsync(e,t,i)))}_extensionsLoadMeshPrimitiveAsync(e,t,i,s,n,r){return this._applyExtensions(n,"loadMeshPrimitive",(a=>a._loadMeshPrimitiveAsync&&a._loadMeshPrimitiveAsync(e,t,i,s,n,r)))}_extensionsLoadMaterialAsync(e,t,i,s,n){return this._applyExtensions(t,"loadMaterial",(r=>r._loadMaterialAsync&&r._loadMaterialAsync(e,t,i,s,n)))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",(s=>s.createMaterial&&s.createMaterial(e,t,i)))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",(s=>s.loadMaterialPropertiesAsync&&s.loadMaterialPropertiesAsync(e,t,i)))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",(s=>s.loadTextureInfoAsync&&s.loadTextureInfoAsync(e,t,i)))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",(s=>s._loadTextureAsync&&s._loadTextureAsync(e,t,i)))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",(i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t)))}_extensionsLoadAnimationChannelAsync(e,t,i,s,n){return this._applyExtensions(i,"loadAnimationChannel",(r=>r._loadAnimationChannelAsync&&r._loadAnimationChannelAsync(e,t,i,s,n)))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",(s=>s._loadSkinAsync&&s._loadSkinAsync(e,t,i)))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",(s=>s._loadUriAsync&&s._loadUriAsync(e,t,i)))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",(i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t)))}_extensionsLoadBufferAsync(e,t,i,s){return this._applyExtensions(t,"loadBuffer",(n=>n.loadBufferAsync&&n.loadBufferAsync(e,t,i,s)))}static LoadExtensionAsync(e,t,i,s){if(!t.extensions)return null;const n=t.extensions[i];return n?s(`${e}/extensions/${i}`,n):null}static LoadExtraAsync(e,t,i,s){if(!t.extras)return null;const n=t.extras[i];return n?s(`${e}/extras/${i}`,n):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&-1!==this._gltf.extensionsUsed.indexOf(e)}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}}qa._RegisteredExtensions={},qa.DefaultSampler={index:-1},Va._CreateGLTF2Loader=e=>new qa(e);class Qa extends Yr{constructor(e,t,i,s=tt.TEXTUREFORMAT_RGBA,n=tt.TEXTURETYPE_UNSIGNED_INT,r=!1,a=!1,o=tt.TEXTURE_TRILINEAR_SAMPLINGMODE,l=null){super("",e),this._texture=e.getEngine().createRawCubeTexture(t,i,s,n,r,a,o,l)}update(e,t,i,s,n=null){this._texture.getEngine().updateRawCubeTexture(this._texture,e,t,i,s,n)}updateRGBDAsync(e,t=null,i=.8,s=0){return function(e,t,i,s,n){const r=ca(e.getEngine().createRawCubeTexture(null,e.width,e.format,e.type,e.generateMipMaps,e.invertY,e.samplingMode,e._compression),t).then((()=>e));return e.onRebuildCallback=e=>({proxy:r,isReady:!0,isAsync:!0}),e._source=13,e._bufferViewArrayArray=t,e._lodGenerationScale=s,e._lodGenerationOffset=n,e._sphericalPolynomial=i,ca(e,t).then((()=>(e.isReady=!0,e)))}(this._texture,e,t,i,s).then((()=>{}))}clone(){return se.Clone((()=>{const e=this.getScene(),t=this._texture,i=new Qa(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return 13===t.source&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i}),this)}}const ja="EXT_lights_image_based";class Za{constructor(e){this.name=ja,this._loader=e,this.enabled=this._loader.isExtensionUsed(ja)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return qa.LoadExtensionAsync(e,t,this.name,((i,s)=>{this._loader._allMaterialsDirtyRequired=!0;const n=new Array;n.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const r=Ka.Get(`${i}/light`,this._lights,s.light);return n.push(this._loadLightAsync(`/extensions/${this.name}/lights/${s.light}`,r).then((e=>{this._loader.babylonScene.environmentTexture=e}))),this._loader.logClose(),Promise.all(n).then((()=>{}))}))}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const s=new Array(t.specularImages.length);for(let n=0;n<t.specularImages.length;n++){const r=t.specularImages[n];s[n]=new Array(r.length);for(let t=0;t<r.length;t++){const a=`${e}/specularImages/${n}/${t}`;this._loader.logOpen(`${a}`);const o=r[t],l=Ka.Get(a,this._loader.gltf.images,o);i.push(this._loader.loadImageAsync(`/images/${o}`,l).then((e=>{s[n][t]=e}))),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then((()=>{const i=new Qa(this._loader.babylonScene,null,t.specularImageSize);if(i.name=t.name||"environment",t._babylonTexture=i,null!=t.intensity&&(i.level=t.intensity),t.rotation){let e=k.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(e=k.Inverse(e)),G.FromQuaternionToRef(e,i.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const n=gr.FromArray(t.irradianceCoefficients);n.scaleInPlace(t.intensity),n.convertIrradianceToLambertianRadiance();const r=Er.FromHarmonics(n),a=(s.length-1)/q.Log2(t.specularImageSize);return i.updateRGBDAsync(s,r,a)}))}return t._loaded.then((()=>t._babylonTexture))}}qa.RegisterExtension(ja,(e=>new Za(e))),gs.prototype.thinInstanceAdd=function(e,t=!0){if(!this.getScene().getEngine().getCaps().instancedArrays)return ce.Error("Thin Instances are not supported on this device as Instanced Array extension not supported"),-1;this._thinInstanceUpdateBufferSize("matrix",Array.isArray(e)?e.length:1);const i=this._thinInstanceDataStorage.instancesCount;if(Array.isArray(e))for(let i=0;i<e.length;++i)this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e[i],i===e.length-1&&t);else this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e,t);return i},gs.prototype.thinInstanceAddSelf=function(e=!0){return this.thinInstanceAdd(G.IdentityReadOnly,e)},gs.prototype.thinInstanceRegisterAttribute=function(e,t){e===li.ColorKind&&(e=li.ColorInstanceKind),this.removeVerticesData(e),this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.strides[e]=t,this._userThinInstanceBuffersStorage.sizes[e]=t*Math.max(32,this._thinInstanceDataStorage.instancesCount),this._userThinInstanceBuffersStorage.data[e]=new Float32Array(this._userThinInstanceBuffersStorage.sizes[e]),this._userThinInstanceBuffersStorage.vertexBuffers[e]=new li(this.getEngine(),this._userThinInstanceBuffersStorage.data[e],e,!0,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])},gs.prototype.thinInstanceSetMatrixAt=function(e,t,i=!0){if(!this._thinInstanceDataStorage.matrixData||e>=this._thinInstanceDataStorage.instancesCount)return!1;const s=this._thinInstanceDataStorage.matrixData;return t.copyToArray(s,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},gs.prototype.thinInstanceSetAttributeAt=function(e,t,i,s=!0){return e===li.ColorKind&&(e=li.ColorInstanceKind),!(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[e]||t>=this._thinInstanceDataStorage.instancesCount)&&(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),s&&this.thinInstanceBufferUpdated(e),!0)},Object.defineProperty(gs.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){const t=this._thinInstanceDataStorage.matrixData??this.source?._thinInstanceDataStorage.matrixData;e<=(t?t.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),gs.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!0){const s=new oi(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(s.createVertexBuffer(e+t,4*t,4));return s},gs.prototype.thinInstanceSetBuffer=function(e,t,i=0,s=!0){i=i||16,"matrix"===e?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,s),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,s))):(e===li.ColorKind&&(e=li.ColorInstanceKind),null===t?this._userThinInstanceBuffersStorage?.data[e]&&(this.removeVerticesData(e),delete this._userThinInstanceBuffersStorage.data[e],delete this._userThinInstanceBuffersStorage.strides[e],delete this._userThinInstanceBuffersStorage.sizes[e],delete this._userThinInstanceBuffersStorage.vertexBuffers[e]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[e]=t,this._userThinInstanceBuffersStorage.strides[e]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new li(this.getEngine(),t,e,!s,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},gs.prototype.thinInstanceBufferUpdated=function(e){"matrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.matrixBuffer?.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):"previousMatrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.previousMatrixBuffer?.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(e===li.ColorKind&&(e=li.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[e].isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0)))},gs.prototype.thinInstancePartialBufferUpdate=function(e,t,i){"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===li.ColorKind&&(e=li.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},gs.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;t<this._thinInstanceDataStorage.instancesCount;++t)this._thinInstanceDataStorage.worldMatrices[t]=G.FromArray(e,16*t)}return this._thinInstanceDataStorage.worldMatrices},gs.prototype.thinInstanceRefreshBoundingInfo=function(e=!1,t=!1,i=!1){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return;const s=this._thinInstanceDataStorage.boundingVectors;if(e||!this.rawBoundingInfo){s.length=0,this.refreshBoundingInfo(t,i);const e=this.getBoundingInfo();this.rawBoundingInfo=new pi(e.minimum,e.maximum)}const n=this.getBoundingInfo(),r=this._thinInstanceDataStorage.matrixData;if(0===s.length)for(let e=0;e<n.boundingBox.vectors.length;++e)s.push(n.boundingBox.vectors[e].clone());X.Vector3[0].setAll(Number.POSITIVE_INFINITY),X.Vector3[1].setAll(Number.NEGATIVE_INFINITY);for(let e=0;e<this._thinInstanceDataStorage.instancesCount;++e){G.FromArrayToRef(r,16*e,X.Matrix[0]);for(let e=0;e<s.length;++e)B.TransformCoordinatesToRef(s[e],X.Matrix[0],X.Vector3[2]),X.Vector3[0].minimizeInPlace(X.Vector3[2]),X.Vector3[1].maximizeInPlace(X.Vector3[2])}n.reConstruct(X.Vector3[0],X.Vector3[1]),this._updateBoundingInfo()},gs.prototype._thinInstanceRecreateBuffer=function(e,t=!0){"matrix"===e?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",this._thinInstanceDataStorage.matrixData,t)):"previousMatrix"===e?this._scene.needsPreviousWorldMatrices&&(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.previousMatrixData??this._thinInstanceDataStorage.matrixData,t)):(e===li.ColorKind&&(e=li.ColorInstanceKind),this._userThinInstanceBuffersStorage.vertexBuffers[e]?.dispose(),this._userThinInstanceBuffersStorage.vertexBuffers[e]=new li(this.getEngine(),this._userThinInstanceBuffersStorage.data[e],e,!t,!1,this._userThinInstanceBuffersStorage.strides[e],!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e]))},gs.prototype._thinInstanceUpdateBufferSize=function(e,t=1){e===li.ColorKind&&(e=li.ColorInstanceKind);const i="matrix"===e;if(!(i||this._userThinInstanceBuffersStorage&&this._userThinInstanceBuffersStorage.strides[e]))return;const s=i?16:this._userThinInstanceBuffersStorage.strides[e],n=i?this._thinInstanceDataStorage.matrixBufferSize:this._userThinInstanceBuffersStorage.sizes[e];let r=i?this._thinInstanceDataStorage.matrixData:this._userThinInstanceBuffersStorage.data[e];const a=(this._thinInstanceDataStorage.instancesCount+t)*s;let o=n;for(;o<a;)o*=2;if(!r||n!=o){if(r){const e=new Float32Array(o);e.set(r,0),r=e}else r=new Float32Array(o);i?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",r,!1),this._thinInstanceDataStorage.matrixData=r,this._thinInstanceDataStorage.matrixBufferSize=o,this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",r,!1))):(this._userThinInstanceBuffersStorage.vertexBuffers[e]?.dispose(),this._userThinInstanceBuffersStorage.data[e]=r,this._userThinInstanceBuffersStorage.sizes[e]=o,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new li(this.getEngine(),r,e,!0,!1,s,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e]))}},gs.prototype._thinInstanceInitializeUserStorage=function(){this._userThinInstanceBuffersStorage||(this._userThinInstanceBuffersStorage={data:{},sizes:{},vertexBuffers:{},strides:{}})},gs.prototype._disposeThinInstanceSpecificData=function(){this._thinInstanceDataStorage?.matrixBuffer&&(this._thinInstanceDataStorage.matrixBuffer.dispose(),this._thinInstanceDataStorage.matrixBuffer=null)};const $a="EXT_mesh_gpu_instancing";class Ja{constructor(e){this.name=$a,this._loader=e,this.enabled=this._loader.isExtensionUsed($a)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((e,s)=>{this._loader._disableInstancedMesh++;const n=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return n;const r=new Array;let a=0;const o=t=>{if(null==s.attributes[t])return void r.push(Promise.resolve(null));const i=Ka.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,s.attributes[t]);if(r.push(this._loader._loadFloatAccessorAsync(`/accessors/${i.bufferView}`,i)),0===a)a=i.count;else if(a!==i.count)throw new Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return o("TRANSLATION"),o("ROTATION"),o("SCALE"),n.then((e=>Promise.all(r).then((([i,s,n])=>{const r=new Float32Array(16*a);X.Vector3[0].copyFromFloats(0,0,0),X.Quaternion[0].copyFromFloats(0,0,0,1),X.Vector3[1].copyFromFloats(1,1,1);for(let e=0;e<a;++e)i&&B.FromArrayToRef(i,3*e,X.Vector3[0]),s&&k.FromArrayToRef(s,4*e,X.Quaternion[0]),n&&B.FromArrayToRef(n,3*e,X.Vector3[1]),G.ComposeToRef(X.Vector3[1],X.Quaternion[0],X.Vector3[0],X.Matrix[0]),X.Matrix[0].copyToArray(r,16*e);for(const e of t._primitiveBabylonMeshes)e.thinInstanceSetBuffer("matrix",r,16,!0);return e}))))}))}}qa.RegisterExtension($a,(e=>new Ja(e)));class eo{static get Default(){return eo._Default||(eo._Default=new eo),eo._Default}constructor(){const e=eo.Configuration.decoder;this._decoderModulePromise=Qt.LoadBabylonScriptAsync(e.url).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,s,n){return this._decoderModulePromise.then((async()=>{MeshoptDecoder.useWorkers(1);const r=await MeshoptDecoder.decodeGltfBufferAsync(t,i,e,s,n);return MeshoptDecoder.useWorkers(0),r}))}}eo.Configuration={decoder:{url:`${Qt._DefaultCdnUrl}/meshopt_decoder.js`}},eo._Default=null;const to="EXT_meshopt_compression";class io{constructor(e){this.name=to,this.enabled=e.isExtensionUsed(to),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return qa.LoadExtensionAsync(e,t,this.name,((i,s)=>{const n=t;if(n._meshOptData)return n._meshOptData;const r=Ka.Get(`${e}/buffer`,this._loader.gltf.buffers,s.buffer);return n._meshOptData=this._loader.loadBufferAsync(`/buffers/${r.index}`,r,s.byteOffset||0,s.byteLength).then((e=>eo.Default.decodeGltfBufferAsync(e,s.count,s.byteStride,s.mode,s.filter))),n._meshOptData}))}}qa.RegisterExtension(to,(e=>new io(e)));const so="EXT_texture_webp";class no{constructor(e){this.name=so,this._loader=e,this.enabled=e.isExtensionUsed(so)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{const r=null==t.sampler?qa.DefaultSampler:Ka.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),a=Ka.Get(`${s}/source`,this._loader.gltf.images,n.source);return this._loader._createTextureAsync(e,r,a,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}qa.RegisterExtension(so,(e=>new no(e)));const ro="EXT_texture_avif";class ao{constructor(e){this.name=ro,this._loader=e,this.enabled=e.isExtensionUsed(ro)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{const r=null==t.sampler?qa.DefaultSampler:Ka.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),a=Ka.Get(`${s}/source`,this._loader.gltf.images,n.source);return this._loader._createTextureAsync(e,r,a,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}qa.RegisterExtension(ro,(e=>new ao(e)));class oo{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map((e=>({workerPromise:Promise.resolve(e),idle:!0})))}dispose(){for(const e of this._workerInfos)e.workerPromise.then((e=>{e.terminate()}));this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(const t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then((i=>{t(i,(()=>{const t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0}))}))}}class lo extends oo{constructor(e,t,i=lo.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length<this._maxWorkers){const t={workerPromise:this._createWorkerAsync(),idle:!1};this._workerInfos.push(t),this._execute(t,e)}else this._pendingActions.push(e)}_execute(e,t){e.timeoutId&&(clearTimeout(e.timeoutId),delete e.timeoutId),super._execute(e,((i,s)=>{t(i,(()=>{s(),e.idle&&(e.timeoutId=setTimeout((()=>{e.workerPromise.then((e=>{e.terminate()}));const t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)}),this._options.idleTimeElapsedBeforeRelease))}))}))}}function ho(e,t,i,s,n){let r=null,a=null,o=null;try{let l;r=new e.Decoder,a=new e.DecoderBuffer,a.Init(t,t.byteLength);const h=r.GetEncodedGeometryType(a);switch(h){case e.TRIANGULAR_MESH:{const t=new e.Mesh;if(l=r.DecodeBufferToMesh(a,t),!l.ok()||0===t.ptr)throw new Error(l.error_msg());const i=3*t.num_faces(),n=4*i,h=e._malloc(n);try{r.GetTrianglesUInt32Array(t,n,h);const a=new Uint32Array(i);a.set(new Uint32Array(e.HEAPF32.buffer,h,i)),s(a)}finally{e._free(h)}o=t;break}case e.POINT_CLOUD:{const t=new e.PointCloud;if(l=r.DecodeBufferToPointCloud(a,t),!l.ok()||!t.ptr)throw new Error(l.error_msg());o=t;break}default:throw new Error(`Invalid geometry type ${h}`)}const c=o.num_points(),u=(t,i,s,r)=>{const a=r.data_type(),o=r.num_components(),l=r.normalized(),h=r.byte_stride(),u=r.byte_offset(),d={[e.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:e.HEAPF32},[e.DT_INT8]:{typedArrayConstructor:Int8Array,heap:e.HEAP8},[e.DT_INT16]:{typedArrayConstructor:Int16Array,heap:e.HEAP16},[e.DT_INT32]:{typedArrayConstructor:Int32Array,heap:e.HEAP32},[e.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:e.HEAPU8},[e.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:e.HEAPU16},[e.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:e.HEAPU32}}[a];if(!d)throw new Error(`Invalid data type ${a}`);const _=c*o,f=_*d.typedArrayConstructor.BYTES_PER_ELEMENT,m=e._malloc(f);try{t.GetAttributeDataArrayForAllPoints(i,r,a,f,m);const e=new d.typedArrayConstructor(d.heap.buffer,m,_);n(s,e.slice(),o,u,h,l)}finally{e._free(m)}};if(i)for(const e in i){const t=i[e],s=r.GetAttributeByUniqueId(o,t);u(r,o,e,s)}else{const t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(const e in t){const i=r.GetAttributeId(o,t[e]);if(-1!==i){const t=r.GetAttribute(o,i);u(r,o,e,t)}}}return c}finally{o&&e.destroy(o),a&&e.destroy(a),r&&e.destroy(r)}}function co(){let e;onmessage=t=>{const i=t.data;switch(i.id){case"init":{const t=i.decoder;t.url&&importScripts(t.url);const s=t.wasmBinary?{wasmBinary:t.wasmBinary}:{};e=DracoDecoderModule(s),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{const t=ho(e,i.dataView,i.attributes,(e=>{postMessage({id:"indices",data:e},[e.buffer])}),((e,t,i,s,n,r)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:s,byteStride:n,normalized:r},[t.buffer])}));postMessage({id:"decodeMeshDone",totalVertices:t})}))}}}lo.DefaultOptions={idleTimeElapsedBeforeRelease:1e3};class uo{static get DecoderAvailable(){const e=uo.Configuration.decoder;return!!(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly||e.fallbackUrl)}static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static get Default(){return uo._Default||(uo._Default=new uo),uo._Default}static ResetDefault(e){uo._Default&&(e||uo._Default.dispose(),uo._Default=null)}constructor(e=uo.DefaultNumWorkers){const t=uo.Configuration.decoder;if(t.workerPool||"object"==typeof e&&e.workerPool)this._workerPoolPromise=Promise.resolve(t.workerPool||e.workerPool);else{const i=t.wasmBinary||"object"==typeof e&&e.wasmBinary,s="number"==typeof e?e:e.numWorkers,n=s&&"function"==typeof Worker&&"function"==typeof URL,r=n||!n&&!t.jsModule,a=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:r?Qt.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):Qt.LoadFileAsync(Qt.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:r?Qt.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};n?this._workerPoolPromise=a.wasmBinaryPromise.then((e=>{const t=`${ho}(${co})()`,i=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));return new lo(s,(()=>function(e,t,i){return new Promise(((s,n)=>{const r=t=>{e.removeEventListener("error",r),e.removeEventListener("message",a),n(t)},a=t=>{"initDone"===t.data.id&&(e.removeEventListener("error",r),e.removeEventListener("message",a),s(e))};if(e.addEventListener("error",r),e.addEventListener("message",a),t){const s=t.slice(0);e.postMessage({id:"init",decoder:{url:i,wasmBinary:s}},[s])}else e.postMessage({id:"init",decoder:{url:i}})}))}(new Worker(i),e,a.url)))})):this._decoderModulePromise=a.wasmBinaryPromise.then((async e=>{if("undefined"==typeof DracoDecoderModule&&!t.jsModule){if(!a.url)throw new Error("Draco decoder module is not available");await Qt.LoadBabylonScriptAsync(a.url)}return await(i=e,s=t.jsModule,new Promise((e=>{(s||DracoDecoderModule)({wasmBinary:i}).then((t=>{e({module:t})}))})));var i,s}))}}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then((e=>{e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise}async whenReadyAsync(){this._workerPoolPromise?await this._workerPoolPromise:this._decoderModulePromise&&await this._decoderModulePromise}decodeMeshToMeshDataAsync(e,t,i){const s=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength);if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((n,r)=>{e.push(((e,a)=>{let o=null;const l=[],h=t=>{e.removeEventListener("error",h),e.removeEventListener("message",c),r(t),a()},c=t=>{const s=t.data;switch(s.id){case"decodeMeshDone":e.removeEventListener("error",h),e.removeEventListener("message",c),n({indices:o,attributes:l,totalVertices:s.totalVertices}),a();break;case"indices":o=s.data;break;case"attribute":l.push({kind:s.kind,data:s.data,size:s.size,byteOffset:s.byteOffset,byteStride:s.byteStride,normalized:(r=s.kind,u=s.normalized,i&&void 0!==i[r]?(u!==i[r]&&ce.Warn(`Normalized flag from Draco data (${u}) does not match normalized flag from glTF accessor (${i[r]}). Using flag from glTF accessor.`),i[r]):u)})}var r,u};e.addEventListener("error",h),e.addEventListener("message",c);const u=s.slice();e.postMessage({id:"decodeMesh",dataView:u,attributes:t},[u.buffer])}))}))));if(this._decoderModulePromise)return this._decoderModulePromise.then((e=>{let i=null;const n=[],r=ho(e.module,s,t,(e=>{i=e}),((e,t,i,s,r,a)=>{n.push({kind:e,data:t,size:i,byteOffset:s,byteStride:r,normalized:a})}));return{indices:i,attributes:n,totalVertices:r}}));throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,s){const n=await this.decodeMeshToMeshDataAsync(i,s),r=new Ci(e,t);n.indices&&r.setIndices(n.indices);for(const e of n.attributes)r.setVerticesBuffer(new li(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),n.totalVertices);return r}async _decodeMeshToGeometryForGltfAsync(e,t,i,s,n){const r=await this.decodeMeshToMeshDataAsync(i,s,n),a=new Ci(e,t);r.indices&&a.setIndices(r.indices);for(const e of r.attributes)a.setVerticesBuffer(new li(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),r.totalVertices);return a}async decodeMeshAsync(e,t){const i=await this.decodeMeshToMeshDataAsync(e,t),s=new vi;i.indices&&(s.indices=i.indices);for(const e of i.attributes){const t=li.GetFloatData(e.data,e.size,li.GetDataType(e.data),e.byteOffset,e.byteStride,e.normalized,i.totalVertices);s.set(t,e.kind)}return s}}uo.Configuration={decoder:{wasmUrl:`${Qt._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${Qt._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${Qt._DefaultCdnUrl}/draco_decoder_gltf.js`}},uo.DefaultNumWorkers=uo.GetDefaultNumWorkers(),uo._Default=null;const _o="KHR_draco_mesh_compression";class fo{constructor(e){this.name=_o,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=uo.DecoderAvailable&&this._loader.isExtensionUsed(_o)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{if(null!=t.mode&&4!==t.mode&&5!==t.mode)throw new Error(`${e}: Unsupported mode ${t.mode}`);const r={},a={},o=(e,s)=>{const o=n.attributes[e];if(null!=o&&(i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(s)&&i._delayInfo.push(s),r[s]=o,this.useNormalizedFlagFromAccessor)){const i=Ka.TryGet(this._loader.gltf.accessors,t.attributes[e]);i&&(a[s]=i.normalized||!1)}};o("POSITION",li.PositionKind),o("NORMAL",li.NormalKind),o("TANGENT",li.TangentKind),o("TEXCOORD_0",li.UVKind),o("TEXCOORD_1",li.UV2Kind),o("TEXCOORD_2",li.UV3Kind),o("TEXCOORD_3",li.UV4Kind),o("TEXCOORD_4",li.UV5Kind),o("TEXCOORD_5",li.UV6Kind),o("JOINTS_0",li.MatricesIndicesKind),o("WEIGHTS_0",li.MatricesWeightsKind),o("COLOR_0",li.ColorKind);const l=Ka.Get(s,this._loader.gltf.bufferViews,n.bufferView);return l._dracoBabylonGeometry||(l._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${l.index}`,l).then((t=>(this.dracoCompression||uo.Default)._decodeMeshToGeometryForGltfAsync(i.name,this._loader.babylonScene,t,r,a).catch((t=>{throw new Error(`${e}: ${t.message}`)}))))),l._dracoBabylonGeometry}))}}qa.RegisterExtension(_o,(e=>new fo(e)));class mo extends Zs{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=G.Identity(),this._projectionMatrix=G.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=B.Zero()),B.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=B.Zero()),B.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=B.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=B.Cross(this.direction,Ki.Y),t=B.Cross(e,this.direction);return B.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=B.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=G.Identity()),G.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}getDepthMaxZ(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),this.parent&&this.parent.getWorldMatrix||(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=X.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),B.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(B.Dot(t,B.Up()))&&(t.z=1e-13);const s=X.Vector3[1];return i.addToRef(t,s),G.LookAtLHToRef(i,s,B.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}e([c()],mo.prototype,"position",null),e([c()],mo.prototype,"direction",null),e([a()],mo.prototype,"shadowMinZ",null),e([a()],mo.prototype,"shadowMaxZ",null),re.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new po(e,B.Zero(),t)));class po extends mo{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,i){super(e,i),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return Zs.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;t&&G.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=B.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let s=Number.MAX_VALUE,n=-Number.MAX_VALUE;for(let r=0;r<i.length;r++){const a=i[r];if(!a)continue;const o=a.getBoundingInfo().boundingBox;for(let i=0;i<o.vectorsWorld.length;i++)B.TransformCoordinatesToRef(o.vectorsWorld[i],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<s&&(s=e.z),e.z>n&&(n=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=s,this._shadowMaxZ=n)}const n=this._orthoRight-this._orthoLeft,r=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;G.OrthoOffCenterLHToRef(this._orthoLeft-n*this.shadowOrthoScale,this._orthoRight+n*this.shadowOrthoScale,this._orthoBottom-r*this.shadowOrthoScale,this._orthoTop+r*this.shadowOrthoScale,l?o:a,l?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}}e([a()],po.prototype,"shadowFrustumSize",null),e([a()],po.prototype,"shadowOrthoScale",null),e([a()],po.prototype,"autoUpdateExtends",void 0),e([a()],po.prototype,"autoCalcShadowZBounds",void 0),e([a("orthoLeft")],po.prototype,"_orthoLeft",void 0),e([a("orthoRight")],po.prototype,"_orthoRight",void 0),e([a("orthoTop")],po.prototype,"_orthoTop",void 0),e([a("orthoBottom")],po.prototype,"_orthoBottom",void 0),C("BABYLON.DirectionalLight",po),re.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new go(e,B.Zero(),t)));class go extends mo{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){const t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next()){t.value.recreateShadowMap()}}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return Zs.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new B(1,0,0);case 1:return new B(-1,0,0);case 2:return new B(0,-1,0);case 3:return new B(0,1,0);case 4:return new B(0,0,1);case 5:return new B(0,0,-1)}return B.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;const n=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,r=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;G.PerspectiveFovLHToRef(this.shadowAngle,1,a?r:n,a?n:r,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",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.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}e([a()],go.prototype,"shadowAngle",null),C("BABYLON.PointLight",go),re.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new Eo(e,B.Zero(),B.Zero(),0,0,t)));class Eo extends mo{get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(.5*e),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()}get innerAngle(){return this._innerAngle}set innerAngle(e){this._innerAngle=e,this._computeAngleValues()}get shadowAngleScale(){return this._shadowAngleScale}set shadowAngleScale(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()}get projectionTextureMatrix(){return this._projectionTextureMatrix}get projectionTextureLightNear(){return this._projectionTextureLightNear}set projectionTextureLightNear(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureLightFar(){return this._projectionTextureLightFar}set projectionTextureLightFar(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureUpDirection(){return this._projectionTextureUpDirection}set projectionTextureUpDirection(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0}get projectionTexture(){return this._projectionTexture}set projectionTexture(e){this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(Eo._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):Eo._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce((()=>{this._markMeshesAsLightDirty()}))))}static _IsProceduralTexture(e){return void 0!==e.onGeneratedObservable}static _IsTexture(e){return void 0!==e.onLoadObservable}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,s,n,r){super(e,r),this._innerAngle=0,this._projectionTextureMatrix=G.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=B.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=B.Zero(),this._projectionTextureViewLightMatrix=G.Zero(),this._projectionTextureProjectionLightMatrix=G.Zero(),this._projectionTextureScalingMatrix=G.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=s,this.exponent=n}getClassName(){return"SpotLight"}getTypeID(){return Zs.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;this._shadowAngleScale=this._shadowAngleScale||1;const n=this._shadowAngleScale*this._angle,r=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;G.PerspectiveFovLHToRef(n,1,o?a:r,o?r:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),G.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),s=-i*t,n=1/Math.tan(this._angle/2);G.FromValuesToRef(n/1,0,0,0,0,n,0,0,0,0,i,1,0,0,s,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof wn){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;G.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}_computeAngleValues(){this._lightAngleScale=1/Math.max(.001,Math.cos(.5*this._innerAngle)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightTexture"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=B.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=B.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return i=this.computeTransformedInformation()?B.Normalize(this.transformedDirection):B.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!(!this.projectionTexture||!this.projectionTexture.isReady())}}e([a()],Eo.prototype,"angle",null),e([a()],Eo.prototype,"innerAngle",null),e([a()],Eo.prototype,"shadowAngleScale",null),e([a()],Eo.prototype,"exponent",void 0),e([a()],Eo.prototype,"projectionTextureLightNear",null),e([a()],Eo.prototype,"projectionTextureLightFar",null),e([a()],Eo.prototype,"projectionTextureUpDirection",null),e([o("projectedLightTexture")],Eo.prototype,"_projectionTexture",void 0),C("BABYLON.SpotLight",Eo);const To="KHR_lights_punctual";class Ao{constructor(e){this.name=To,this._loader=e,this.enabled=this._loader.isExtensionUsed(To)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,Ka.Assign(this._lights)}}loadNodeAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>(this._loader._allMaterialsDirtyRequired=!0,this._loader.loadNodeAsync(e,t,(e=>{let t;const r=Ka.Get(s,this._lights,n.light),a=r.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,r.type){case"directional":{const e=new po(a,B.Backward(),this._loader.babylonScene);e.position.setAll(0),t=e;break}case"point":t=new go(a,B.Zero(),this._loader.babylonScene);break;case"spot":{const e=new Eo(a,B.Zero(),B.Backward(),0,1,this._loader.babylonScene);e.angle=2*(r.spot&&r.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(r.spot&&r.spot.innerConeAngle||0),t=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${s}: Invalid light type (${r.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,r._babylonLight=t,t.falloffType=Zs.FALLOFF_GLTF,t.diffuse=r.color?J.FromArray(r.color):J.White(),t.intensity=null==r.intensity?1:r.intensity,t.range=null==r.range?Number.MAX_VALUE:r.range,t.parent=e,this._loader._babylonLights.push(t),qa.AddPointerMetadata(t,s),i(e)})))))}}qa.RegisterExtension(To,(e=>new Ao(e)));const Ro="KHR_materials_pbrSpecularGlossiness";class vo{constructor(e){this.name=Ro,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ro)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loadSpecularGlossinessPropertiesAsync(s,n,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then((()=>{}))}))}_loadSpecularGlossinessPropertiesAsync(e,t,i){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.metallic=null,i.roughness=null,t.diffuseFactor?(i.albedoColor=J.FromArray(t.diffuseFactor),i.alpha=t.diffuseFactor[3]):i.albedoColor=J.White(),i.reflectivityColor=t.specularFactor?J.FromArray(t.specularFactor):J.White(),i.microSurface=null==t.glossinessFactor?1:t.glossinessFactor,t.diffuseTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,t.diffuseTexture,(e=>{e.name=`${i.name} (Diffuse)`,i.albedoTexture=e}))),t.specularGlossinessTexture&&(s.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,t.specularGlossinessTexture,(e=>{e.name=`${i.name} (Specular Glossiness)`,i.reflectivityTexture=e,i.reflectivityTexture.hasAlpha=!0}))),i.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(s).then((()=>{}))}}qa.RegisterExtension(Ro,(e=>new vo(e)));const Io="KHR_materials_unlit";class So{constructor(e){this.name=Io,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(Io)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,(()=>this._loadUnlitPropertiesAsync(e,t,i)))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);const s=new Array;i.unlit=!0;const n=t.pbrMetallicRoughness;return n&&(n.baseColorFactor?(i.albedoColor=J.FromArray(n.baseColorFactor),i.alpha=n.baseColorFactor[3]):i.albedoColor=J.White(),n.baseColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,n.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e})))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then((()=>{}))}}qa.RegisterExtension(Io,(e=>new So(e)));const Co="KHR_materials_clearcoat";class bo{constructor(e){this.name=Co,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Co)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadClearCoatPropertiesAsync(s,n,i)),Promise.all(r).then((()=>{}))}))}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.clearCoat.isEnabled=!0,i.clearCoat.useRoughnessFromMainTexture=!1,i.clearCoat.remapF0OnInterfaceChange=!1,null!=t.clearcoatFactor?i.clearCoat.intensity=t.clearcoatFactor:i.clearCoat.intensity=0,t.clearcoatTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,(e=>{e.name=`${i.name} (ClearCoat Intensity)`,i.clearCoat.texture=e}))),null!=t.clearcoatRoughnessFactor?i.clearCoat.roughness=t.clearcoatRoughnessFactor:i.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,(e=>{e.name=`${i.name} (ClearCoat Roughness)`,i.clearCoat.textureRoughness=e})))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,(e=>{e.name=`${i.name} (ClearCoat Normal)`,i.clearCoat.bumpTexture=e}))),i.invertNormalMapX=!i.getScene().useRightHandedSystem,i.invertNormalMapY=i.getScene().useRightHandedSystem,null!=t.clearcoatNormalTexture.scale&&(i.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(s).then((()=>{}))}}qa.RegisterExtension(Co,(e=>new bo(e)));const yo="KHR_materials_iridescence";class Mo{constructor(e){this.name=yo,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(yo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadIridescencePropertiesAsync(s,n,i)),Promise.all(r).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.iridescence.isEnabled=!0,i.iridescence.intensity=t.iridescenceFactor??0,i.iridescence.indexOfRefraction=t.iridescenceIor??t.iridescenceIOR??1.3,i.iridescence.minimumThickness=t.iridescenceThicknessMinimum??100,i.iridescence.maximumThickness=t.iridescenceThicknessMaximum??400,t.iridescenceTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,(e=>{e.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=e}))),t.iridescenceThicknessTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,(e=>{e.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=e}))),Promise.all(s).then((()=>{}))}}qa.RegisterExtension(yo,(e=>new Mo(e)));const xo="KHR_materials_anisotropy";class Oo{constructor(e){this.name=xo,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(xo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadIridescencePropertiesAsync(s,n,i)),Promise.all(r).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=t.anisotropyStrength??0,i.anisotropy.angle=t.anisotropyRotation??0,t.anisotropyTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,(e=>{e.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=e}))),Promise.all(s).then((()=>{}))}}qa.RegisterExtension(xo,(e=>new Oo(e)));const Do="KHR_materials_emissive_strength";class Po{constructor(e){this.name=Do,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(Do)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then((()=>{this._loadEmissiveProperties(s,n,i)}))))}_loadEmissiveProperties(e,t,i){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);void 0!==t.emissiveStrength&&(i.emissiveIntensity=t.emissiveStrength)}}qa.RegisterExtension(Do,(e=>new Po(e)));const No="KHR_materials_sheen";class Lo{constructor(e){this.name=No,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(No)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadSheenPropertiesAsync(s,n,i)),Promise.all(r).then((()=>{}))}))}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,null!=t.sheenColorFactor?i.sheen.color=J.FromArray(t.sheenColorFactor):i.sheen.color=J.Black(),t.sheenColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,t.sheenColorTexture,(e=>{e.name=`${i.name} (Sheen Color)`,i.sheen.texture=e}))),void 0!==t.sheenRoughnessFactor?i.sheen.roughness=t.sheenRoughnessFactor:i.sheen.roughness=0,t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,(e=>{e.name=`${i.name} (Sheen Roughness)`,i.sheen.textureRoughness=e})))),i.sheen.albedoScaling=!0,i.sheen.useRoughnessFromMainTexture=!1,Promise.all(s).then((()=>{}))}}qa.RegisterExtension(No,(e=>new Lo(e)));const Fo="KHR_materials_specular";class wo{constructor(e){this.name=Fo,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Fo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadSpecularPropertiesAsync(s,n,i)),Promise.all(r).then((()=>{}))}))}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);const s=new Array;return void 0!==t.specularFactor&&(i.metallicF0Factor=t.specularFactor),void 0!==t.specularColorFactor&&(i.metallicReflectanceColor=J.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,(e=>{e.name=`${i.name} (Specular F0 Strength)`,i.metallicReflectanceTexture=e,i.useOnlyMetallicFromMetallicReflectanceTexture=!0})))),t.specularColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,(e=>{e.name=`${i.name} (Specular F0 Color)`,i.reflectanceTexture=e}))),Promise.all(s).then((()=>{}))}}qa.RegisterExtension(Fo,(e=>new wo(e)));const Bo="KHR_materials_ior";class Uo{constructor(e){this.name=Bo,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(Bo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadIorPropertiesAsync(s,n,i)),Promise.all(r).then((()=>{}))}))}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);return void 0!==t.ior?i.indexOfRefraction=t.ior:i.indexOfRefraction=Uo._DEFAULT_IOR,Promise.resolve()}}Uo._DEFAULT_IOR=1.5,qa.RegisterExtension(Bo,(e=>new Uo(e)));const ko="KHR_materials_variants";class Go{constructor(e){this.name=ko,this._loader=e,this.enabled=this._loader.isExtensionUsed(ko)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return Go.GetAvailableVariants(e)}static SelectVariant(e,t){const i=this._GetExtensionMetadata(e);if(!i)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${ko} extension`);const s=e=>{const t=i.variants[e];if(t)for(const e of t)e.mesh.material=e.material};if(t instanceof Array)for(const e of t)s(e);else s(t);i.lastSelected=t}selectVariant(e,t){Go.SelectVariant(e,t)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${ko} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){Go.Reset(e)}static GetLastSelectedVariant(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${ko} extension`);return t.lastSelected}getLastSelectedVariant(e){return Go.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){return e?._internalMetadata?.gltf?.[ko]||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}_loadMeshPrimitiveAsync(e,t,i,s,n,r){return qa.LoadExtensionAsync(e,n,this.name,((a,o)=>{const l=new Array;return l.push(this._loader._loadMeshPrimitiveAsync(e,t,i,s,n,(t=>{if(r(t),t instanceof gs){const i=qa._GetDrawMode(e,n.mode),s=this._loader.rootBabylonMesh,r=s?s._internalMetadata=s._internalMetadata||{}:{},h=r.gltf=r.gltf||{},c=h[ko]=h[ko]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:t,material:t.material});for(let e=0;e<o.mappings.length;++e){const n=o.mappings[e],r=Ka.Get(`${a}/mappings/${e}/material`,this._loader.gltf.materials,n.material);l.push(this._loader._loadMaterialAsync(`#/materials/${n.material}`,r,t,i,(e=>{for(let i=0;i<n.variants.length;++i){const r=n.variants[i],a=Ka.Get(`/extensions/${ko}/variants/${r}`,this._variants,r);c.variants[a.name]=c.variants[a.name]||[],c.variants[a.name].push({mesh:t,material:e}),t.onClonedObservable.add((e=>{const i=e;let n=null,r=i;do{if(r=r.parent,!r)return;n=Go._GetExtensionMetadata(r)}while(null===n);if(s&&n===Go._GetExtensionMetadata(s)){r._internalMetadata={};for(const e in s._internalMetadata)r._internalMetadata[e]=s._internalMetadata[e];r._internalMetadata.gltf=[];for(const e in s._internalMetadata.gltf)r._internalMetadata.gltf[e]=s._internalMetadata.gltf[e];r._internalMetadata.gltf[ko]={lastSelected:null,original:[],variants:{}};for(const e of n.original)r._internalMetadata.gltf[ko].original.push({mesh:e.mesh,material:e.material});for(const e in n.variants)if(Object.prototype.hasOwnProperty.call(n.variants,e)){r._internalMetadata.gltf[ko].variants[e]=[];for(const t of n.variants[e])r._internalMetadata.gltf[ko].variants[e].push({mesh:t.mesh,material:t.material})}n=r._internalMetadata.gltf[ko]}for(const e of n.original)e.mesh===t&&(e.mesh=i);for(const e of n.variants[a.name])e.mesh===t&&(e.mesh=i)}))}})))}}}))),Promise.all(l).then((([e])=>e))}))}}qa.RegisterExtension(ko,(e=>new Go(e)));class Vo{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:tt.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...Vo._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new g,this._scene.onDisposeObservable.addOnce((()=>{this.dispose()})),this._parseScene(),this._setupRenderTargets()}updateOptions(e){if(!Object.keys(e).filter((t=>this._options[t]!==e[t])).length)return;const t={...this._options,...e},i=this._options;this._options=t,t.renderSize===i.renderSize&&t.renderTargetTextureType===i.renderTargetTextureType&&t.generateMipmaps===i.generateMipmaps&&this._opaqueRenderTarget?(this._opaqueRenderTarget.samples=t.samples,this._opaqueRenderTarget.lodGenerationScale=t.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=t.lodGenerationOffset):this._setupRenderTargets()}getOpaqueTarget(){return this._opaqueRenderTarget}_shouldRenderAsTransmission(e){return!!e&&!!(e instanceof Br&&e.subSurface.isRefractionEnabled)}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),Qt.SetImmediate((()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,-1===this._transparentMeshesCache.indexOf(e)&&this._transparentMeshesCache.push(e)):-1===this._opaqueMeshesCache.indexOf(e)&&this._opaqueMeshesCache.push(e)}))}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);-1!==t&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),-1!==t&&this._opaqueMeshesCache.splice(t,1)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){const t=this._transparentMeshesCache.indexOf(e),i=this._opaqueMeshesCache.indexOf(e);this._shouldRenderAsTransmission(e.material)?(e.material instanceof Br&&(e.material.subSurface.refractionTexture=this._opaqueRenderTarget),-1!==i?(this._opaqueMeshesCache.splice(i,1),this._transparentMeshesCache.push(e)):-1===t&&this._transparentMeshesCache.push(e)):-1!==t?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):-1===i&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){return null!==this._opaqueRenderTarget?.getInternalTexture()}_setupRenderTargets(){let e,t;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new Kn("opaqueSceneTexture",this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),this._opaqueRenderTarget.ignoreCameraViewport=!0,this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.clearColor=this._options.clearColor?.clone()??this._scene.clearColor.clone(),this._opaqueRenderTarget.gammaSpace=!1,this._opaqueRenderTarget.lodGenerationScale=this._options.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=this._options.lodGenerationOffset,this._opaqueRenderTarget.samples=this._options.samples,this._opaqueRenderTarget.renderSprites=!0,this._opaqueRenderTarget.renderParticles=!0,this._opaqueRenderTarget.onBeforeBindObservable.add((i=>{t=this._scene.environmentIntensity,this._scene.environmentIntensity=1,e=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?i.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(i.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0})),this._opaqueRenderTarget.onAfterUnbindObservable.add((()=>{this._scene.environmentIntensity=t,this._scene.imageProcessingConfiguration._applyByPostProcess=e})),this._transparentMeshesCache.forEach((e=>{this._shouldRenderAsTransmission(e.material)&&(e.material.refractionTexture=this._opaqueRenderTarget)}))}dispose(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]}}const Xo="KHR_materials_transmission";class Ho{constructor(e){this.name=Xo,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(Xo),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadTransparentPropertiesAsync(s,t,i,n)),Promise.all(r).then((()=>{}))}))}_loadTransparentPropertiesAsync(e,t,i,s){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);const n=i;if(n.subSurface.isRefractionEnabled=!0,n.subSurface.volumeIndexOfRefraction=1,n.subSurface.useAlbedoToTintRefraction=!0,void 0===s.transmissionFactor)return n.subSurface.refractionIntensity=0,n.subSurface.isRefractionEnabled=!1,Promise.resolve();{n.subSurface.refractionIntensity=s.transmissionFactor;const e=n.getScene();n.subSurface.refractionIntensity&&!e._transmissionHelper?new Vo({},n.getScene()):n.subSurface.refractionIntensity&&!e._transmissionHelper?._isRenderTargetValid()&&e._transmissionHelper?._setupRenderTargets()}return n.subSurface.minimumThickness=0,n.subSurface.maximumThickness=0,s.transmissionTexture?(s.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,s.transmissionTexture,void 0).then((e=>{n.subSurface.refractionIntensityTexture=e,n.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}qa.RegisterExtension(Xo,(e=>new Ho(e)));const zo="KHR_materials_diffuse_transmission";class Wo{constructor(e){this.name=zo,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(zo),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadTranslucentPropertiesAsync(s,t,i,n)),Promise.all(r).then((()=>{}))}))}_loadTranslucentPropertiesAsync(e,t,i,s){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);const n=i;if(n.subSurface.isTranslucencyEnabled=!0,n.subSurface.volumeIndexOfRefraction=1,n.subSurface.minimumThickness=0,n.subSurface.maximumThickness=0,n.subSurface.useAlbedoToTintTranslucency=!1,void 0===s.diffuseTransmissionFactor)return n.subSurface.translucencyIntensity=0,n.subSurface.isTranslucencyEnabled=!1,Promise.resolve();n.subSurface.translucencyIntensity=s.diffuseTransmissionFactor;const r=new Array;return n.subSurface.useGltfStyleTextures=!0,s.diffuseTransmissionTexture&&(s.diffuseTransmissionTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,s.diffuseTransmissionTexture).then((e=>{n.subSurface.translucencyIntensityTexture=e})))),void 0!==s.diffuseTransmissionColorFactor?n.subSurface.translucencyColor=J.FromArray(s.diffuseTransmissionColorFactor):n.subSurface.translucencyColor=J.White(),s.diffuseTransmissionColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,s.diffuseTransmissionColorTexture).then((e=>{n.subSurface.translucencyColorTexture=e}))),Promise.all(r).then((()=>{}))}}qa.RegisterExtension(zo,(e=>new Wo(e)));const Yo="KHR_materials_volume";class Ko{constructor(e){this.name=Yo,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(Yo),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadVolumePropertiesAsync(s,t,i,n)),Promise.all(r).then((()=>{}))}))}_loadVolumePropertiesAsync(e,t,i,s){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!s.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const n=void 0!==s.attenuationDistance?s.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=n,void 0!==s.attenuationColor&&3==s.attenuationColor.length&&i.subSurface.tintColor.copyFromFloats(s.attenuationColor[0],s.attenuationColor[1],s.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=s.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,s.thicknessTexture?(s.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,s.thicknessTexture).then((e=>{i.subSurface.thicknessTexture=e,i.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}qa.RegisterExtension(Yo,(e=>new Ko(e)));const qo="KHR_materials_dispersion";class Qo{constructor(e){this.name=qo,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(qo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadDispersionPropertiesAsync(s,t,i,n)),Promise.all(r).then((()=>{}))}))}_loadDispersionPropertiesAsync(e,t,i,s){if(!(i instanceof Br))throw new Error(`${e}: Material type not supported`);return i.subSurface.isRefractionEnabled&&s.dispersion?(i.subSurface.isDispersionEnabled=!0,i.subSurface.dispersion=s.dispersion,Promise.resolve()):Promise.resolve()}}qa.RegisterExtension(qo,(e=>new Qo(e)));const jo="KHR_mesh_quantization";class Zo{constructor(e){this.name=jo,this.enabled=e.isExtensionUsed(jo)}dispose(){}}qa.RegisterExtension(jo,(e=>new Zo(e)));const $o="KHR_texture_basisu";class Jo{constructor(e){this.name=$o,this._loader=e,this.enabled=e.isExtensionUsed($o)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>{const r=null==t.sampler?qa.DefaultSampler:Ka.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),a=Ka.Get(`${s}/source`,this._loader.gltf.images,n.source);return this._loader._createTextureAsync(e,r,a,(e=>{i(e)}),t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}}qa.RegisterExtension($o,(e=>new Jo(e)));const el="KHR_texture_transform";class tl{constructor(e){this.name=el,this._loader=e,this.enabled=this._loader.isExtensionUsed(el)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((s,n)=>this._loader.loadTextureInfoAsync(e,t,(e=>{if(!(e instanceof wn))throw new Error(`${s}: Texture type not supported`);n.offset&&(e.uOffset=n.offset[0],e.vOffset=n.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,n.rotation&&(e.wAng=-n.rotation),n.scale&&(e.uScale=n.scale[0],e.vScale=n.scale[1]),null!=n.texCoord&&(e.coordinatesIndex=n.texCoord),i(e)}))))}}qa.RegisterExtension(el,(e=>new tl(e)));const il="KHR_xmp_json_ld";class sl{constructor(e){this.name=il,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(il)}dispose(){this._loader=null}onLoading(){if(null===this._loader.rootBabylonMesh)return;const e=this._loader.gltf.extensions?.KHR_xmp_json_ld,t=this._loader.gltf.asset?.extensions?.KHR_xmp_json_ld;if(e&&t){const i=+t.packet;e.packets&&i<e.packets.length&&(this._loader.rootBabylonMesh.metadata=this._loader.rootBabylonMesh.metadata||{},this._loader.rootBabylonMesh.metadata.xmp=e.packets[i])}}}function nl(e,t,i,s){return J.FromArray(t,i).scale(s)}function rl(e,t,i,s){return t[i]*s}function al(e,t,i,s){return-t[i]*s}function ol(e,t,i,s){return t[i+1]*s}function ll(e,t,i,s){return t[i]*s*2}function hl(e){return{scale:[new ul(Ls.ANIMATIONTYPE_FLOAT,`${e}.uScale`,rl,(()=>2)),new ul(Ls.ANIMATIONTYPE_FLOAT,`${e}.vScale`,ol,(()=>2))],offset:[new ul(Ls.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,rl,(()=>2)),new ul(Ls.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,ol,(()=>2))],rotation:[new ul(Ls.ANIMATIONTYPE_FLOAT,`${e}.wAng`,al,(()=>1))]}}qa.RegisterExtension(il,(e=>new sl(e)));class cl extends Ha{buildAnimations(e,t,i,s,n){n(e._babylonCamera,this._buildAnimation(t,i,s))}}class ul extends Ha{buildAnimations(e,t,i,s,n){for(const r in e._data)n(e._data[r].babylonMaterial,this._buildAnimation(t,i,s))}}class dl extends Ha{buildAnimations(e,t,i,s,n){n(e._babylonLight,this._buildAnimation(t,i,s))}}const _l={__array__:{__target__:!0,...Wa}},fl={__array__:{__target__:!0,orthographic:{xmag:[new cl(Ls.ANIMATIONTYPE_FLOAT,"orthoLeft",al,(()=>1)),new cl(Ls.ANIMATIONTYPE_FLOAT,"orthoRight",ol,(()=>1))],ymag:[new cl(Ls.ANIMATIONTYPE_FLOAT,"orthoBottom",al,(()=>1)),new cl(Ls.ANIMATIONTYPE_FLOAT,"orthoTop",ol,(()=>1))],zfar:[new cl(Ls.ANIMATIONTYPE_FLOAT,"maxZ",rl,(()=>1))],znear:[new cl(Ls.ANIMATIONTYPE_FLOAT,"minZ",rl,(()=>1))]},perspective:{yfov:[new cl(Ls.ANIMATIONTYPE_FLOAT,"fov",rl,(()=>1))],zfar:[new cl(Ls.ANIMATIONTYPE_FLOAT,"maxZ",rl,(()=>1))],znear:[new cl(Ls.ANIMATIONTYPE_FLOAT,"minZ",rl,(()=>1))]}}},ml={nodes:_l,materials:{__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new ul(Ls.ANIMATIONTYPE_COLOR3,"albedoColor",nl,(()=>4)),new ul(Ls.ANIMATIONTYPE_FLOAT,"alpha",(function(e,t,i,s){return t[i+3]*s}),(()=>4))],metallicFactor:[new ul(Ls.ANIMATIONTYPE_FLOAT,"metallic",rl,(()=>1))],roughnessFactor:[new ul(Ls.ANIMATIONTYPE_FLOAT,"roughness",rl,(()=>1))],baseColorTexture:{extensions:{KHR_texture_transform:hl("albedoTexture")}},metallicRoughnessTexture:{extensions:{KHR_texture_transform:hl("metallicTexture")}}},emissiveFactor:[new ul(Ls.ANIMATIONTYPE_COLOR3,"emissiveColor",nl,(()=>3))],normalTexture:{scale:[new ul(Ls.ANIMATIONTYPE_FLOAT,"bumpTexture.level",rl,(()=>1))],extensions:{KHR_texture_transform:hl("bumpTexture")}},occlusionTexture:{strength:[new ul(Ls.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",rl,(()=>1))],extensions:{KHR_texture_transform:hl("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:hl("emissiveTexture")}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:[new ul(Ls.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",rl,(()=>1))],anisotropyRotation:[new ul(Ls.ANIMATIONTYPE_FLOAT,"anisotropy.angle",rl,(()=>1))],anisotropyTexture:{extensions:{KHR_texture_transform:hl("anisotropy.texture")}}},KHR_materials_clearcoat:{clearcoatFactor:[new ul(Ls.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",rl,(()=>1))],clearcoatRoughnessFactor:[new ul(Ls.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",rl,(()=>1))],clearcoatTexture:{extensions:{KHR_texture_transform:hl("clearCoat.texture")}},clearcoatNormalTexture:{scale:[new ul(Ls.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",rl,(()=>1))],extensions:{KHR_texture_transform:hl("clearCoat.bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:hl("clearCoat.textureRoughness")}}},KHR_materials_dispersion:{dispersion:[new ul(Ls.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",rl,(()=>1))]},KHR_materials_emissive_strength:{emissiveStrength:[new ul(Ls.ANIMATIONTYPE_FLOAT,"emissiveIntensity",rl,(()=>1))]},KHR_materials_ior:{ior:[new ul(Ls.ANIMATIONTYPE_FLOAT,"indexOfRefraction",rl,(()=>1))]},KHR_materials_iridescence:{iridescenceFactor:[new ul(Ls.ANIMATIONTYPE_FLOAT,"iridescence.intensity",rl,(()=>1))],iridescenceIor:[new ul(Ls.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",rl,(()=>1))],iridescenceThicknessMinimum:[new ul(Ls.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",rl,(()=>1))],iridescenceThicknessMaximum:[new ul(Ls.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",rl,(()=>1))],iridescenceTexture:{extensions:{KHR_texture_transform:hl("iridescence.texture")}},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:hl("iridescence.thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:[new ul(Ls.ANIMATIONTYPE_COLOR3,"sheen.color",nl,(()=>3))],sheenRoughnessFactor:[new ul(Ls.ANIMATIONTYPE_FLOAT,"sheen.roughness",rl,(()=>1))],sheenColorTexture:{extensions:{KHR_texture_transform:hl("sheen.texture")}},sheenRoughnessTexture:{extensions:{KHR_texture_transform:hl("sheen.textureRoughness")}}},KHR_materials_specular:{specularFactor:[new ul(Ls.ANIMATIONTYPE_FLOAT,"metallicF0Factor",rl,(()=>1))],specularColorFactor:[new ul(Ls.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",nl,(()=>3))],specularTexture:{extensions:{KHR_texture_transform:hl("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:hl("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:[new ul(Ls.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",rl,(()=>1))],transmissionTexture:{extensions:{KHR_texture_transform:hl("subSurface.refractionIntensityTexture")}}},KHR_materials_volume:{attenuationColor:[new ul(Ls.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",nl,(()=>3))],attenuationDistance:[new ul(Ls.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",rl,(()=>1))],thicknessFactor:[new ul(Ls.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",rl,(()=>1))],thicknessTexture:{extensions:{KHR_texture_transform:hl("subSurface.thicknessTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:[new ul(Ls.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",rl,(()=>1))],diffuseTransmissionTexture:{extensions:{KHR_texture_transform:hl("subSurface.translucencyIntensityTexture")}},diffuseTransmissionColorFactor:[new ul(Ls.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",nl,(()=>3))],diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:hl("subSurface.translucencyColorTexture")}}}}}},cameras:fl,extensions:{KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new dl(Ls.ANIMATIONTYPE_COLOR3,"diffuse",nl,(()=>3))],intensity:[new dl(Ls.ANIMATIONTYPE_FLOAT,"intensity",rl,(()=>1))],range:[new dl(Ls.ANIMATIONTYPE_FLOAT,"range",rl,(()=>1))],spot:{innerConeAngle:[new dl(Ls.ANIMATIONTYPE_FLOAT,"innerAngle",ll,(()=>1))],outerConeAngle:[new dl(Ls.ANIMATIONTYPE_FLOAT,"angle",ll,(()=>1))]}}}}}};class pl{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t,i=this._gltf,s=this._infoTree;if(!e.startsWith("/"))throw new Error("Path must start with a /");const n=e.split("/");n.shift();for(const r of n){if(s.__array__)s=s.__array__;else if(s=s[r],!s)throw new Error(`Path ${e} is invalid`);if(void 0===i)throw new Error(`Path ${e} is invalid`);i=i[r],s.__target__&&(t=i)}return{object:t,info:s}}}const gl="KHR_animation_pointer";class El extends pl{constructor(e){super(e,ml)}}class Tl{constructor(e){this.name=gl,this._loader=e,this._pathToObjectConverter=new El(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(gl)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,i,s,n){const r=s.target.extensions?.KHR_animation_pointer;if(!r||!this._pathToObjectConverter)return null;"pointer"!==s.target.path&&ce.Warn(`${e}/target/path: Value (${s.target.path}) must be (pointer) when using the ${this.name} extension`),null!=s.target.node&&ce.Warn(`${e}/target/node: Value (${s.target.node}) must not be present when using the ${this.name} extension`);const a=`${e}/extensions/${this.name}`,o=r.pointer;if(!o)throw new Error(`${a}: Pointer is missing`);try{const r=this._pathToObjectConverter.convert(o);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,r,n)}catch(e){return ce.Warn(`${a}/pointer: Invalid pointer (${o}) skipped`),null}}}qa.RegisterExtension(gl,(e=>new Tl(e)));class Al{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new Al(this.frame,this.action,this.onlyOnce)}}class Rl{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if(Ui.audioEngine?.audioContext&&(this.isPlaying||this.isPaused)){const e=this.isPaused?0:Ui.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;const t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,s=null,n){if(this.autoplay=!1,this._loop=!1,this.useCustomAttenuation=!1,this.isPlaying=!1,this.isPaused=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this.metadata=null,this.onEndedObservable=new g,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=B.Zero(),this._localDirection=new B(1,0,0),this._volume=1,this._isReadyToPlay=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=e,i=i||M.LastCreatedScene)if(this._scene=i,Rl._SceneComponentInitialization(i),this._readyToPlayCallback=s,this._customAttenuationFunction=(e,t,i,s,n)=>t<i?e*(1-t/i):0,n&&(this.autoplay=n.autoplay||!1,this._loop=n.loop||!1,void 0!==n.volume&&(this._volume=n.volume),this._spatialSound=n.spatialSound??!1,this.maxDistance=n.maxDistance??100,this.useCustomAttenuation=n.useCustomAttenuation??!1,this.rolloffFactor=n.rolloffFactor||1,this.refDistance=n.refDistance||1,this.distanceModel=n.distanceModel||"linear",this._playbackRate=n.playbackRate||1,this._streaming=n.streaming??!1,this._length=n.length,this._offset=n.offset),Ui.audioEngine?.canUseWebAudio&&Ui.audioEngine.audioContext){this._soundGain=Ui.audioEngine.audioContext.createGain(),this._soundGain.gain.value=this._volume,this._inputAudioNode=this._soundGain,this._outputAudioNode=this._soundGain,this._spatialSound&&this._createSpatialParameters(),this._scene.mainSoundTrack.addSound(this);let e=!0;if(t)try{"string"==typeof t?(this._urlType="String",this._url=t):t instanceof ArrayBuffer?this._urlType="ArrayBuffer":t instanceof HTMLMediaElement?this._urlType="MediaElement":t instanceof MediaStream?this._urlType="MediaStream":t instanceof AudioBuffer?this._urlType="AudioBuffer":Array.isArray(t)&&(this._urlType="Array");let i=[],s=!1;switch(this._urlType){case"MediaElement":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=Ui.audioEngine.audioContext.createMediaElementSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"MediaStream":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=Ui.audioEngine.audioContext.createMediaStreamSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"ArrayBuffer":t.byteLength>0&&(s=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e<i.length;e++){const t=i[e];if(s=n&&n.skipCodecCheck||-1!==t.indexOf(".mp3",t.length-4)&&Ui.audioEngine.isMP3supported||-1!==t.indexOf(".ogg",t.length-4)&&Ui.audioEngine.isOGGsupported||-1!==t.indexOf(".wav",t.length-4)||-1!==t.indexOf(".m4a",t.length-4)||-1!==t.indexOf(".mp4",t.length-4)||-1!==t.indexOf("blob:"),s){this._streaming?(this._htmlAudioElement=new Audio(t),this._htmlAudioElement.controls=!1,this._htmlAudioElement.loop=this.loop,Qt.SetCorsBehavior(t,this._htmlAudioElement),this._htmlAudioElement.preload="auto",this._htmlAudioElement.addEventListener("canplaythrough",(()=>{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()})),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,(e=>{this._soundLoaded(e)}),void 0,!0,!0,(e=>{e&&ce.Error("XHR "+e.status+" error on: "+t+"."),ce.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}));break}}break;default:e=!1}e?s||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)):ce.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){ce.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),Ui.audioEngine&&!Ui.audioEngine.WarnedWebAudioUnsupported&&(ce.Error("Web Audio is not supported by your browser."),Ui.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){Ui.audioEngine?.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,-1===this.soundTrackId?this._scene.mainSoundTrack.removeSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].removeSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){Ui.audioEngine?.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){Ui.audioEngine?.audioContext&&Ui.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{ce.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){Ui.audioEngine?.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){e&&(this.loop=e.loop??this.loop,this.maxDistance=e.maxDistance??this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation??this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor??this.rolloffFactor,this.refDistance=e.refDistance??this.refDistance,this.distanceModel=e.distanceModel??this.distanceModel,this._playbackRate=e.playbackRate??this._playbackRate,this._length=e.length??void 0,this.spatialSound=e.spatialSound??this._spatialSound,this._setOffset(e.offset??void 0),this.setVolume(e.volume??this._volume),this._updateSpatialParameters(),this.isPlaying&&(this._streaming&&this._htmlAudioElement?(this._htmlAudioElement.playbackRate=this._playbackRate,this._htmlAudioElement.loop!==this.loop&&(this._htmlAudioElement.loop=this.loop)):this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.loop!==this.loop&&(this._soundSource.loop=this.loop),void 0!==this._offset&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),void 0!==this._length&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(0|this._offset)+this._length))))}_createSpatialParameters(){Ui.audioEngine?.canUseWebAudio&&Ui.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??Ui.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){this._spatialSound&&(this._inputAudioNode=this._soundGain,this._soundPanner?.disconnect(),this._soundPanner=null,this._spatialSound=!1)}_updateSpatialParameters(){this._spatialSound&&(this._soundPanner?this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){Ui.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){Ui.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){t<e?ce.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."):(this._coneInnerAngle=e,this._coneOuterAngle=t,this._coneOuterGain=i,this._isDirectional=!0,this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length)))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!=this._coneInnerAngle){if(this._coneOuterAngle<e)return void ce.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneInnerAngle=e,Ui.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle)}}get directionalConeOuterAngle(){return this._coneOuterAngle}set directionalConeOuterAngle(e){if(e!=this._coneOuterAngle){if(e<this._coneInnerAngle)return void ce.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneOuterAngle=e,Ui.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneOuterAngle=this._coneOuterAngle)}}setPosition(e){e.equals(this._position)||(this._position.copyFrom(e),Ui.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&!isNaN(this._position.x)&&!isNaN(this._position.y)&&!isNaN(this._position.z)&&(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z))}setLocalDirectionToMesh(e){this._localDirection=e,Ui.audioEngine?.canUseWebAudio&&this._connectedTransformNode&&this.isPlaying&&this._updateDirection()}_updateDirection(){if(!this._connectedTransformNode||!this._soundPanner)return;const e=this._connectedTransformNode.getWorldMatrix(),t=B.TransformNormal(this._localDirection,e);t.normalize(),this._soundPanner.orientationX.value=t.x,this._soundPanner.orientationY.value=t.y,this._soundPanner.orientationZ.value=t.z}updateDistanceFromListener(){if(Ui.audioEngine?.canUseWebAudio&&this._connectedTransformNode&&this.useCustomAttenuation&&this._soundGain&&this._scene.activeCamera){const e=this._scene.audioListenerPositionProvider?this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length():this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);this._soundGain.gain.value=this._customAttenuationFunction(this._volume,e,this.maxDistance,this.refDistance,this.rolloffFactor)}}setAttenuationFunction(e){this._customAttenuationFunction=e}play(e,t,i){if(this._isReadyToPlay&&this._scene.audioEnabled&&Ui.audioEngine?.audioContext)try{this._clearTimeoutsAndObservers();let s=e?Ui.audioEngine?.audioContext.currentTime+e:Ui.audioEngine?.audioContext.currentTime;if(this._soundSource&&this._streamingSource||this._spatialSound&&this._soundPanner&&(isNaN(this._position.x)||isNaN(this._position.y)||isNaN(this._position.z)||(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z),this._isDirectional&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle,this._soundPanner.coneOuterAngle=this._coneOuterAngle,this._soundPanner.coneOuterGain=this._coneOuterGain,this._connectedTransformNode?this._updateDirection():this._soundPanner.setOrientation(this._localDirection.x,this._localDirection.y,this._localDirection.z))),this._streaming){if(this._streamingSource||(this._streamingSource=Ui.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),this._htmlAudioElement.onended=()=>{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const e=()=>{if(Ui.audioEngine?.unlocked){const t=this._htmlAudioElement.play();void 0!==t&&t.catch((()=>{Ui.audioEngine?.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Ui.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Ui.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const n=()=>{if(Ui.audioEngine?.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){const e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=Ui.audioEngine?.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,void 0!==t&&(this._soundSource.loopStart=t),void 0!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},s=e?Ui.audioEngine?.audioContext.currentTime+e:Ui.audioEngine.audioContext.currentTime;const n=((this.isPaused?this.currentTime:0)+(this._offset??0))%this._soundSource.buffer.duration;this._soundSource.start(s,n,this.loop?void 0:i)}}};"suspended"===Ui.audioEngine?.audioContext.state?this._tryToPlayTimeout=setTimeout((()=>{"suspended"===Ui.audioEngine?.audioContext.state?(Ui.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Ui.audioEngine.onAudioUnlockedObservable.addOnce((()=>{n()})))):n()}),500):n()}this._startTime=s,this.isPlaying=!0,this.isPaused=!1}catch(e){ce.Error("Error while trying to play audio: "+this.name+", "+e.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){if(this.isPlaying)if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if(Ui.audioEngine?.audioContext&&this._soundSource){const t=e?Ui.audioEngine.audioContext.currentTime+e:void 0;this._soundSource.onended=()=>{this.isPlaying=!1,this.isPaused=!1,this._startTime=0,this._currentTime=0,this._soundSource&&(this._soundSource.onended=()=>{}),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1;else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):Ui.audioEngine?.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=Ui.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){Ui.audioEngine?.canUseWebAudio&&this._soundGain&&(t&&Ui.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(Ui.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,Ui.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,Ui.audioEngine.audioContext.currentTime+t)):this._soundGain.gain.value=e),this._volume=e}setPlaybackRate(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))}getPlaybackRate(){return this._playbackRate}getVolume(){return this._volume}attachToMesh(e){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=e,this._spatialSound||(this._spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=e=>this._onRegisterAfterWorldMatrixUpdate(e),this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)}detachFromMesh(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)}_onRegisterAfterWorldMatrixUpdate(e){if(e.getBoundingInfo){const t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);Ui.audioEngine?.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new Rl(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){const e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,s){const n=e.name;let r;r=e.url?i+e.url:i+n;const a={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let o;if(s){const e=()=>{s._isReadyToPlay?(o._audioBuffer=s.getAudioBuffer(),o._isReadyToPlay=!0,o.autoplay&&o.play(0,o._offset,o._length)):setTimeout(e,300)};o=new Rl(n,new ArrayBuffer(0),t,null,a),e()}else o=new Rl(n,r,t,(()=>{t.removePendingData(o)}),a),t.addPendingData(o);if(e.position){const t=B.FromArray(e.position);o.setPosition(t)}if(e.isDirectional&&(o.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=B.FromArray(e.localDirectionToMesh);o.setLocalDirectionToMesh(t)}if(e.connectedMeshId){const i=t.getMeshById(e.connectedMeshId);i&&o.attachToMesh(i)}return e.metadata&&(o.metadata=e.metadata),o}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(Ui.audioEngine?.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}Rl._SceneComponentInitialization=e=>{throw W("AudioSceneComponent")},C("BABYLON.Sound",Rl);class vl{constructor(e,t,i){if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==i.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=i;let s=0;for(const e of i)s+=e;const n=s>0?1/s:0;for(let e=0;e<this._weights.length;e++)this._weights[e]*=n;this._sounds=t;for(const e of this._sounds)e.onEndedObservable.add((()=>{this._onended()}))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAngle<e)return void ce.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneInnerAngle=e;for(const t of this._sounds)t.directionalConeInnerAngle=e}}get directionalConeOuterAngle(){return this._coneOuterAngle}set directionalConeOuterAngle(e){if(e!==this._coneOuterAngle){if(e<this._coneInnerAngle)return void ce.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneOuterAngle=e;for(const t of this._sounds)t.directionalConeOuterAngle=e}}get volume(){return this._volume}set volume(e){if(e!==this._volume)for(const t of this._sounds)t.setVolume(e)}_onended(){void 0!==this._currentIndex&&(this._sounds[this._currentIndex].autoplay=!1),this.loop&&this.isPlaying?this.play():this.isPlaying=!1}pause(){this.isPaused=!0,void 0!==this._currentIndex&&this._sounds[this._currentIndex].pause()}stop(){this.isPlaying=!1,void 0!==this._currentIndex&&this._sounds[this._currentIndex].stop()}play(e){if(!this.isPaused){this.stop();const e=Math.random();let t=0;for(let i=0;i<this._weights.length;i++)if(t+=this._weights[i],e<=t){this._currentIndex=i;break}}const t=this._sounds[this._currentIndex];t.isReady()?t.play(0,this.isPaused?void 0:e):t.autoplay=!0,this.isPlaying=!0,this.isPaused=!1}}const Il="MSFT_audio_emitter";class Sl{constructor(e){this.name=Il,this._loader=e,this.enabled=this._loader.isExtensionUsed(Il)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,Ka.Assign(this._clips),Ka.Assign(this._emitters)}}loadSceneAsync(e,t){return qa.LoadExtensionAsync(e,t,this.name,((i,s)=>{const n=new Array;n.push(this._loader.loadSceneAsync(e,t));for(const e of s.emitters){const t=Ka.Get(`${i}/emitters`,this._emitters,e);if(null!=t.refDistance||null!=t.maxDistance||null!=t.rolloffFactor||null!=t.distanceModel||null!=t.innerAngle||null!=t.outerAngle)throw new Error(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);n.push(this._loadEmitterAsync(`${i}/emitters/${t.index}`,t))}return Promise.all(n).then((()=>{}))}))}loadNodeAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((e,s)=>{const n=new Array;return this._loader.loadNodeAsync(e,t,(t=>{for(const i of s.emitters){const s=Ka.Get(`${e}/emitters`,this._emitters,i);n.push(this._loadEmitterAsync(`${e}/emitters/${s.index}`,s).then((()=>{for(const e of s._babylonSounds)e.attachToMesh(t),null==s.innerAngle&&null==s.outerAngle||(e.setLocalDirectionToMesh(B.Forward()),e.setDirectionalCone(2*Qt.ToDegrees(null==s.innerAngle?Math.PI:s.innerAngle),2*Qt.ToDegrees(null==s.outerAngle?Math.PI:s.outerAngle),0))})))}i(t)})).then((e=>Promise.all(n).then((()=>e))))}))}loadAnimationAsync(e,t){return qa.LoadExtensionAsync(e,t,this.name,((i,s)=>this._loader.loadAnimationAsync(e,t).then((n=>{const r=new Array;Ka.Assign(s.events);for(const a of s.events)r.push(this._loadAnimationEventAsync(`${i}/events/${a.index}`,e,t,a,n));return Promise.all(r).then((()=>n))}))))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const s=Ka.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${s.index}`,s)}return t._objectURL=i.then((e=>URL.createObjectURL(new Blob([e],{type:t.mimeType})))),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){const e=new Array,i=t.name||`emitter${t.index}`,s={loop:!1,autoplay:!1,volume:null==t.volume?1:t.volume};for(let n=0;n<t.clips.length;n++){const r=`/extensions/${this.name}/clips`,a=Ka.Get(r,this._clips,t.clips[n].clip);e.push(this._loadClipAsync(`${r}/${t.clips[n].clip}`,a).then((e=>{const r=t._babylonSounds[n]=new Rl(i,e,this._loader.babylonScene,null,s);r.refDistance=t.refDistance||1,r.maxDistance=t.maxDistance||256,r.rolloffFactor=t.rolloffFactor||1,r.distanceModel=t.distanceModel||"exponential"})))}const n=Promise.all(e).then((()=>{const e=t.clips.map((e=>e.weight||1)),i=new vl(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(i.directionalConeInnerAngle=2*Qt.ToDegrees(t.innerAngle)),t.outerAngle&&(i.directionalConeOuterAngle=2*Qt.ToDegrees(t.outerAngle)),t.volume&&(i.volume=t.volume),t._babylonData.sound=i}));t._babylonData={loaded:n}}return t._babylonData.loaded}_getEventAction(e,t,i,s,n){switch(i){case"play":return e=>{const i=(n||0)+(e-s);t.play(i)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${i}`)}}_loadAnimationEventAsync(e,t,i,s,n){if(0==n.targetedAnimations.length)return Promise.resolve();const r=n.targetedAnimations[0],a=s.emitter,o=Ka.Get(`/extensions/${this.name}/emitters`,this._emitters,a);return this._loadEmitterAsync(e,o).then((()=>{const t=o._babylonData.sound;if(t){const i=new Al(s.time,this._getEventAction(e,t,s.action,s.time,s.startOffset));r.animation.addEvent(i),n.onAnimationGroupEndObservable.add((()=>{t.stop()})),n.onAnimationGroupPauseObservable.add((()=>{t.pause()}))}}))}}qa.RegisterExtension(Il,(e=>new Sl(e)));const Cl="MSFT_lod";class bl{constructor(e){this.name=Cl,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new g,this.onMaterialLODsLoadedObservable=new g,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.enabled=this._loader.isExtensionUsed(Cl)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e<this._nodePromiseLODs.length;e++){const t=Promise.all(this._nodePromiseLODs[e]).then((()=>{0!==e&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())}));this._loader._completePromises.push(t)}for(let e=0;e<this._materialPromiseLODs.length;e++){const t=Promise.all(this._materialPromiseLODs[e]).then((()=>{0!==e&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())}));this._loader._completePromises.push(t)}}loadSceneAsync(e,t){const i=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),i}loadNodeAsync(e,t,i){return qa.LoadExtensionAsync(e,t,this.name,((e,s)=>{let n;const r=this._getLODs(e,t,this._loader.gltf.nodes,s.ids);this._loader.logOpen(`${e}`);for(let e=0;e<r.length;e++){const t=r[e];0!==e&&(this._nodeIndexLOD=e,this._nodeSignalLODs[e]=this._nodeSignalLODs[e]||new Jr);const s=e=>{i(e),e.setEnabled(!1)},a=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,s).then((t=>{if(0!==e){const t=r[e-1];t._babylonTransformNode&&(this._disposeTransformNode(t._babylonTransformNode),delete t._babylonTransformNode)}return t.setEnabled(!0),t}));this._nodePromiseLODs[e]=this._nodePromiseLODs[e]||[],0===e?n=a:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(a))}return this._loader.logClose(),n}))}_loadMaterialAsync(e,t,i,s,n){return this._nodeIndexLOD?null:qa.LoadExtensionAsync(e,t,this.name,((e,r)=>{let a;const o=this._getLODs(e,t,this._loader.gltf.materials,r.ids);this._loader.logOpen(`${e}`);for(let e=0;e<o.length;e++){const t=o[e];0!==e&&(this._materialIndexLOD=e);const r=this._loader._loadMaterialAsync(`/materials/${t.index}`,t,i,s,(t=>{0===e&&n(t)})).then((t=>{if(0!==e){n(t);const i=o[e-1]._data;i[s]&&(this._disposeMaterials([i[s].babylonMaterial]),delete i[s])}return t}));this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],0===e?a=r:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(r))}return this._loader.logClose(),a}))}_loadUriAsync(e,t,i){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const s=this._nodeIndexLOD-1;return this._nodeSignalLODs[s]=this._nodeSignalLODs[s]||new Jr,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const s=this._materialIndexLOD-1;return this._materialSignalLODs[s]=this._materialSignalLODs[s]||new Jr,this._materialSignalLODs[s].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}return null}loadBufferAsync(e,t,i,s){if(this._loader.parent.useRangeRequests&&!t.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const t=(e,t)=>{const n=i,r=n+s-1;let a=e[t];return a?(a.start=Math.min(a.start,n),a.end=Math.max(a.end,r)):(a={start:n,end:r,loaded:new Jr},e[t]=a),a.loaded.promise.then((e=>new Uint8Array(e.buffer,e.byteOffset+i-a.start,s)))};return this._loader.log("deferred"),null!==this._nodeIndexLOD?t(this._nodeBufferLODs,this._nodeIndexLOD):null!==this._materialIndexLOD?t(this._materialBufferLODs,this._materialIndexLOD):t(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const i=e[t];i&&(this._loader.log(`Loading buffer range [${i.start}-${i.end}]`),this._loader.bin.readAsync(i.start,i.end-i.start+1).then((e=>{i.loaded.resolve(e)}),(e=>{i.loaded.reject(e)})))}_getLODs(e,t,i,s){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const n=[];for(let t=s.length-1;t>=0;t--)if(n.push(Ka.Get(`${e}/ids/${s[t]}`,i,s[t])),n.length===this.maxLODsToLoad)return n;return n.push(t),n}_disposeTransformNode(e){const t=[],i=e.material;i&&t.push(i);for(const i of e.getChildMeshes())i.material&&t.push(i.material);e.dispose();const s=t.filter((e=>this._loader.babylonScene.meshes.every((t=>t.material!=e))));this._disposeMaterials(s)}_disposeMaterials(e){const t={};for(const i of e){for(const e of i.getActiveTextures())t[e.uniqueId]=e;i.dispose()}for(const e in t)for(const i of this._loader.babylonScene.materials)i.hasTexture(t[e])&&delete t[e];for(const e in t)t[e].dispose()}}qa.RegisterExtension(Cl,(e=>new bl(e)));const yl="MSFT_minecraftMesh";class Ml{constructor(e){this.name=yl,this._loader=e,this.enabled=this._loader.isExtensionUsed(yl)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtraAsync(e,t,this.name,((s,n)=>{if(n){if(!(i instanceof Br))throw new Error(`${s}: Material type not supported`);const n=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,n}return null}))}}qa.RegisterExtension(yl,(e=>new Ml(e)));const xl="MSFT_sRGBFactors";class Ol{constructor(e){this.name=xl,this._loader=e,this.enabled=this._loader.isExtensionUsed(xl)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return qa.LoadExtraAsync(e,t,this.name,((s,n)=>{if(n){if(!(i instanceof Br))throw new Error(`${s}: Material type not supported`);const n=this._loader.loadMaterialPropertiesAsync(e,t,i),r=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,r),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,r),n}return null}))}}var Dl;qa.RegisterExtension(xl,(e=>new Ol(e))),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(Dl||(Dl={}));class Pl{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=Xt(),this.connectedPointIds=[],this.name=e,this._connectionType=t}get connectionType(){return this._connectionType}_isSingularConnection(){return!0}isConnected(){return this._connectedPoint.length>0}connectTo(e){if(this._connectionType===e._connectionType)throw new Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw new Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName();for(const t of this._connectedPoint)e.connectedPointIds.push(t.uniqueId)}getClassName(){return"FGConnection"}deserialize(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds}static Parse(e={},t){const i=new(Qt.Instantiate(e.className))(e.name,e._connectionType,t);return i.deserialize(e),i}}class Nl{constructor(e){this.value=this._toInt(e)}_toInt(e){return 0|e}add(e){return new Nl(this.value+e.value)}subtract(e){return new Nl(this.value-e.value)}multiply(e){return new Nl(Math.imul(this.value,e.value))}divide(e){return new Nl(this.value/e.value)}getClassName(){return Nl.ClassName}equals(e){return this.value===e.value}static Parse(e){return new Nl(e.value)}}Nl.ClassName="FlowGraphInteger",C("FlowGraphInteger",Nl);class Ll{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new Ll(e.typeName,e.defaultValue)}}const Fl=new Ll("any",void 0),wl=new Ll("number",0),Bl=new Ll("boolean",!1),Ul=new Ll("Vector2",w.Zero()),kl=new Ll("Vector3",B.Zero());new Ll("Vector4",U.Zero());const Gl=new Ll("Matrix",G.Identity());new Ll("Color3",J.Black()),new Ll("Quaternion",k.Identity());const Vl=new Ll("FlowGraphInteger",new Nl(0));class Xl extends Pl{constructor(e,t,i,s){super(e,t,i),this.richType=s}_isSingularConnection(){return 0===this.connectionType}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return 1===this.connectionType?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){const i=Pl.Parse(e,t);return i.richType=Ll.Parse(e.richType),i}}function Hl(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function zl(e){return"Vector2"===e||"Vector3"===e||"Vector4"===e||"Quaternion"===e||"Color3"===e||"Color4"===e}function Wl(e,t,i){const s=t?.getClassName?.()??"";Hl(s)?i[e]={name:t.name,className:s}:zl(s)?i[e]={value:t.asArray(),className:s}:i[e]=t}function Yl(e,t,i){const s=t[e];let n;const r=s?.className;return n=Hl(r)?i.getMeshByName(s.name):zl(r)?function(e,t){if("Vector2"===e)return w.FromArray(t);if("Vector3"===e)return B.FromArray(t);if("Vector4"===e)return U.FromArray(t);if("Quaternion"===e)return k.FromArray(t);if("Color3"===e)return new J(t[0],t[1],t[2]);if("Color4"===e)return new ee(t[0],t[1],t[2],t[3]);throw new Error(`Unknown vector class name ${e}`)}(r,s.value):"Matrix"===r?G.FromArray(s.value):r===Nl.ClassName?Nl.Parse(s):s&&void 0!==s.value?s.value:s,n}C("FGDataConnection",Xl);class Kl{constructor(e){this.config=e,this.uniqueId=Xt(),this.name=this.config?.name??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new Xl(e,0,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new Xl(e,1,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find((t=>t.name===e))}getDataOutput(e){return this.dataOutputs.find((t=>t.name===e))}serialize(e={},t=Wl){e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(const t of this.dataInputs){const i={};t.serialize(i),e.dataInputs.push(i)}for(const t of this.dataOutputs){const i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=Qt.Instantiate(e.className),s={},n=t.valueParseFunction??Yl;if(e.config)for(const i in e.config)s[i]=n(i,e.config,t.scene);var r;("FGSetPropertyBlock"===(r=e.className)||"FGGetPropertyBlock"===r||"FGPlayAnimationBlock"===r||"FGMeshPickEventBlock"===r)&&(s.pathConverter=t.pathConverter);const a=new i(s);a.uniqueId=e.uniqueId;for(let t=0;t<e.dataInputs.length;t++){const i=a.getDataInput(e.dataInputs[t].name);if(!i)throw new Error("Could not find data input with name "+e.dataInputs[t].name+" in block "+e.className);i.deserialize(e.dataInputs[t])}for(let t=0;t<e.dataOutputs.length;t++){const i=a.getDataOutput(e.dataOutputs[t].name);if(!i)throw new Error("Could not find data output with name "+e.dataOutputs[t].name+" in block "+e.className);i.deserialize(e.dataOutputs[t])}return a.metadata=e.metadata,a.deserialize&&a.deserialize(e),a}}class ql extends Pl{_isSingularConnection(){return 1===this.connectionType}_activateSignal(e){0===this.connectionType?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._execute(e,this),e._increaseExecutionId()):this._connectedPoint[0]?._activateSignal(e)}}C("FlowGraphSignalConnection",ql);class Ql extends Kl{constructor(e){super(e),this.signalInputs=[],this.signalOutputs=[],this.in=this._registerSignalInput("in")}_registerSignalInput(e){const t=new ql(e,0,this);return this.signalInputs.push(t),t}_registerSignalOutput(e){const t=new ql(e,1,this);return this.signalOutputs.push(t),t}getSignalInput(e){return this.signalInputs.find((t=>t.name===e))}getSignalOutput(e){return this.signalOutputs.find((t=>t.name===e))}serialize(e={}){super.serialize(e),e.signalInputs=[],e.signalOutputs=[];for(const t of this.signalInputs){const i={};t.serialize(i),e.signalInputs.push(i)}for(const t of this.signalOutputs){const i={};t.serialize(i),e.signalOutputs.push(i)}}deserialize(e){for(let t=0;t<e.signalInputs.length;t++){const i=this.getSignalInput(e.signalInputs[t].name);if(!i)throw new Error("Could not find signal input with name "+e.signalInputs[t].name+" in block "+e.className);i.deserialize(e.signalInputs[t])}for(let t=0;t<e.signalOutputs.length;t++){const i=this.getSignalOutput(e.signalOutputs[t].name);if(!i)throw new Error("Could not find signal output with name "+e.signalOutputs[t].name+" in block "+e.className);i.deserialize(e.signalOutputs[t])}}getClassName(){return"FGExecutionBlock"}}class jl extends Ql{constructor(e){super(e),this.out=this._registerSignalOutput("out"),this.done=this._registerSignalOutput("done")}_startPendingTasks(e){this._preparePendingTasks(e),e._addPendingBlock(this)}}class Zl extends jl{_execute(e){e._notifyExecuteNode(this),this.out._activateSignal(e)}}class $l{constructor(e){this.uniqueId=Xt(),this._userVariables={},this._executionVariables={},this._connectionValues={},this._pendingBlocks=[],this._executionId=0,this.onNodeExecutedObservable=new g,this._configuration=e}hasVariable(e){return e in this._userVariables}setVariable(e,t){this._userVariables[e]=t}getVariable(e){return this._userVariables[e]}get userVariables(){return this._userVariables}_getUniqueIdPrefixedName(e,t){return`${e.uniqueId}_${t}`}_setExecutionVariable(e,t,i){this._executionVariables[this._getUniqueIdPrefixedName(e,t)]=i}_getExecutionVariable(e,t,i){return this._hasExecutionVariable(e,t)?this._executionVariables[this._getUniqueIdPrefixedName(e,t)]:i}_deleteExecutionVariable(e,t){delete this._executionVariables[this._getUniqueIdPrefixedName(e,t)]}_hasExecutionVariable(e,t){return this._getUniqueIdPrefixedName(e,t)in this._executionVariables}_hasConnectionValue(e){return e.uniqueId in this._connectionValues}_setConnectionValue(e,t){this._connectionValues[e.uniqueId]=t}_getConnectionValue(e){return this._connectionValues[e.uniqueId]}get configuration(){return this._configuration}_addPendingBlock(e){this._pendingBlocks.push(e)}_removePendingBlock(e){const t=this._pendingBlocks.indexOf(e);-1!==t&&this._pendingBlocks.splice(t,1)}_clearPendingBlocks(){for(const e of this._pendingBlocks)e._cancelPendingTasks(this);this._pendingBlocks.length=0}_notifyExecuteNode(e){this.onNodeExecutedObservable.notifyObservers(e)}_increaseExecutionId(){this._executionId++}get executionId(){return this._executionId}serialize(e={},t=Wl){e.uniqueId=this.uniqueId,e._userVariables={};for(const i in this._userVariables)t(i,this._userVariables[i],e._userVariables);e._connectionValues={};for(const i in this._connectionValues)t(i,this._connectionValues[i],e._connectionValues)}getClassName(){return"FGContext"}static Parse(e,t){const i=t.graph.createContext(),s=t.valueParseFunction??Yl;i.uniqueId=e.uniqueId;for(const t in e._userVariables){const n=s(t,e._userVariables,i._configuration.scene);i._userVariables[t]=n}for(const t in e._connectionValues){const n=s(t,e._connectionValues,i._configuration.scene);i._connectionValues[t]=n}return i}}function Jl(e,t){return!(!e.parent||e.parent!==t&&!Jl(e.parent,t))}e([a()],$l.prototype,"uniqueId",void 0);class eh extends Zl{constructor(e){super(e),this.config=e}_getReferencedMesh(){const e=this.config.pathConverter.convert(this.config.path),t=e.info.getObject(e.object);if(!(t&&t instanceof ji))throw new Error("Mesh pick event block requires a valid mesh");return t}_preparePendingTasks(e){let t=e._getExecutionVariable(this,"meshPickObserver");if(!t){const i=this._getReferencedMesh();e._setExecutionVariable(this,"mesh",i),t=i.getScene().onPointerObservable.add((t=>{t.type===Es.POINTERPICK&&t.pickInfo?.pickedMesh&&(t.pickInfo?.pickedMesh===i||Jl(t.pickInfo?.pickedMesh,i))&&this._execute(e)}));const s=i.onDisposeObservable.add((()=>this._onDispose));e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",s)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),s=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(s),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return eh.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}var th,ih;eh.ClassName="FGMeshPickEventBlock",C(eh.ClassName,eh),function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(th||(th={}));class sh{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=0,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>this.dispose()))}createContext(){const e=new $l({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e}getContext(e){return this._executionContexts[e]}addEventBlock(e){this._eventBlocks.push(e)}start(){if(1!==this.state){this.state=1,0===this._executionContexts.length&&this.createContext();for(const e of this._executionContexts){const t=this._getContextualOrder();for(const i of t)i._startPendingTasks(e)}}}_getContextualOrder(){const e=[];for(const t of this._eventBlocks)if(t.getClassName()===eh.ClassName){const i=t._getReferencedMesh();let s=0;for(;s<e.length;s++){const t=e[s]._getReferencedMesh();if(i&&t&&Jl(i,t))break}e.splice(s,0,t)}else e.push(t);return e}dispose(){if(0!==this.state){this.state=0;for(const e of this._executionContexts)e._clearPendingBlocks();this._executionContexts.length=0,this._eventBlocks.length=0,this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null}}visitAllBlocks(e){const t=[],i=new Set;for(const e of this._eventBlocks)t.push(e),i.add(e.uniqueId);for(;t.length>0;){const s=t.pop();e(s);for(const e of s.dataInputs)for(const s of e._connectedPoint)i.has(s._ownerBlock.uniqueId)||(t.push(s._ownerBlock),i.add(s._ownerBlock.uniqueId));if(s instanceof Ql)for(const e of s.signalOutputs)for(const s of e._connectedPoint)i.has(s._ownerBlock.uniqueId)||(t.push(s._ownerBlock),i.add(s._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks((t=>{const i={};t.serialize(i),e.allBlocks.push(i)})),e.executionContexts=[];for(const i of this._executionContexts){const s={};i.serialize(s,t),e.executionContexts.push(s)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const e of i.dataOutputs)if(e.uniqueId===t)return e;throw new Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(const i of e)if(i instanceof Ql)for(const e of i.signalInputs)if(e.uniqueId===t)return e;throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),s=[],n=t.valueParseFunction??Yl;for(const r of e.allBlocks){const e=Kl.Parse(r,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:n});s.push(e),e instanceof Zl&&i.addEventBlock(e)}for(const e of s){for(const t of e.dataInputs)for(const e of t.connectedPointIds){const i=sh.GetDataOutConnectionByUniqueId(s,e);t.connectTo(i)}if(e instanceof Ql)for(const t of e.signalOutputs)for(const e of t.connectedPointIds){const i=sh.GetSignalInConnectionByUniqueId(s,e);t.connectTo(i)}}for(const t of e.executionContexts)$l.Parse(t,{graph:i,valueParseFunction:n});return i}}class nh{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add((()=>{this.dispose()}));(nh.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new sh({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){const t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach((e=>e.start()))}dispose(){this._flowGraphs.forEach((e=>e.dispose())),this._flowGraphs.length=0;const e=nh.SceneCoordinators.get(this.config.scene)??[],t=e.indexOf(this);-1!==t&&e.splice(t,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach((i=>{const s={};i.serialize(s,t),e._flowGraphs.push(s)}))}static Parse(e,t){const i=t.valueParseFunction??Yl,s=new nh({scene:t.scene});return e._flowGraphs?.forEach((e=>{sh.Parse(e,{coordinator:s,valueParseFunction:i,pathConverter:t.pathConverter})})),s}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new g,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}nh.SceneCoordinators=new Map;class rh extends Zl{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const t=e.configuration.scene.onReadyObservable.add((()=>{this._execute(e)}));e._setExecutionVariable(this,"sceneReadyObserver",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return rh.ClassName}}rh.ClassName="FGSceneReadyEventBlock",C("FGSceneReadyEventBlock",rh);class ah extends Zl{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneBeforeRender")){const t=e.configuration.scene.onBeforeRenderObservable.add((()=>{this._execute(e)}));e._setExecutionVariable(this,"sceneBeforeRender",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return ah.ClassName}}ah.ClassName="FGSceneTickEventBlock",C(ah.ClassName,ah);class oh extends Ql{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class lh extends oh{constructor(e){super(e),this.message=this.registerDataInput("message",Fl)}_execute(e){const t=this.message.getValue(e);ce.Log(t),this.out._activateSignal(e)}getClassName(){return lh.ClassName}}lh.ClassName="FGConsoleLogBlock",C(lh.ClassName,lh),function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(ih||(ih={}));class hh{constructor(e){this.onEachCountObservable=new g,this.onTimerAbortedObservable=new g,this.onTimerEndedObservable=new g,this.onStateChangedObservable=new g,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{const t=Date.now();this._timer=t-this._startTime;const i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},s=this._breakOnNextTick||this._breakCondition(i);s||this._timer>=this._timeToEnd?this._stop(i,s):this.onEachCountObservable.notifyObservers(i)},this._setState(0),this._contextObservable=e.contextObservable,this._observableParameters=e.observableParameters??{},this._breakCondition=e.breakCondition??(()=>!1),this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(1===this._state)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(1)}stop(){1===this._state&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(2),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class ch extends jl{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",wl)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(void 0!==t&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],s=e.configuration.scene,n=new hh({timeout:t,contextObservable:s.onBeforeRenderObservable,onEnded:()=>this._onEnded(n,e)});n.start(),i.push(n),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],s=i.indexOf(e);-1!==s?i.splice(s,1):Qt.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningTimers")||[];for(const e of t)e.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return ch.ClassName}}ch.ClassName="FGTimerBlock",C("FGTimerBlock",ch);class uh extends oh{constructor(e){super(e),this.config=e;for(let e=0;e<this.config.eventData.length;e++){const t=this.config.eventData[e];this.registerDataInput(t,Fl)}}_execute(e){const t=this.config.eventId,i=this.dataInputs.map((t=>t.getValue(e)));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return uh.ClassName}}uh.ClassName="FGSendCustomEventBlock",C("FGSendCustomEventBlock",uh);class dh extends Zl{constructor(e){super(e),this.config=e;for(let e=0;e<this.config.eventData.length;e++){const t=this.config.eventData[e];this.registerDataOutput(t,Fl)}}_preparePendingTasks(e){const t=e.configuration.coordinator.getCustomEventObservable(this.config.eventId);this._eventObserver=t.add((t=>{for(let i=0;i<t.length;i++)this.dataOutputs[i].setValue(t[i],e);this._execute(e)}))}_cancelPendingTasks(e){const t=e.configuration.coordinator.getCustomEventObservable(this.config.eventId);t?t.remove(this._eventObserver):Qt.Warn(`FlowGraphReceiveCustomEventBlock: Missing observable for event ${this.config.eventId}`)}getClassName(){return dh.ClassName}serialize(e){super.serialize(e),e.eventId=this.config.eventId,e.eventData=this.config.eventData}}dh.ClassName="FGReceiveCustomEventBlock",C(dh.ClassName,dh);class _h extends Ql{constructor(e){super(e),this.config=e,this.outFlows=[];for(let e=0;e<this.config.numberOutputFlows;e++)this.outFlows.push(this._registerSignalOutput(`${e}`))}_execute(e){for(let t=0;t<this.config.numberOutputFlows;t++)this.outFlows[t]._activateSignal(e)}getClassName(){return _h.ClassName}}_h.ClassName="FGSequenceBlock",C(_h.ClassName,_h);const fh=new RegExp(/\{(\w+)\}/g);class mh{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=fh.exec(e);for(;i;){const[,s]=i;this.templatedInputs.push(t.registerDataInput(s,Vl)),i=fh.exec(e)}}getAccessor(e,t){let i=this.path;for(const e of this.templatedInputs){const s=e.getValue(t).value;i=i.replace(`{${e.name}}`,s.toString())}return e.convert(i)}}class ph extends Kl{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",Fl),this.templateComponent=new mh(e.path,this)}_updateOutputs(e){const t=this.templateComponent.getAccessor(this.config.pathConverter,e),i=t.info.get(t.object);this.value.setValue(i,e)}getClassName(){return ph.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}ph.ClassName="FGGetPropertyBlock",C(ph.ClassName,ph);class gh extends oh{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",Fl),this.templateComponent=new mh(e.path,this)}_execute(e){const t=this.a.getValue(e),i=this.templateComponent.getAccessor(this.config.pathConverter,e);i.info.set(t,i.object),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path}getClassName(){return gh.ClassName}}gh.ClassName="FGSetPropertyBlock",C("FGSetPropertyBlock",gh);const Eh="cachedOperationValue",Th="cachedExecutionId";class Ah extends Kl{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,Th),i=e._getExecutionVariable(this,Eh);if(void 0!==i&&t===e.executionId)this.value.setValue(i,e);else{const t=this._doOperation(e);e._setExecutionVariable(this,Eh,t),e._setExecutionVariable(this,Th,e.executionId),this.value.setValue(t,e)}}}class Rh extends Ah{constructor(e,t,i,s,n,r){super(i,r),this._operation=s,this._className=n,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class vh extends Ah{constructor(e,t,i,s){super(e,s),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class Ih extends Ah{constructor(e,t,i,s,n){super(t,n),this._operation=i,this._className=s,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}class Sh extends Ah{constructor(e,t,i,s,n,r,a){super(s,a),this._operation=n,this._className=r,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t),this.c=this.registerDataInput("c",i)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))}getClassName(){return this._className}}function Ch(e){return e.getClassName?e.getClassName():""}function bh(e,t){return"Vector2"===e&&"Vector2"===t||"Vector3"===e&&"Vector3"===t||"Vector4"===e&&"Vector4"===t}function yh(e,t){return"Matrix"===e&&"Matrix"===t}function Mh(e,t){return"FlowGraphInteger"===e&&"FlowGraphInteger"===t}class xh extends Rh{constructor(e){super(Fl,Fl,Fl,((e,t)=>this._polymorphicAdd(e,t)),xh.ClassName,e)}_polymorphicAdd(e,t){const i=Ch(e),s=Ch(t);return bh(i,s)||yh(i,s)||Mh(i,s)?e.add(t):e+t}}xh.ClassName="FGAddBlock",C(xh.ClassName,xh);class Oh extends Rh{constructor(e){super(Fl,Fl,Fl,((e,t)=>this._polymorphicAdd(e,t)),Oh.ClassName,e)}_polymorphicAdd(e,t){const i=Ch(e),s=Ch(t);return bh(i,s)||Mh(i,s)?e.subtract(t):yh(i,s)?e.add(t.scale(-1)):e-t}}Oh.ClassName="FGSubBlock",C(Oh.ClassName,Oh);class Dh extends Rh{constructor(e){super(Fl,Fl,Fl,((e,t)=>this._polymorphicMultiply(e,t)),Dh.ClassName,e)}_polymorphicMultiply(e,t){const i=Ch(e),s=Ch(t);return bh(i,s)||Mh(i,s)?e.multiply(t):yh(i,s)?G.FromValues(e.m[0]*t.m[0],e.m[4]*t.m[4],e.m[8]*t.m[8],e.m[12]*t.m[12],e.m[1]*t.m[1],e.m[5]*t.m[5],e.m[9]*t.m[9],e.m[13]*t.m[13],e.m[2]*t.m[2],e.m[6]*t.m[6],e.m[10]*t.m[10],e.m[14]*t.m[14],e.m[3]*t.m[3],e.m[7]*t.m[7],e.m[11]*t.m[11],e.m[15]*t.m[15]):e*t}}Dh.ClassName="FGMultiplyBlock",C(Dh.ClassName,Dh);class Ph extends Rh{constructor(e){super(Fl,Fl,Fl,((e,t)=>this._polymorphicDivide(e,t)),Ph.ClassName,e)}_polymorphicDivide(e,t){const i=Ch(e),s=Ch(t);return bh(i,s)||Mh(i,s)?e.divide(t):yh(i,s)?G.FromValues(e.m[0]/t.m[0],e.m[4]/t.m[4],e.m[8]/t.m[8],e.m[12]/t.m[12],e.m[1]/t.m[1],e.m[5]/t.m[5],e.m[9]/t.m[9],e.m[13]/t.m[13],e.m[2]/t.m[2],e.m[6]/t.m[6],e.m[10]/t.m[10],e.m[14]/t.m[14],e.m[3]/t.m[3],e.m[7]/t.m[7],e.m[11]/t.m[11],e.m[15]/t.m[15]):e/t}}Ph.ClassName="FGDivideBlock",C(Ph.ClassName,Ph);class Nh extends vh{constructor(e){super(wl,(()=>Math.random()),Nh.ClassName,e)}}Nh.ClassName="FGRandomBlock",C(Nh.ClassName,Nh);class Lh extends Rh{constructor(e){super(Fl,Fl,wl,((e,t)=>this._polymorphicDot(e,t)),Lh.ClassName,e)}_polymorphicDot(e,t){switch(Ch(e)){case"Vector2":return w.Dot(e,t);case"Vector3":return B.Dot(e,t);case"Vector4":return U.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}Lh.ClassName="FGDotBlock",C(Lh.ClassName,Lh);class Fh extends vh{constructor(e){super(wl,(()=>Math.E),Fh.ClassName,e)}}Fh.ClassName="FGEBlock",C(Fh.ClassName,Fh);class wh extends vh{constructor(e){super(wl,(()=>Math.PI),wh.ClassName,e)}}wh.ClassName="FGPIBlock",C(wh.ClassName,wh);class Bh extends vh{constructor(e){super(wl,(()=>Number.POSITIVE_INFINITY),Bh.ClassName,e)}}Bh.ClassName="FGInfBlock",C(Bh.ClassName,Bh);class Uh extends vh{constructor(e){super(wl,(()=>Number.NaN),Uh.ClassName,e)}}function kh(e,t){switch(Ch(e)){case"FlowGraphInteger":return new Nl(t(e.value));case"Vector2":return new w(t(e.x),t(e.y));case"Vector3":return new B(t(e.x),t(e.y),t(e.z));case"Vector4":return new U(t(e.x),t(e.y),t(e.z),t(e.w));case"Matrix":return G.FromValues(t(e.m[0]),t(e.m[4]),t(e.m[8]),t(e.m[12]),t(e.m[1]),t(e.m[5]),t(e.m[9]),t(e.m[13]),t(e.m[2]),t(e.m[6]),t(e.m[10]),t(e.m[14]),t(e.m[3]),t(e.m[7]),t(e.m[11]),t(e.m[15]));default:return t(e)}}Uh.ClassName="FGNaNBlock",C(Uh.ClassName,Uh);class Gh extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicAbs(e)),Gh.ClassName,e)}_polymorphicAbs(e){return kh(e,Math.abs)}}Gh.ClassName="FGAbsBlock",C(Gh.ClassName,Gh);class Vh extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicSign(e)),Vh.ClassName,e)}_polymorphicSign(e){return kh(e,Math.sign)}}Vh.ClassName="FGSignBlock",C(Vh.ClassName,Vh);class Xh extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicTrunc(e)),Xh.ClassName,e)}_polymorphicTrunc(e){return kh(e,Math.trunc)}}Xh.ClassName="FGTruncBlock",C(Xh.ClassName,Xh);class Hh extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicFloor(e)),Hh.ClassName,e)}_polymorphicFloor(e){return kh(e,Math.floor)}}Hh.ClassName="FGFloorBlock",C(Hh.ClassName,Hh);class zh extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicCeiling(e)),zh.ClassName,e)}_polymorphicCeiling(e){return kh(e,Math.ceil)}}zh.ClassName="FGCeilBlock",C(zh.ClassName,zh);class Wh extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicFract(e)),Wh.ClassName,e)}_polymorphicFract(e){return kh(e,(e=>e-Math.floor(e)))}}Wh.ClassName="FGFractBlock",C(Wh.ClassName,Wh);class Yh extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicNeg(e)),Yh.ClassName,e)}_polymorphicNeg(e){return kh(e,(e=>-e))}}function Kh(e,t,i){switch(Ch(e)){case"FlowGraphInteger":return new Nl(i(e.value,t.value));case"Vector2":return new w(i(e.x,t.x),i(e.y,t.y));case"Vector3":return new B(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z));case"Vector4":return new U(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z),i(e.w,t.w));case"Matrix":return G.FromValues(i(e.m[0],t.m[0]),i(e.m[4],t.m[4]),i(e.m[8],t.m[8]),i(e.m[12],t.m[12]),i(e.m[1],t.m[1]),i(e.m[5],t.m[5]),i(e.m[9],t.m[9]),i(e.m[13],t.m[13]),i(e.m[2],t.m[2]),i(e.m[6],t.m[6]),i(e.m[10],t.m[10]),i(e.m[14],t.m[14]),i(e.m[3],t.m[3]),i(e.m[7],t.m[7]),i(e.m[11],t.m[11]),i(e.m[15],t.m[15]));default:return i(e,t)}}Yh.ClassName="FGNegBlock",C(Yh.ClassName,Yh);class qh extends Rh{constructor(e){super(Fl,Fl,Fl,((e,t)=>this._polymorphicRemainder(e,t)),qh.ClassName,e)}_polymorphicRemainder(e,t){return Kh(e,t,((e,t)=>e%t))}}qh.ClassName="FGRemainderBlock",C(qh.ClassName,qh);class Qh extends Rh{constructor(e){super(Fl,Fl,Fl,((e,t)=>this._polymorphicMin(e,t)),Qh.ClassName,e)}_polymorphicMin(e,t){return Kh(e,t,Math.min)}}Qh.ClassName="FGMinBlock",C(Qh.ClassName,Qh);class jh extends Rh{constructor(e){super(Fl,Fl,Fl,((e,t)=>this._polymorphicMax(e,t)),jh.ClassName,e)}_polymorphicMax(e,t){return Kh(e,t,Math.max)}}function Zh(e,t,i){return Math.min(Math.max(e,Math.min(t,i)),Math.max(t,i))}function $h(e,t,i,s){switch(Ch(e)){case"FlowGraphInteger":return new Nl(s(e.value,t.value,i.value));case"Vector2":return new w(s(e.x,t.x,i.x),s(e.y,t.y,i.y));case"Vector3":return new B(s(e.x,t.x,i.x),s(e.y,t.y,i.y),s(e.z,t.z,i.z));case"Vector4":return new U(s(e.x,t.x,i.x),s(e.y,t.y,i.y),s(e.z,t.z,i.z),s(e.w,t.w,i.w));case"Matrix":return G.FromValues(s(e.m[0],t.m[0],i.m[0]),s(e.m[4],t.m[4],i.m[4]),s(e.m[8],t.m[8],i.m[8]),s(e.m[12],t.m[12],i.m[12]),s(e.m[1],t.m[1],i.m[1]),s(e.m[5],t.m[5],i.m[5]),s(e.m[9],t.m[9],i.m[9]),s(e.m[13],t.m[13],i.m[13]),s(e.m[2],t.m[2],i.m[2]),s(e.m[6],t.m[6],i.m[6]),s(e.m[10],t.m[10],i.m[10]),s(e.m[14],t.m[14],i.m[14]),s(e.m[3],t.m[3],i.m[3]),s(e.m[7],t.m[7],i.m[7]),s(e.m[11],t.m[11],i.m[11]),s(e.m[15],t.m[15],i.m[15]));default:return s(e,t,i)}}jh.ClassName="FGMaxBlock",C(jh.ClassName,jh);class Jh extends Sh{constructor(e){super(Fl,Fl,Fl,Fl,((e,t,i)=>this._polymorphicClamp(e,t,i)),Jh.ClassName,e)}_polymorphicClamp(e,t,i){return $h(e,t,i,Zh)}}function ec(e){return Math.min(Math.max(e,0),1)}Jh.ClassName="FGClampBlock",C(Jh.ClassName,Jh);class tc extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicSaturate(e)),tc.ClassName,e)}_polymorphicSaturate(e){return kh(e,ec)}}tc.ClassName="FGSaturateBlock",C(tc.ClassName,tc);class ic extends Sh{constructor(e){super(Fl,Fl,Fl,Fl,((e,t,i)=>this._polymorphicInterpolate(e,t,i)),ic.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return $h(e,t,i,this._interpolate)}}ic.ClassName="FGInterpolateBlock",C(ic.ClassName,ic);class sc extends Rh{constructor(e){super(Fl,Fl,Bl,((e,t)=>this._polymorphicEq(e,t)),sc.ClassName,e)}_polymorphicEq(e,t){const i=Ch(e),s=Ch(t);return bh(i,s)||yh(i,s)||Mh(i,s)?e.equals(t):e===t}}function nc(e,t,i){const s=Ch(e);if(s===Ch(t)){if(""===s)return i(e,t);if("FlowGraphInteger"===s)return i(e.value,t.value);throw new Error(`Cannot compare ${e} and ${t}`)}throw new Error(`${e} and ${t} are of different types.`)}sc.ClassName="FGEqBlock",C(sc.ClassName,sc);class rc extends Rh{constructor(e){super(Fl,Fl,Bl,((e,t)=>this._polymorphicLessThan(e,t)),rc.ClassName,e)}_polymorphicLessThan(e,t){return nc(e,t,((e,t)=>e<t))}}rc.ClassName="FGLessThanBlock",C(rc.ClassName,rc);class ac extends Rh{constructor(e){super(Fl,Fl,Bl,((e,t)=>this._polymorphicLessThanOrEqual(e,t)),ac.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return nc(e,t,((e,t)=>e<=t))}}ac.ClassName="FGLessThanOrEqualBlock";class oc extends Rh{constructor(e){super(Fl,Fl,Bl,((e,t)=>this._polymorphicGreaterThan(e,t)),oc.ClassName,e)}_polymorphicGreaterThan(e,t){return nc(e,t,((e,t)=>e>t))}}oc.ClassName="FGGreaterThanBlock",C(oc.ClassName,oc);class lc extends Rh{constructor(e){super(Fl,Fl,Bl,((e,t)=>this._polymorphicGreaterThanOrEqual(e,t)),lc.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return nc(e,t,((e,t)=>e>=t))}}lc.ClassName="FGGreaterThanOrEqualBlock",C(lc.ClassName,lc);class hc extends Ih{constructor(e){super(Fl,Bl,(e=>this._polymorphicIsNan(e)),hc.ClassName,e)}_polymorphicIsNan(e){const t=Ch(e);if(""===t)return isNaN(e);if("FlowGraphInteger"===t)return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}hc.ClassName="FGIsNanBlock",C(hc.ClassName,hc);class cc extends Ih{constructor(e){super(Fl,Bl,(e=>this._polymorphicIsInf(e)),cc.ClassName,e)}_polymorphicIsInf(e){const t=Ch(e);if(""===t)return!isFinite(e);if("FlowGraphInteger"===t)return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}cc.ClassName="FGIsInfBlock";class uc extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicDegToRad(e)),uc.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return kh(e,this._degToRad)}}uc.ClassName="FGDegToRadBlock",C(uc.ClassName,uc);class dc extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicRadToDeg(e)),dc.ClassName,e)}_radToDeg(e){return 180*e/Math.PI}_polymorphicRadToDeg(e){return kh(e,this._radToDeg)}}dc.ClassName="FGRadToDegBlock",C(dc.ClassName,dc);class _c extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicSin(e)),_c.ClassName,e)}_polymorphicSin(e){return kh(e,Math.sin)}}_c.ClassName="FGSinBlock",C(_c.ClassName,_c);class fc extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicCos(e)),fc.ClassName,e)}_polymorphicCos(e){return kh(e,Math.cos)}}fc.ClassName="FGCosBlock",C(fc.ClassName,fc);class mc extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicTan(e)),mc.ClassName,e)}_polymorphicTan(e){return kh(e,Math.tan)}}mc.ClassName="FGTanBlock",C(mc.ClassName,mc);class pc extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicAsin(e)),pc.ClassName,e)}_polymorphicAsin(e){return kh(e,Math.asin)}}pc.ClassName="FGAsinBlock",C(pc.ClassName,pc);class gc extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicAcos(e)),gc.ClassName,e)}_polymorphicAcos(e){return kh(e,Math.acos)}}gc.ClassName="FGAcosBlock",C(gc.ClassName,gc);class Ec extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicAtan(e)),Ec.ClassName,e)}_polymorphicAtan(e){return kh(e,Math.atan)}}Ec.ClassName="FGAtanBlock",C(Ec.ClassName,Ec);class Tc extends Rh{constructor(e){super(Fl,Fl,Fl,((e,t)=>this._polymorphicAtan2(e,t)),Tc.ClassName,e)}_polymorphicAtan2(e,t){return Kh(e,t,Math.atan2)}}Tc.ClassName="FGAtan2Block",C(Tc.ClassName,Tc);class Ac extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicSinh(e)),Ac.ClassName,e)}_polymorphicSinh(e){return kh(e,Math.sinh)}}Ac.ClassName="FGSinhBlock",C(Ac.ClassName,Ac);class Rc extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicCosh(e)),Rc.ClassName,e)}_polymorphicCosh(e){return kh(e,Math.cosh)}}Rc.ClassName="FGCoshBlock",C(Rc.ClassName,Rc);class vc extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicTanh(e)),vc.ClassName,e)}_polymorphicTanh(e){return kh(e,Math.tanh)}}vc.ClassName="FGTanhBlock",C(vc.ClassName,vc);class Ic extends Ih{constructor(e){super(Fl,wl,(e=>this._polymorphicAsinh(e)),Ic.ClassName,e)}_polymorphicAsinh(e){return kh(e,Math.asinh)}}Ic.ClassName="FGAsinhBlock",C(Ic.ClassName,Ic);class Sc extends Ih{constructor(e){super(Fl,wl,(e=>this._polymorphicAcosh(e)),Sc.ClassName,e)}_polymorphicAcosh(e){return kh(e,Math.acosh)}}Sc.ClassName="FGAcoshBlock",C(Sc.ClassName,Sc);class Cc extends Ih{constructor(e){super(Fl,wl,(e=>this._polymorphicAtanh(e)),Cc.ClassName,e)}_polymorphicAtanh(e){return kh(e,Math.atanh)}}Cc.ClassName="FGAtanhBlock",C(Cc.ClassName,Cc);class bc extends Ih{constructor(e){super(Fl,wl,(e=>this._polymorphicExp(e)),bc.ClassName,e)}_polymorphicExp(e){return kh(e,Math.exp)}}bc.ClassName="FGExpBlock",C(bc.ClassName,bc);class yc extends Ih{constructor(e){super(Fl,wl,(e=>this._polymorphicLog(e)),yc.ClassName,e)}_polymorphicLog(e){return kh(e,Math.log)}}yc.ClassName="FGLogBlock",C(yc.ClassName,yc);class Mc extends Ih{constructor(e){super(Fl,wl,(e=>this._polymorphicLog2(e)),Mc.ClassName,e)}_polymorphicLog2(e){return kh(e,Math.log2)}}Mc.ClassName="FGLog2Block",C(Mc.ClassName,Mc);class xc extends Ih{constructor(e){super(Fl,wl,(e=>this._polymorphicLog10(e)),xc.ClassName,e)}_polymorphicLog10(e){return kh(e,Math.log10)}}xc.ClassName="FGLog10Block",C(xc.ClassName,xc);class Oc extends Ih{constructor(e){super(Fl,wl,(e=>this._polymorphicSqrt(e)),Oc.ClassName,e)}_polymorphicSqrt(e){return kh(e,Math.sqrt)}}Oc.ClassName="FGSqrtBlock",C(Oc.ClassName,Oc);class Dc extends Ih{constructor(e){super(Fl,wl,(e=>this._polymorphicCubeRoot(e)),Dc.ClassName,e)}_polymorphicCubeRoot(e){return kh(e,Math.cbrt)}}Dc.ClassName="FGCubeRootBlock",C(Dc.ClassName,Dc);class Pc extends Rh{constructor(e){super(Fl,wl,wl,((e,t)=>this._polymorphicPow(e,t)),Pc.ClassName,e)}_polymorphicPow(e,t){return Kh(e,t,Math.pow)}}Pc.ClassName="FGPowBlock",C(Pc.ClassName,Pc);class Nc extends Ih{constructor(e){super(Fl,wl,(e=>this._polymorphicLength(e)),Nc.ClassName,e)}_polymorphicLength(e){switch(Ch(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}Nc.ClassName="FGLengthBlock",C(Nc.ClassName,Nc);class Lc extends Ih{constructor(e){super(Fl,Fl,(e=>this._polymorphicNormalize(e)),Lc.ClassName,e)}_polymorphicNormalize(e){switch(Ch(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}Lc.ClassName="FGNormalizeBlock",C(Lc.ClassName,Lc);class Fc extends Rh{constructor(e){super(kl,kl,kl,((e,t)=>B.Cross(e,t)),Fc.ClassName,e)}}Fc.ClassName="FGCrossBlock",C(Fc.ClassName,Fc);class wc extends Rh{constructor(e){super(Ul,wl,Ul,((e,t)=>w.Transform(e,G.RotationZ(t))),wc.ClassName,e)}}wc.ClassName="FGRotate2DBlock",C(wc.ClassName,wc);class Bc extends Sh{constructor(e){super(kl,kl,wl,kl,((e,t,i)=>B.TransformCoordinates(e,G.RotationAxis(t,i))),Bc.ClassName,e)}}Bc.ClassName="FGRotate3DBlock",C(Bc.ClassName,Bc);class Uc extends Ih{constructor(e){super(Gl,Gl,(e=>G.Transpose(e)),Uc.ClassName,e)}}Uc.ClassName="FGTransposeBlock",C(Uc.ClassName,Uc);class kc extends Ih{constructor(e){super(Gl,wl,(e=>e.determinant()),kc.ClassName,e)}}kc.ClassName="FGDeterminantBlock",C(kc.ClassName,kc);class Gc extends Ih{constructor(e){super(Gl,Gl,(e=>G.Invert(e)),Gc.ClassName,e)}}Gc.ClassName="FGInvertMatrixBlock",C(Gc.ClassName,Gc);class Vc extends Rh{constructor(e){super(Gl,Gl,Gl,((e,t)=>t.multiply(e)),Vc.ClassName,e)}}Vc.ClassName="FGMatMulBlock",C(Vc.ClassName,Vc);class Xc extends Ih{constructor(e){super(Vl,Vl,(e=>new Nl(~e.value)),Xc.ClassName,e)}}Xc.ClassName="FGBitwiseNotBlock",C(Xc.ClassName,Xc);class Hc extends Rh{constructor(e){super(Vl,Vl,Vl,((e,t)=>new Nl(e.value&t.value)),Hc.ClassName,e)}}Hc.ClassName="FGBitwiseAndBlock",C(Hc.ClassName,Hc);class zc extends Rh{constructor(e){super(Vl,Vl,Vl,((e,t)=>new Nl(e.value|t.value)),zc.ClassName,e)}}zc.ClassName="FGBitwiseOrBlock",C(zc.ClassName,zc);class Wc extends Rh{constructor(e){super(Vl,Vl,Vl,((e,t)=>new Nl(e.value^t.value)),Wc.ClassName,e)}}Wc.ClassName="FGBitwiseXorBlock",C(Wc.ClassName,Wc);class Yc extends Rh{constructor(e){super(Vl,Vl,Vl,((e,t)=>new Nl(e.value<<t.value)),Yc.ClassName,e)}}Yc.ClassName="FGBitwiseLeftShiftBlock",C(Yc.ClassName,Yc);class Kc extends Rh{constructor(e){super(Vl,Vl,Vl,((e,t)=>new Nl(e.value>>t.value)),Kc.ClassName,e)}}Kc.ClassName="FGBitwiseRightShiftBlock",C(Kc.ClassName,Kc);class qc extends Ih{constructor(e){super(Vl,Vl,(e=>new Nl(Math.clz32(e.value))),qc.ClassName,e)}}qc.ClassName="FGCountLeadingZerosBlock",C(qc.ClassName,qc);class Qc extends Ih{constructor(e){super(Vl,Vl,(e=>new Nl(e.value?31-Math.clz32(e.value&-e.value):32)),Qc.ClassName,e)}}Qc.ClassName="FGCountTrailingZerosBlock",C(Qc.ClassName,Qc);class jc extends Ih{constructor(e){super(Vl,Vl,(e=>new Nl(function(e){let t=0;for(;e;)t+=1&e,e>>=1;return t}(e.value))),jc.ClassName,e)}}jc.ClassName="FGCountOneBitsBlock",C(jc.ClassName,jc);class Zc extends oh{constructor(e={startIndex:new Nl(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",Vl),this.value=this.registerDataOutput("value",Vl)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const t=this.value.getValue(e);t.value<this.n.getValue(e).value&&(this.value.setValue(new Nl(t.value+1),e),this.out._activateSignal(e))}}getClassName(){return Zc.ClassName}}Zc.ClassName="FGDoNBlock",C(Zc.ClassName,Zc);class $c extends Kl{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,Fl)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return $c.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}$c.ClassName="FGGetVariableBlock",C($c.ClassName,$c);class Jc extends oh{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,Fl)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return Jc.ClassName}}Jc.ClassName="FGSetVariableBlock",C(Jc.ClassName,Jc);class eu extends oh{constructor(e){super(e),this.config=e,this.condition=this.registerDataInput("condition",Bl),this.loopBody=this._registerSignalOutput("loopBody")}_execute(e,t){let i=this.condition.getValue(e);for(this.config?.isDo&&!i&&this.loopBody._activateSignal(e);i;)this.loopBody._activateSignal(e),i=this.condition.getValue(e);this.out._activateSignal(e)}getClassName(){return eu.ClassName}serialize(e){super.serialize(e),e.isDo=this.config?.isDo}}eu.ClassName="FGWhileLoopBlock",C(eu.ClassName,eu);const tu={"lifecycle/onStart":rh.ClassName,"lifecycle/onTick":ah.ClassName,log:lh.ClassName,"flow/delay":ch.ClassName,"customEvent/send":uh.ClassName,"customEvent/receive":dh.ClassName,"flow/sequence":_h.ClassName,"world/get":ph.ClassName,"world/set":gh.ClassName,"flow/doN":Zc.ClassName,"variable/get":$c.ClassName,"variable/set":Jc.ClassName,"flow/whileLoop":eu.ClassName,"math/random":Nh.ClassName,"math/e":Fh.ClassName,"math/pi":wh.ClassName,"math/inf":Bh.ClassName,"math/nan":Uh.ClassName,"math/abs":Gh.ClassName,"math/sign":Vh.ClassName,"math/trunc":Xh.ClassName,"math/floor":Hh.ClassName,"math/ceil":zh.ClassName,"math/fract":Wh.ClassName,"math/neg":Yh.ClassName,"math/add":xh.ClassName,"math/sub":Oh.ClassName,"math/mul":Dh.ClassName,"math/div":Ph.ClassName,"math/rem":qh.ClassName,"math/min":Qh.ClassName,"math/max":jh.ClassName,"math/clamp":Jh.ClassName,"math/saturate":tc.ClassName,"math/mix":ic.ClassName,"math/eq":sc.ClassName,"math/lt":rc.ClassName,"math/le":ac.ClassName,"math/gt":oc.ClassName,"math/ge":lc.ClassName,"math/isnan":hc.ClassName,"math/isinf":cc.ClassName,"math/rad":uc.ClassName,"math/deg":dc.ClassName,"math/sin":_c.ClassName,"math/cos":fc.ClassName,"math/tan":mc.ClassName,"math/asin":pc.ClassName,"math/acos":gc.ClassName,"math/atan":Ec.ClassName,"math/atan2":Tc.ClassName,"math/sinh":Ac.ClassName,"math/cosh":Rc.ClassName,"math/tanh":vc.ClassName,"math/asinh":Ic.ClassName,"math/acosh":Sc.ClassName,"math/atanh":Cc.ClassName,"math/exp":bc.ClassName,"math/log":yc.ClassName,"math/log2":Mc.ClassName,"math/log10":xc.ClassName,"math/sqrt":Oc.ClassName,"math/cbrt":Dc.ClassName,"math/pow":Pc.ClassName,"math/length":Nc.ClassName,"math/normalize":Lc.ClassName,"math/dot":Lh.ClassName,"math/cross":Fc.ClassName,"math/rotate2d":wc.ClassName,"math/rotate3d":Bc.ClassName,"math/transpose":Uc.ClassName,"math/determinant":kc.ClassName,"math/inverse":Gc.ClassName,"math/matmul":Vc.ClassName,"math/not":Xc.ClassName,"math/and":Hc.ClassName,"math/or":zc.ClassName,"math/xor":Wc.ClassName,"math/asr":Kc.ClassName,"math/lsl":Yc.ClassName,"math/clz":qc.ClassName,"math/ctz":Qc.ClassName,"math/popcnt":jc.ClassName},iu={float2:"Vector2",float3:"Vector3",float4:"Vector4",float4x4:"Matrix",int:"FlowGraphInteger"};function su(e,t,i){if(void 0!==e.type){const s=t.types&&t.types[e.type];if(!s)throw new Error(`${i}: Unknown type: ${e.type}`);const n=s.signature;if(!n)throw new Error(`${i}: Type ${e.type} has no signature`);const r=iu[n];return{value:e.value,className:r}}return e.value}function nu(e,t,i){const s=tu[t.type];if(!s)throw new Error(`/extensions/KHR_interactivity/nodes/${e}: Unknown block type: ${t.type}`);const n=e.toString(),r=function(e,t,i){const s={},n=e.configuration??[];for(const e of n)if("customEvent"===e.id){const n=t.customEvents&&t.customEvents[e.value];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown custom event: ${e.value}`);s.eventId=n.id,s.eventData=n.values.map((e=>e.id))}else if("variable"===e.id){const n=t.variables&&t.variables[e.value];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown variable: ${e.value}`);s.variableName=n.id}else if("path"===e.id){const t=e.value;s.path=t}else s[e.id]=su(e,t,`/extensions/KHR_interactivity/nodes/${i}`);return s}(t,i,n);return{className:s,config:r,uniqueId:n,metadata:t.metadata,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[]}}class ru extends pl{constructor(e){super(e,au)}}const au={nodes:{__array__:{__target__:!0,translation:{type:"Vector3",get:e=>e._babylonTransformNode.position,set:(e,t)=>{t._babylonTransformNode.position=e},getObject:e=>e._babylonTransformNode}}}},ou="KHR_interactivity";class lu{constructor(e){this._loader=e,this.name=ou,this.enabled=this._loader.isExtensionUsed(ou),this._pathConverter=new ru(this._loader.gltf)}dispose(){this._loader=null,delete this._pathConverter}onReady(){if(!this._loader.babylonScene||!this._pathConverter)return;const e=this._loader.babylonScene,t=this._loader.gltf.extensions?.KHR_interactivity,i=function(e){const t={uniqueId:Xt(),_userVariables:{},_connectionValues:{}},i=[t],s=[];for(let t=0;t<e.nodes.length;t++){const i=nu(t,e.nodes[t],e);s.push(i)}for(let i=0;i<e.nodes.length;i++){const n=e.nodes[i],r=s[i],a=n.flows??[];for(const e of a){const t=e.id,n={uniqueId:Xt(),name:t,_connectionType:1,connectedPointIds:[]};r.signalOutputs.push(n);const a=e.node,o=e.socket,l=s[a];if(!l)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Could not find node with id ${a} that connects its input with with node ${i}'s output ${t}`);let h=l.signalInputs.find((e=>e.name===o));h||(h={uniqueId:Xt(),name:o,_connectionType:0,connectedPointIds:[]},l.signalInputs.push(h)),h.connectedPointIds.push(n.uniqueId),n.connectedPointIds.push(h.uniqueId)}const o=n.values??[];for(const n of o){const a=n.id,o={uniqueId:Xt(),name:a,_connectionType:0,connectedPointIds:[]};if(r.dataInputs.push(o),void 0!==n.value){const s=su(n,e,`/extensions/KHR_interactivity/nodes/${i}`);t._connectionValues[o.uniqueId]=s}else{if(void 0===n.node||void 0===n.socket)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Invalid socket ${a} in node ${i}`);{const e=n.node,t=n.socket,r=s[e];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Could not find node with id ${e} that connects its output with node${i}'s input ${a}`);let l=r.dataOutputs.find((e=>e.name===t));l||(l={uniqueId:Xt(),name:t,_connectionType:1,connectedPointIds:[]},r.dataOutputs.push(l)),o.connectedPointIds.push(l.uniqueId),l.connectedPointIds.push(o.uniqueId)}}}}const n=e.variables??[];for(let i=0;i<n.length;i++){const s=n[i],r=s.id;t._userVariables[r]=su(s,e,`/extensions/KHR_interactivity/variables/${i}`)}return{allBlocks:s,executionContexts:i}}(t),s=new nh({scene:e});sh.Parse(i,{coordinator:s,pathConverter:this._pathConverter}),s.start()}}qa.RegisterExtension(ou,(e=>new lu(e)));const hu="ExtrasAsMetadata";class cu{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const i=e.metadata=e.metadata||{};(i.gltf=i.gltf||{}).extras=t.extras}}constructor(e){this.name=hu,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}createMaterial(e,t,i){const s=this._loader.createMaterial(e,t,i);return this._assignExtras(s,t),s}}qa.RegisterExtension(hu,(e=>new cu(e)));const uu={backgroundColor:new ee(.1,.1,.2,1)};class du{constructor(e,t){this._engine=e,this._isDisposed=!1,this._loadModelLock=new ea,this._loadModelAbortController=null,this._loadEnvironmentLock=new ea,this._environment=null,this._loadEnvironmentAbortController=null;const i={...uu,...t};this._details={scene:new Dn(this._engine),model:null},this._details.scene.clearColor=i.backgroundColor,this._camera=new js("camera1",0,0,1,B.Zero(),this._details.scene),this._camera.attachControl(),this._reframeCamera(),this.loadEnvironmentAsync(void 0).catch((()=>{})),this._engine.runRenderLoop((()=>{this._details.scene.render()})),t?.onInitialized?.(this._details)}async loadModelAsync(e,t){this._throwIfDisposedOrAborted(t);const i=e instanceof URL?e.href:e;this._loadModelAbortController?.abort("New model is being loaded before previous model finished loading.");const s=this._loadModelAbortController=new AbortController;await this._loadModelLock.lockAsync((async()=>{this._throwIfDisposedOrAborted(t,s.signal),this._details.model?.dispose(),this._details.model=await Pn.LoadAssetContainerAsync("",i,this._details.scene),this._details.model.addAllToScene(),this._reframeCamera()}))}async loadEnvironmentAsync(e,t){this._throwIfDisposedOrAborted(t),this._loadEnvironmentAbortController?.abort("New environment is being loaded before previous environment finished loading.");const i=this._loadEnvironmentAbortController=new AbortController;await this._loadEnvironmentLock.lockAsync((async()=>{this._throwIfDisposedOrAborted(t,i.signal),this._environment?.dispose(),this._environment=await new Promise(((t,i)=>{if(e){const s=Yr.CreateFromPrefilteredData(e.href,this._details.scene);this._details.scene.environmentTexture=s;const n=function(e,t,i,s){const n=$r("hdrSkyBox",{size:i},e),r=new Br("skyBox",e);return r.backFaceCulling=!1,r.reflectionTexture=t.clone(),r.reflectionTexture&&(r.reflectionTexture.coordinatesMode=wn.SKYBOX_MODE),r.microSurface=1-s,r.disableLighting=!0,r.twoSidedLighting=!0,n.material=r,n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n}(this._details.scene,s,(this._camera.maxZ-this._camera.minZ)/2,.3);this._details.scene.autoClear=!1;const r=s.onLoadObservable.addOnce((()=>{r.remove(),a.remove(),t({dispose(){s.dispose(),n?.dispose()}})})),a=wn.OnTextureLoadErrorObservable.add((e=>{e===s&&(r.remove(),a.remove(),i(new Error("Failed to load environment texture.")))}))}else{const e=new $s("hemilight",B.Up(),this._details.scene);this._details.scene.autoClear=!0,t(e)}}))}))}dispose(){this._details.scene.dispose(),this._isDisposed=!0}_reframeCamera(){this._camera.useFramingBehavior=!0;const e=this._camera.getBehaviorByName("Framing");e.framingTime=0,e.elevationReturnTime=-1;let t=1;if(this._details.scene.meshes.length){this._camera.lowerRadiusLimit=null;const i=this._details.scene.getWorldExtends((e=>e.isVisible&&e.isEnabled()));e.zoomOnBoundingInfo(i.min,i.max);const s=i.max.subtract(i.min),n=i.min.add(s.scale(.5));t=1.2*s.length(),isFinite(t)||(t=1,n.copyFromFloats(0,0,0)),this._camera.setTarget(n)}this._camera.lowerRadiusLimit=.01*t,this._camera.wheelPrecision=100/t,this._camera.alpha=Math.PI/2,this._camera.beta=Math.PI/2,this._camera.radius=t,this._camera.minZ=.01*t,this._camera.maxZ=1e3*t,this._camera.speed=.2*t,this._camera.useAutoRotationBehavior=!0,this._camera.pinchPrecision=200/this._camera.radius,this._camera.upperRadiusLimit=5*this._camera.radius,this._camera.wheelDeltaPercentage=.01,this._camera.pinchDeltaPercentage=.01,this._camera.restoreStateInterpolationFactor=.1}_throwIfDisposedOrAborted(...e){if(this._isDisposed)throw new Error("Viewer is disposed.");for(const t of e)t?.throwIfAborted()}}const _u={engine:"WebGL"};class fu extends HTMLElement{constructor(){super();const e=this.attachShadow({mode:"open"});e.innerHTML='\n <style>\n :host {\n display: block;\n width: 100%;\n height: 100%;\n }\n\n #container {\n display: block;\n width: 100%;\n height: 100%;\n }\n\n #renderCanvas {\n width: 100%;\n height: 100%;\n display: block;\n font-size: 0;\n }\n </style>\n <div id="container">\n <canvas id="renderCanvas" touch-action="none"></canvas>\n </div>\n ';const t=e.querySelector("#renderCanvas");this._viewer=function(e,t){const i={..._u,...t},s=[];let n=!1;const r=new ResizeObserver((()=>n=!0));r.observe(e),s.push((()=>r.disconnect()));const a=new Ui(e,void 0,t),o=i.onInitialized;i.onInitialized=e=>{const t=e.scene.onBeforeRenderObservable.add((()=>{n&&(a.resize(),n=!1)}));s.push((()=>t.remove())),o?.(e)};const l=new du(a,i);return s.push(l.dispose.bind(l)),s.push((()=>a.dispose())),l.dispose=()=>s.forEach((e=>e())),l}(t)}get src(){return this.getAttribute("src")}set src(e){null===e?this.removeAttribute("src"):this.setAttribute("src",e)}connectedCallback(){}attributeChangedCallback(e,t,i){switch(e){case"src":this._viewer.loadModelAsync(new URL(i)).catch(ce.Log);break;case"env":this._viewer.loadEnvironmentAsync(new URL(i)).catch(ce.Log)}}}fu.observedAttributes=Object.freeze(["src","env"]),globalThis.customElements.define("babylon-viewer",fu);export{fu as HTML3DElement,du as Viewer};
|
|
2
|
-
//# sourceMappingURL=babylon-viewer.esm.min.js.map
|