(()=>{"use strict";const e=function(){var e;return window._niftiez_global||(e=new class{constructor(){this._engine=null,this._scene=null,this._sceneToRender=null,this._scenes=null,this._canvas=null}get engine(){return this._engine}get scene(){return this._scene}get sceneToRender(){return this._sceneToRender}get scenes(){return this._scenes}get canvas(){return this._canvas}set engine(e){this._engine=e}set scene(e){this._scene=e}set sceneToRender(e){this._sceneToRender=e}set scenes(e){this._scenes=e}set canvas(e){this._canvas=e}},window._niftiez_global=e),window._niftiez_global};class t{constructor(){const t=e().engine.getRenderingCanvasClientRect();this._width=t.width,this._height=t.height,this._aspect=t.height/t.width}get width(){return this._width}get height(){return this._height}get aspect(){return this._aspect}}class i{constructor(e,t=!1,i,n){this.initialize(e,t,i,n)}initialize(e,t=!1,i,n){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=n,this}}class n{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1}}class s{static FromPromise(e,t){const i=new s;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 i(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,r=!1){if(!e)return null;const a=new n(e,t,s);return a.unregisterOnNextCall=r,i?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(a,this._lastNotifiedValue),a}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return!!e&&(-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))}removeCallback(e,t){for(let i=0;i{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,n,s){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=n,r.skipNextObservers=!1,r.lastReturnValue=e,r.userInfo=s;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 n=this._eventState;n.mask=i,n.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,n)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){this._observers.length=0,this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new s;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}function r(){return"undefined"!=typeof window}function a(){return"undefined"!=typeof navigator}function o(){return"undefined"!=typeof document}function l(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}const h={IsWindowObjectExist:r,IsNavigatorAvailable:a,IsDocumentAvailable:o,GetDOMTextContent:l};class c{static _CheckLimit(e,t){let i=c._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},c._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){var i;const n=c._LogLimitOutputs[e];if(!n||!c.MessageLimitReached)return;const s=this._Levels[t];n.current===n.limit&&c[s.name](c.MessageLimitReached.replace(/%LIMIT%/g,""+n.limit).replace(/%TYPE%/g,null!==(i=s.name)&&void 0!==i?i:""))}static _AddLogEntry(e){c._LogCache=e+c._LogCache,c.OnNewCacheEntry&&c.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){if(void 0!==i&&!c._CheckLimit(t,i))return;const n=c._FormatMessage(t),s=this._Levels[e];s.logFunc&&s.logFunc("BJS - "+n);const r=`
${n}

`;c._AddLogEntry(r),c._GenerateLimitMessage(t,e)}static get LogCache(){return c._LogCache}static ClearLogCache(){c._LogCache="",c._LogLimitOutputs={},c.errorsCount=0}static set LogLevels(e){c.Log=c._LogDisabled,c.Warn=c._LogDisabled,c.Error=c._LogDisabled,[c.MessageLogLevel,c.WarningLogLevel,c.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];c[e.name]=c._LogEnabled.bind(c,t)}}))}}c.NoneLogLevel=0,c.MessageLogLevel=1,c.WarningLogLevel=2,c.ErrorLogLevel=4,c.AllLogLevel=7,c.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",c._LogCache="",c._LogLimitOutputs={},c._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],c.errorsCount=0,c.Log=c._LogEnabled.bind(c,c.MessageLogLevel),c.Warn=c._LogEnabled.bind(c,c.WarningLogLevel),c.Error=c._LogEnabled.bind(c,c.ErrorLogLevel);const d=(e,t)=>e?e.getClassName&&"Mesh"===e.getClassName()?null:e.getClassName&&"SubMesh"===e.getClassName()?e.clone(t):e.clone?e.clone():null:null;class u{static DeepCopy(e,t,i,n){const s=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 r of s){if("_"===r[0]&&(!n||-1===n.indexOf(r)))continue;if(r.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(r))continue;const s=e[r],a=typeof s;if("function"!==a)try{if("object"===a)if(s instanceof Array){if(t[r]=[],s.length>0)if("object"==typeof s[0])for(let e=0;e(e.__proto__=t,e));const T=3e3;class A extends E{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",E._setPrototypeOf(this,A.prototype)}}const v=e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,n,s,r,a,o,l,h="",c=0;const d=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c>2,a=(3&i)<<4|n>>4,o=(15&n)<<2|s>>6,l=63&s,isNaN(n)?o=l=64:isNaN(s)&&(l=64),h+=t.charAt(r)+t.charAt(a)+t.charAt(o)+t.charAt(l);return h},S=e=>atob(e);class R{constructor(){this.children=[]}isValid(e){return!0}process(e,t){var i,n,s,r,a,o;let l="";if(this.line){let h=this.line;const c=t.processor;if(c){c.lineProcessor&&(h=c.lineProcessor(h,t.isFragment,t.processingContext));const l=null!==(n=null===(i=t.processor)||void 0===i?void 0:i.attributeKeywordName)&&void 0!==n?n:"attribute",d=t.isFragment&&(null===(s=t.processor)||void 0===s?void 0:s.varyingFragmentKeywordName)?null===(r=t.processor)||void 0===r?void 0:r.varyingFragmentKeywordName:!t.isFragment&&(null===(a=t.processor)||void 0===a?void 0:a.varyingVertexKeywordName)?null===(o=t.processor)||void 0===o?void 0:o.varyingVertexKeywordName:"varying";!t.isFragment&&c.attributeProcessor&&this.line.startsWith(l)?h=c.attributeProcessor(this.line,e,t.processingContext):c.varyingProcessor&&this.line.startsWith(d)?h=c.varyingProcessor(this.line,t.isFragment,e,t.processingContext):c.uniformProcessor&&c.uniformRegexp&&c.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(h=c.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):c.uniformBufferProcessor&&c.uniformBufferRegexp&&c.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(h=c.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):c.textureProcessor&&c.textureRegexp&&c.textureRegexp.test(this.line)?h=c.textureProcessor(this.line,t.isFragment,e,t.processingContext):(c.uniformProcessor||c.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?c.uniformProcessor&&(h=c.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):c.uniformBufferProcessor&&(h=c.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,c.endOfUniformBufferProcessor&&(h=c.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}l+=h+"\r\n"}return this.children.forEach((i=>{l+=i.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),l}}class C{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex{l=l.trim(),""!==l&&(t.push(l),l="")},s=e=>{iI._Stack[i],a=()=>-1===i?"!!INVALID EXPRESSION!!":I._Stack[i--];let o=0,l="";for(;o1){for(n();-1!==i&&I._OperatorPriority[r()]>=I._OperatorPriority[c];)t.push(a());s(c),o++}else l+=h;o++}for(n();-1!==i;)"("===r()?a():t.push(a());return t}}I._OperatorPriority={")":0,"(":1,"||":2,"&&":3},I._Stack=["","","","","","","","","","","","","","","","","","","",""];class b extends I{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 y extends I{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}}class P extends I{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}}class D extends I{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 n=parseInt(t),s=parseInt(this.testValue);switch(this.operand){case">":i=n>s;break;case"<":i=n=":i=n>=s;break;case"==":i=n===s}return i}}var O;!function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(O||(O={}));const L=/defined\s*?\((.+?)\)/g,N=/defined\s*?\[(.+?)\]/g,F=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g;class w{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,n){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const s=this._ProcessShaderConversion(e,t,n);i(s,e)}))}static PreProcess(e,t,i,n){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const s=this._ApplyPreProcessing(e,t,n);i(s,e)}))}static Finalize(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}static _ProcessPrecision(e,t){var i;if(null===(i=t.processor)||void 0===i?void 0:i.noPrecision)return e;const n=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=n?"precision highp float;\n"+e:"precision mediump float;\n"+e:n||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new b(t[1].trim(),"!"===e[0]);const i=["==",">=","<=","<",">"];let n="",s=0;for(n of i)if(s=e.indexOf(n),s>-1)break;if(-1===s)return new b(e);const r=e.substring(0,s).trim(),a=e.substring(s+n.length).trim();return new D(r,n,a)}static _BuildSubExpression(e){e=e.replace(L,"defined[$1]");const t=I.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],n=i[i.length-2];i.length-=2;const s="&&"==e?new P:new y;"string"==typeof t&&(t=t.replace(N,"defined($1)")),"string"==typeof n&&(n=n.replace(N,"defined($1)")),s.leftOperand="string"==typeof n?this._ExtractOperation(n):n,s.rightOperand="string"==typeof t?this._ExtractOperation(t):t,i.push(s)}let n=i[i.length-1];return"string"==typeof n&&(n=n.replace(N,"defined($1)")),"string"==typeof n?this._ExtractOperation(n):n}static _BuildExpression(e,t){const i=new M,n=e.substring(0,t);let s=e.substring(t);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),i.testExpression="#ifdef"===n?new b(s):"#ifndef"===n?new b(s,!0):this._BuildSubExpression(s),i}static _MoveCursorWithinIf(e,t,i){let n=e.currentLine;for(;this._MoveCursor(e,i);){n=e.currentLine;const s=n.substring(0,5).toLowerCase();if("#else"===s){const i=new R;return t.children.push(i),void this._MoveCursor(e,i)}if("#elif"===s){const e=this._BuildExpression(n,5);t.children.push(e),i=e}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine,n=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/.exec(i);if(n&&n.length)switch(n[0]){case"#ifdef":{const n=new x;t.children.push(n);const s=this._BuildExpression(i,6);n.children.push(s),this._MoveCursorWithinIf(e,n,s);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const n=new x;t.children.push(n);const s=this._BuildExpression(i,7);n.children.push(s),this._MoveCursorWithinIf(e,n,s);break}case"#if":{const n=new x,s=this._BuildExpression(i,3);t.children.push(n),n.children.push(s),this._MoveCursorWithinIf(e,n,s);break}}else{const e=new R;if(e.line=i,t.children.push(e),"#"===i[0]&&"d"===i[1]){const t=i.replace(";","").split(" ");e.additionalDefineKey=t[1],3===t.length&&(e.additionalDefineValue=t[2])}}}return!1}static _EvaluatePreProcessors(e,t,i){const n=new R,s=new C;return s.lineIndex=-1,s.lines=e.split("\n"),this._MoveCursor(s,n),n.process(t,i)}static _PreparePreProcessors(e,t){var i;const n=e.defines,s={};for(const e of n){const t=e.replace("#define","").replace(";","").trim().split(" ");s[t[0]]=t.length>1?t[1]:""}return(null===(i=e.processor)||void 0===i?void 0:i.shaderLanguage)===O.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",t._getGlobalDefines(s),s}static _ProcessShaderConversion(e,t,i){let n=this._ProcessPrecision(e,t);if(!t.processor)return n;if(t.processor.shaderLanguage===O.GLSL&&-1!==n.indexOf("#version 3")&&(n=n.replace("#version 300 es",""),!t.processor.parseGLES3))return n;const s=t.defines,r=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(n=t.processor.preProcessor(n,s,t.isFragment,t.processingContext)),n=this._EvaluatePreProcessors(n,r,t),t.processor.postProcessor&&(n=t.processor.postProcessor(n,s,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}static _ApplyPreProcessing(e,t,i){var n,s;let r=e;const a=t.defines,o=this._PreparePreProcessors(t,i);return(null===(n=t.processor)||void 0===n?void 0:n.preProcessor)&&(r=t.processor.preProcessor(r,a,t.isFragment,t.processingContext)),r=this._EvaluatePreProcessors(r,o,t),(null===(s=t.processor)||void 0===s?void 0:s.postProcessor)&&(r=t.processor.postProcessor(r,a,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}static _ProcessIncludes(e,t,i){let n=F.exec(e),s=new String(e),r=!1;for(;null!=n;){let a=n[1];if(-1!==a.indexOf("__decl__")&&(a=a.replace(/__decl__/,""),t.supportsUniformBuffers&&(a=a.replace(/Vertex/,"Ubo"),a=a.replace(/Fragment/,"Ubo")),a+="Declaration"),!t.includesShadersStore[a]){const e=t.shadersRepository+"ShadersInclude/"+a+".fx";return void w._FileToolsLoadFile(e,(e=>{t.includesShadersStore[a]=e,this._ProcessIncludes(s,t,i)}))}{let e=t.includesShadersStore[a];if(n[2]){const t=n[3].split(",");for(let i=0;it+"{X}"))),e+=a.replace(/\{X\}/g,i.toString())+"\n"}else t.supportsUniformBuffers||(e=e.replace(/light\{X\}.(\w*)/g,((e,t)=>t+"{X}"))),e=e.replace(/\{X\}/g,i)}s=s.replace(n[0],e),r=r||e.indexOf("#include<")>=0||e.indexOf("#include <")>=0}n=F.exec(e)}r?this._ProcessIncludes(s.toString(),t,i):i(s)}static _FileToolsLoadFile(e,t,i,n,s,r){throw _("FileTools")}}class B{static GetShadersRepository(e=O.GLSL){return e===O.GLSL?B.ShadersRepository:B.ShadersRepositoryWGSL}static GetShadersStore(e=O.GLSL){return e===O.GLSL?B.ShadersStore:B.ShadersStoreWGSL}static GetIncludesShadersStore(e=O.GLSL){return e===O.GLSL?B.IncludesShadersStore:B.IncludesShadersStoreWGSL}}B.ShadersRepository="src/Shaders/",B.ShadersStore={},B.IncludesShadersStore={},B.ShadersRepositoryWGSL="src/ShadersWGSL/",B.ShadersStoreWGSL={},B.IncludesShadersStoreWGSL={};class U{static get ShadersRepository(){return B.ShadersRepository}static set ShadersRepository(e){B.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new s),this._onBindObservable}constructor(e,t,i,n=null,a,o=null,l=null,h=null,c=null,d,u="",f=O.GLSL){var _,p,m;let g;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new s,this.onErrorObservable=new s,this._onBindObservable=null,this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!1,this._wasPreviouslyUsingInstances=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.name=e,this._key=u;let E,T,A=null;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=null!==(_=e.shaderLanguage)&&void 0!==_?_:O.GLSL,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t{if(R[0]&&R[1]){S.isFragment=!0;const[t,i]=R;w.Process(i,S,((i,n)=>{this._fragmentSourceCodeBeforeMigration=n,A&&(i=A("fragment",i));const s=w.Finalize(t,i,S);S=null,this._useFinalCode(s.vertexCode,s.fragmentCode,e)}),this._engine)}};this._loadShader(E,"Vertex","",(e=>{w.Initialize(S),w.Process(e,S,((t,i)=>{this._rawVertexSourceCode=e,this._vertexSourceCodeBeforeMigration=i,A&&(t=A("vertex",t)),R[0]=t,C()}),this._engine)})),this._loadShader(T,"Fragment","Pixel",(e=>{this._rawFragmentSourceCode=e,R[1]=e,C()}));const x=function(e){return function(){return this._pipelineContext&&this._pipelineContext[e].apply(this._pipelineContext,arguments),this}};["Int?","UInt?","IntArray?","UIntArray?","Array?","Color?","Vector?","Float?","Matrices","Matrix","Matrix3x3","Matrix2x2","Quaternion","DirectColor4"].forEach((e=>{const t=`set${e}`;t.endsWith("?")?["",2,3,4].forEach((e=>{this[t.slice(0,-1)+e]=this[t.slice(0,-1)+e]||x(t.slice(0,-1)+e).bind(this)})):this[t]=this[t]||x(t).bind(this)}))}_useFinalCode(e,t,i){if(i){const n=i.vertexElement||i.vertex||i.spectorName||i,s=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===O.WGSL?"//":"")+"#define SHADER_NAME vertex:"+n+"\n"+e,this._fragmentSourceCode=(this._shaderLanguage===O.WGSL?"//":"")+"#define SHADER_NAME fragment:"+s+"\n"+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){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)}_loadShader(e,t,i,n){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void n(l(e));if("source:"===e.substr(0,7))return void n(e.substr(7));if("base64:"===e.substr(0,7))return void n(window.atob(e.substr(7)));const s=B.GetShadersStore(this._shaderLanguage);if(s[e+t+"Shader"])return void n(s[e+t+"Shader"]);if(i&&s[e+i+"Shader"])return void n(s[e+i+"Shader"]);let r;r="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:B.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(r+"."+t.toLowerCase()+".fx",n)}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getVertexShaderCode())&&void 0!==t?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getFragmentShaderCode())&&void 0!==t?t:this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}_rebuildProgram(e,t,i,n){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{n&&n(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;t{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,e,this._attributes),e)for(let t=0;t=t&&(s=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${n[t-1]}`)}}return[e,s]}_processCompilationErrors(e,t=null){var i,n,s;this._compilationError=e.message;const r=this._attributesNames,a=this._fallbacks;if(c.Error("Unable to compile effect:"),c.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),c.Error("Attributes: "+r.map((function(e){return" "+e}))),c.Error("Defines:\r\n"+this.defines),U.LogShaderCodeOnCompilationError){let e=null,t=null,r=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getVertexShaderCode())&&([r,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),r&&(c.Error("Vertex code:"),c.Error(r))),(null===(n=this._pipelineContext)||void 0===n?void 0:n._getFragmentShaderCode())&&([r,t]=this._getShaderCodeAndErrorLine(null===(s=this._pipelineContext)||void 0===s?void 0:s._getFragmentShaderCode(),this._compilationError,!0),r&&(c.Error("Fragment code:"),c.Error(r))),e&&c.Error(e),t&&c.Error(t)}c.Error("Error: "+this._compilationError);const o=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,o()),a?(this._pipelineContext=null,a.hasMoreFallbacks?(this._allFallbacksProcessed=!1,c.Error("Trying next fallback."),this.defines=a.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,o(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||o())}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)}setDepthStencilTexture(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){const n=this._samplerList.indexOf(e);for(let e=1;e{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let t;switch(this.source){case H.Temp:break;case H.Url:return void(t=this._engine.createTexture(null!==(e=this._originalUrl)&&void 0!==e?e: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 H.Raw:t=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,void 0,this._useSRGBBuffer),t._swapAndDie(this,!1),this.isReady=!0;break;case H.Raw3D:t=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),t._swapAndDie(this,!1),this.isReady=!0;break;case H.Raw2DArray:t=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),t._swapAndDie(this,!1),this.isReady=!0;break;case H.Dynamic:t=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),t._swapAndDie(this,!1),this._engine.updateDynamicTexture(this,this._engine.getRenderingCanvas(),this.invertY,void 0,void 0,!0);break;case H.Cube:return void(t=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,(()=>{t._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer));case H.CubeRaw:t=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),t._swapAndDie(this,!1),this.isReady=!0;break;case H.CubeRawRGBD:return;case H.CubePrefiltered:return t=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(t._sphericalPolynomial=this._sphericalPolynomial)}}_swapAndDie(e,t=!0){var i;null===(i=this._hardwareTexture)||void 0===i||i.setUsage(e._source,this.generateMipMaps,this.isCube,this.width,this.height),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 n=this._engine.getLoadedTexturesCache();let s=n.indexOf(this);-1!==s&&n.splice(s,1),s=n.indexOf(e),-1===s&&n.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null)}}W._Counter=0;class X{constructor(){this.shaderLanguage=O.GLSL}postProcessor(e,t,i,n,s){if(!s.getCaps().drawBuffersExtension){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}class Y{constructor(){this.shaderLanguage=O.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const n=-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)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,(n?"":"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 K{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=K._Counter++}}K._Counter=0;class j extends K{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}const q=["Int","Int2","Int3","Int4","UInt","UInt2","UInt3","UInt4","Vector2","Vector3","Vector4","Float2","Float","Float3","Float4","Quaternion","Color3","Color4","DirectColor4"];class Q{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null;const e=[],t=function(){e.length=0,Array.prototype.push.apply(e,arguments),e[0]=this._uniforms[e[0]]},i=i=>{const n=q.includes(i.substring(3))&&"FloatN";if(n){const s=this[`_cache${n}`];return function(){const n=this.engine[i];t.apply(this,arguments),s.apply(this,arguments)&&(n.apply(this.engine,e)||(this._valueCache[arguments[0]]=null))}}return function(){const n=this.engine[i];t.apply(this,arguments),void 0!==arguments[1]&&(this._valueCache[arguments[0]]=null,n.apply(this.engine,e))}};["Int?","UInt?","IntArray?","UIntArray?","Array?","Float?","Matrices","Matrix3x3","Matrix2x2"].forEach((e=>{const t=`set${e}`;this[t]||(t.endsWith("?")?["",2,3,4].forEach((e=>{this[t.slice(0,-1)+e]=this[t.slice(0,-1)+e]||i(t.slice(0,-1)+e).bind(this)})):this[t]=this[t]||i(t).bind(this))}))}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}_fillEffectInformation(e,t,i,n,s,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)=>{n[i[t]]=e})),this._uniforms=n,h=0;h{r[e]=t}));for(const e of l.getAttributes(this,a))o.push(e)}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],n=t.updateFlag;return(void 0===i||i!==n)&&(this._valueCache[e]=n,!0)}_cacheFloatN(e,t,i,n,s){let r=this._valueCache[arguments[0]];if(!r||r.length!==arguments.length-1)return r=Array.prototype.slice.call(arguments,1),this._valueCache[arguments[0]]=r,!0;let a=!1;for(let e=0;e1&&!this.disableUniformBuffers}getCreationOptions(){return this._creationOptions}get _shouldUseHighPrecisionShader(){return!(!this._caps.highPrecisionShaderSupported||!this._highPrecisionShadersAllowed)}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get activeRenderLoops(){return this._activeRenderLoops}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}get currentViewport(){return this._cachedViewport}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),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,5,0,!1,!1,1)}return this._emptyCubeTexture}get isWebGPU(){return this._isWebGPU}get shaderPlatformName(){return this._shaderPlatformName}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return this._snapshotRenderingMode}set snapshotRenderingMode(e){this._snapshotRenderingMode=e}snapshotRenderingReset(){this.snapshotRendering=!1}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 ie._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,i,n){var a,o,l,h,d,u,_,p,m,g,E;this._name="WebGL",this._isDisposed=!1,this.forcePOTTextures=!1,this.isFullscreen=!1,this.cullBackFaces=null,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this.validateShaderPrograms=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this.disableUniformBuffers=!1,this.onDisposeObservable=new s,this._frameId=0,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._renderingQueueLaunched=!1,this._activeRenderLoops=new Array,this.onContextLostObservable=new s,this.onContextRestoredObservable=new s,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new k,this._stencilStateComposer=new ee,this._stencilState=new G,this._alphaState=new V,this._alphaMode=1,this._alphaEquation=0,this._internalTexturesCache=new Array,this._renderTargetWrapperCache=new Array,this._activeChannel=0,this._currentTextureChannel=-1,this._boundTexturesCache={},this._compiledEffects={},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._activeRequests=new Array,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new s,this._isWebGPU=!1,this._snapshotRenderingMode=0,this._viewportCached={x:0,y:0,z:0,w:0},this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},this.startTime=f.Now;let T=null;i=i||{},this._creationOptions=i,this.adaptToDeviceRatio=null!=n&&n,this._stencilStateComposer.stencilGlobal=this._stencilState,Z.SetMatrixPrecision(!!i.useHighPrecisionMatrix),i.antialias=null!=t?t:i.antialias,i.deterministicLockstep=null!==(a=i.deterministicLockstep)&&void 0!==a&&a,i.lockstepMaxSteps=null!==(o=i.lockstepMaxSteps)&&void 0!==o?o:4,i.timeStep=null!==(l=i.timeStep)&&void 0!==l?l:1/60,i.audioEngine=null===(h=i.audioEngine)||void 0===h||h,i.stencil=null===(d=i.stencil)||void 0===d||d,this._audioContext=null!==(_=null===(u=i.audioEngineOptions)||void 0===u?void 0:u.audioContext)&&void 0!==_?_:null,this._audioDestination=null!==(m=null===(p=i.audioEngineOptions)||void 0===p?void 0:p.audioDestination)&&void 0!==m?m:null,this.premultipliedAlpha=null===(g=i.premultipliedAlpha)||void 0===g||g,this.useExactSrgbConversions=null!==(E=i.useExactSrgbConversions)&&void 0!==E&&E,this._doNotHandleContextLost=!!i.doNotHandleContextLost,this._isStencilEnable=!!i.stencil,n=n||i.adaptToDeviceRatio||!1;const A=r()&&window.devicePixelRatio||1,v=i.limitDeviceRatio||A;if(this._hardwareScalingLevel=n?1/Math.min(v,A):1,this._lastDevicePixelRatio=A,!e)return;if(e.getContext){if(T=e,this._renderingCanvas=T,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of ie.ExceptionList){const n=t.key,s=t.targets;if(new RegExp(n).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,n=t.captureConstraint,s=new RegExp(i).exec(e);if(s&&s.length>0&&parseInt(s[s.length-1])>=n)continue}for(const e of s)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,c.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(this._initGLContext.bind(this))},T.addEventListener("webglcontextlost",this._onContextLost,!1),T.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference="high-performance"),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=T.getContext("webgl2",i)||T.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(!T)throw new Error("The provided canvas is null or undefined.");try{this._gl=T.getContext("webgl",i)||T.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;e1?new Y:new X,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);const S=`Babylon.js v${ie.Version}`;console.log(S+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",S)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&o()&&"ontouchend"in document},this._checkForMobile(),r()&&window.addEventListener("resize",this._checkForMobile))}_restoreEngineAfterContextLost(e){setTimeout((async()=>{var t;this._dummyFramebuffer=null;const i=this._depthCullingState.depthTest,n=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;await e(),this.wipeCaches(!0),this._rebuildEffects(),null===(t=this._rebuildComputeEffects)||void 0===t||t.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0),this._depthCullingState.depthTest=i,this._depthCullingState.depthFunc=n,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=r,c.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}),0)}_sharedInit(e){this._renderingCanvas=e}_getShaderProcessingContext(e){return null}_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._wasPreviouslyReady=!1,t._prepareEffect()}U.ResetCache()}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuild();for(const e of this._storageBuffers)e._rebuild()}_initGLContext(){var e;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")),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},this._glVersion=this._gl.getParameter(this._gl.VERSION);const t=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=t&&(this._glRenderer=this._gl.getParameter(t.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(t.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=(null!==(e=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))&&void 0!==e?e: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;else{const e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._gl.SRGB=e.SRGB_EXT,this._gl.SRGB8=e.SRGB_ALPHA_EXT,this._gl.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=0&&this._activeRenderLoops.splice(t,1)}_renderLoop(){if(!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let e=0;e0?this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}getHostWindow(){return r()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}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}_queueNewFrame(e,t){return ie.QueueNewFrame(e,t)}runRenderLoop(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=this._renderLoop.bind(this),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}clear(e,t,i,n=!1){const s=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=s;let r=0;t&&e&&(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),n&&(this._gl.clearStencil(0),r|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(r)}_viewport(e,t,i,n){e===this._viewportCached.x&&t===this._viewportCached.y&&i===this._viewportCached.z&&n===this._viewportCached.w||(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=n,this._gl.viewport(e,t,i,n))}setViewport(e,t,i){const n=t||this.getRenderWidth(),s=i||this.getRenderHeight(),r=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(r*n,a*s,n*e.width,s*e.height)}beginFrame(){}endFrame(){this._badOS&&this.flushFramebuffer(),this._frameId++}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const e=r()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}r()?(t=this._renderingCanvas?this._renderingCanvas.clientWidth||this._renderingCanvas.width:window.innerWidth,i=this._renderingCanvas?this._renderingCanvas.clientHeight||this._renderingCanvas.height:window.innerHeight):(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){return!(!this._renderingCanvas||(e|=0,t|=0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t||(this._renderingCanvas.width=e,this._renderingCanvas.height=t,0)))}bindFramebuffer(e,t=0,i,n,s,r=0,a=0){var o,l,h,c,d;const u=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(u._MSAAFramebuffer?u._MSAAFramebuffer:u._framebuffer);const f=this._gl;e.is2DArray?f.framebufferTextureLayer(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,null===(o=e.texture._hardwareTexture)||void 0===o?void 0:o.underlyingResource,r,a):e.isCube&&f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(l=e.texture._hardwareTexture)||void 0===l?void 0:l.underlyingResource,r);const _=e._depthStencilTexture;if(_){const i=e._depthStencilTextureWithStencil?f.DEPTH_STENCIL_ATTACHMENT:f.DEPTH_ATTACHMENT;e.is2DArray?f.framebufferTextureLayer(f.FRAMEBUFFER,i,null===(h=_._hardwareTexture)||void 0===h?void 0:h.underlyingResource,r,a):e.isCube?f.framebufferTexture2D(f.FRAMEBUFFER,i,f.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(c=_._hardwareTexture)||void 0===c?void 0:c.underlyingResource,r):f.framebufferTexture2D(f.FRAMEBUFFER,i,f.TEXTURE_2D,null===(d=_._hardwareTexture)||void 0===d?void 0:d.underlyingResource,r)}this._cachedViewport&&!s?this.setViewport(this._cachedViewport,i,n):(i||(i=e.width,r&&(i/=Math.pow(2,r))),n||(n=e.height,r&&(n/=Math.pow(2,r))),this._viewport(0,0,i,n)),this.wipeCaches()}setState(e,t=0,i,n=!1,s,r,a=0){var o,l;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const h=null===(l=null!==(o=this.cullBackFaces)&&void 0!==o?o:s)||void 0===l||l?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==h||i)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(a);const c=n?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==c||i)&&(this._depthCullingState.frontFace=c),this._stencilStateComposer.stencilMaterial=r}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}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentFramebuffer}generateMipmaps(e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)}unBindFramebuffer(e,t=!1,i){var n;const s=e;this._currentRenderTarget=null;const r=this._gl;if(s._MSAAFramebuffer){if(e.isMulti)return void this.unBindMultiColorAttachmentFramebuffer(e,t,i);r.bindFramebuffer(r.READ_FRAMEBUFFER,s._MSAAFramebuffer),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,s._framebuffer),r.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,r.COLOR_BUFFER_BIT,r.NEAREST)}!(null===(n=e.texture)||void 0===n?void 0:n.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){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 n=new j(i);return this.bindArrayBuffer(n),e instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t):this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),this._resetVertexBufferBinding(),n.references=1,n}createDynamicVertexBuffer(e){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t){const i=this._gl.createBuffer(),n=new j(i);if(!i)throw new Error("Unable to create index buffer");this.bindIndexBuffer(n);const s=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,s,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),n.references=1,n.is32Bits=4===s.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=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 n=e.program,s=this._gl.getUniformBlockIndex(n,t);this._gl.uniformBlockBinding(n,s,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,n,s,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!==n&&(o.type=n,l=!0),o.normalized!==s&&(o.normalized=s,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=n,o.normalized=s,o.stride=r,o.offset=a,o.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),n===this._gl.UNSIGNED_INT||n===this._gl.INT?this._gl.vertexAttribIPointer(t,i,n,r,a):this._gl.vertexAttribPointer(t,i,n,s,r,a))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const n=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s=0){const t=n[s];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,n){const s=this._gl.createVertexArray();if(!s)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,n),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}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,n,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;const t=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let r=0;for(let a=0;a=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[a],this._gl.FLOAT,!1,n,r)),r+=4*i[a]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,n){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,n)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1?"#version 300 es\n#define WEBGL2 \n":"",o=this._compileShader(t,"vertex",n,a),l=this._compileShader(i,"fragment",n,a);return this._createShaderProgram(e,o,l,s,r)}inlineShaderCode(e){return e}createPipelineContext(e){const t=new Q;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,i,n,s=null){const r=n.createProgram();if(e.program=r,!r)throw new Error("Unable to create program");return n.attachShader(r,t),n.attachShader(r,i),n.linkProgram(r),e.context=n,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),r}_finalizePipelineContext(e){const t=e.context,i=e.vertexShader,n=e.fragmentShader,s=e.program;if(!t.getProgramParameter(s,t.LINK_STATUS)){if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){const t=this._gl.getShaderInfoLog(i);if(t)throw e.vertexCompilationError=t,new Error("VERTEX SHADER "+t)}if(!this._gl.getShaderParameter(n,this._gl.COMPILE_STATUS)){const t=this._gl.getShaderInfoLog(n);if(t)throw e.fragmentCompilationError=t,new Error("FRAGMENT SHADER "+t)}const r=t.getProgramInfoLog(s);if(r)throw e.programLinkError=r,new Error(r)}if(this.validateShaderPrograms&&(t.validateProgram(s),!t.getProgramParameter(s,t.VALIDATE_STATUS))){const i=t.getProgramInfoLog(s);if(i)throw e.programValidationError=i,new Error(i)}t.deleteShader(i),t.deleteShader(n),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,i,n,s,r,a,o,l,h){const c=e;c.program=n?this.createRawShaderProgram(c,t,i,void 0,l):this.createShaderProgram(c,t,i,o,void 0,l),c.program.__SPECTOR_rebuildProgram=a}_isRenderingStateCompiled(e){const t=e;return!!this._gl.getProgramParameter(t.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(t),!0)}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(!i.isParallelCompiled)return void t();const n=i.onCompiled;i.onCompiled=n?()=>{n(),t()}:t}getUniforms(e,t){const i=new Array,n=e;for(let e=0;e1||this.isWebGPU)),(1!==a||this._caps.textureFloatLinearFiltering)&&(2!==a||this._caps.textureHalfFloatLinearFiltering)||(o=1),1!==a||this._caps.textureFloat||(a=0,c.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=this._gl,f=new W(this,n),_=e.width||e,p=e.height||e,m=e.layers||0,g=this._getSamplingParameters(o,r),E=0!==m?u.TEXTURE_2D_ARRAY:u.TEXTURE_2D,T=this._getRGBABufferInternalSizedFormat(a,l,h),A=this._getInternalFormat(l),v=this._getWebGLTextureType(a);return this._bindTextureDirectly(E,f),0!==m?(f.is2DArray=!0,u.texImage3D(E,0,T,_,p,m,0,A,v,null)):u.texImage2D(E,0,T,_,p,0,A,v,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),f._useSRGBBuffer=h,f.baseWidth=_,f.baseHeight=p,f.width=_,f.height=p,f.depth=m,f.isReady=!0,f.samples=d,f.generateMipMaps=r,f.samplingMode=o,f.type=a,f.format=l,this._internalTexturesCache.push(f),f}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,n,s=3,r=null,a=null,o,l,h=null,d=null,u=null,f=null,_,p,g){const E="data:"===(e=e||"").substr(0,5),T="blob:"===e.substr(0,5),A=E&&-1!==e.indexOf(";base64,"),v=d||new W(this,H.Url),S=e;!this._transformTextureUrl||A||d||h||(e=this._transformTextureUrl(e)),S!==e&&(v._originalUrl=S);const R=e.lastIndexOf(".");let C=f||(R>-1?e.substring(R).toLowerCase():""),x=null;C.indexOf("?")>-1&&(C=C.split("?")[0]);for(const e of ie._TextureLoaders)if(e.canLoad(C,_)){x=e;break}n&&n.addPendingData(v),v.url=e,v.generateMipMaps=!t,v.samplingMode=s,v.invertY=i,v._useSRGBBuffer=this._getUseSRGBBuffer(!!g,t),this._doNotHandleContextLost||(v._buffer=h);let M=null;r&&!d&&(M=v.onLoadedObservable.add(r)),d||this._internalTexturesCache.push(v);const I=(i,d)=>{n&&n.removePendingData(v),e===S?(M&&v.onLoadedObservable.remove(M),m.UseFallbackTexture&&this._createTextureBase(m.FallbackTexture,t,v.invertY,n,s,null,a,o,l,h,v),i=(i||"Unknown error")+(m.UseFallbackTexture?" - Fallback texture was used":""),v.onErrorObservable.notifyObservers({message:i,exception:d}),a&&a(i,d)):(c.Warn(`Failed to load ${e}, falling back to ${S}`),this._createTextureBase(S,t,v.invertY,n,s,r,a,o,l,h,v,u,f,_,p,g))};if(x){const t=e=>{x.loadData(e,v,((e,t,i,r,a,l)=>{l?I("TextureLoader failed to load data"):o(v,C,n,{width:e,height:t},v.invertY,!i,r,(()=>(a(),!1)),s)}),p)};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,n?n.offlineProvider:void 0,!0,((e,t)=>{I("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{T&&!this._doNotHandleContextLost&&(v._buffer=e),o(v,C,n,e,v.invertY,t,!1,l,s)};!E||A?h&&("string"==typeof h.decoding||h.close)?i(h):ie._FileToolsLoadImage(e,i,I,n?n.offlineProvider:null,_,v.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof h||h instanceof ArrayBuffer||ArrayBuffer.isView(h)||h instanceof Blob?ie._FileToolsLoadImage(h,i,I,n?n.offlineProvider:null,_,v.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):h&&i(h)}return v}createTexture(e,t,i,n,s=3,r=null,a=null,o=null,l=null,h=null,c=null,d,u,f,_){return this._createTextureBase(e,t,i,n,s,r,a,this._prepareWebGLTexture.bind(this),((e,t,i,s,r,a)=>{const o=this._gl,l=i.width===e&&i.height===t,c=h?this._getInternalFormat(h,r._useSRGBBuffer):".jpg"!==s||r._useSRGBBuffer?r._useSRGBBuffer?o.SRGB8_ALPHA8:o.RGBA:o.RGB;let d=h?this._getInternalFormat(h):".jpg"!==s||r._useSRGBBuffer?o.RGBA:o.RGB;if(r._useSRGBBuffer&&1===this.webGLVersion&&(d=c),l)return o.texImage2D(o.TEXTURE_2D,0,c,d,o.UNSIGNED_BYTE,i),!1;const u=this._caps.maxTextureSize;if(i.width>u||i.height>u||!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,c,d,o.UNSIGNED_BYTE,this._workingCanvas),r.width=e,r.height=t,1));{const e=new W(this,H.Temp);this._bindTextureDirectly(o.TEXTURE_2D,e,!0),o.texImage2D(o.TEXTURE_2D,0,c,d,o.UNSIGNED_BYTE,i),this._rescaleTexture(e,r,n,c,(()=>{this._releaseTexture(e),this._bindTextureDirectly(o.TEXTURE_2D,r,!0),a()}))}return!0}),o,l,h,c,d,u,_)}static _FileToolsLoadImage(e,t,i,n,s,r){throw _("FileTools")}_rescaleTexture(e,t,i,n,s){}createRawTexture(e,t,i,n,s,r,a,o=null,l=0,h=0,c=!1){throw _("Engine.RawTexture")}createRawCubeTexture(e,t,i,n,s,r,a,o=null){throw _("Engine.RawTexture")}createRawTexture3D(e,t,i,n,s,r,a,o,l=null,h=0){throw _("Engine.RawTexture")}createRawTexture2DArray(e,t,i,n,s,r,a,o,l=null,h=0){throw _("Engine.RawTexture")}_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 n=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(n,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(n,this._gl.TEXTURE_MIN_FILTER,s.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(n)),this._bindTextureDirectly(n,null),t.samplingMode=e}updateTextureDimensions(e,t,i,n=1){}updateTextureWrappingMode(e,t,i=null,n=null){const s=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==n&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(n),e),e._cachedWrapR=n),this._bindTextureDirectly(s,null)}_setupDepthStencilTexture(e,t,i,n,s,r=1){const a=t.width||t,o=t.height||t,l=t.layers||0;e.baseWidth=a,e.baseHeight=o,e.width=a,e.height=o,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=r,e.generateMipMaps=!1,e.samplingMode=n?2:1,e.type=0,e._comparisonFunction=s;const h=this._gl,c=this._getTextureTarget(e),d=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(c,h.TEXTURE_MAG_FILTER,d.mag),h.texParameteri(c,h.TEXTURE_MIN_FILTER,d.min),h.texParameteri(c,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(c,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===s?(h.texParameteri(c,h.TEXTURE_COMPARE_FUNC,515),h.texParameteri(c,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(c,h.TEXTURE_COMPARE_FUNC,s),h.texParameteri(c,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,n,s,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 37492:case 36196:this._caps.etc2?t=o.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779: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,n,0,s)}_uploadDataToTextureDirectly(e,t,i=0,n=0,s,r=!1){const a=this._gl,o=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===s?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=a.TEXTURE_2D;e.isCube&&(c=a.TEXTURE_CUBE_MAP_POSITIVE_X+i);const d=Math.round(Math.log(e.width)*Math.LOG2E),u=Math.round(Math.log(e.height)*Math.LOG2E),f=r?e.width:Math.pow(2,Math.max(d-n,0)),_=r?e.height:Math.pow(2,Math.max(u-n,0));a.texImage2D(c,n,h,f,_,0,l,o,t)}updateTextureData(e,t,i,n,s,r,a=0,o=0,l=!1){const h=this._gl,c=this._getWebGLTextureType(e.type),d=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let u=h.TEXTURE_2D,f=h.TEXTURE_2D;e.isCube&&(f=h.TEXTURE_CUBE_MAP_POSITIVE_X+a,u=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(u,e,!0),h.texSubImage2D(f,o,i,n,s,r,d,c,t),l&&this._gl.generateMipmap(f),this._bindTextureDirectly(u,null)}_uploadArrayBufferViewToTexture(e,t,i=0,n=0){const s=this._gl,r=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(r,e,!0),this._uploadDataToTextureDirectly(e,t,i,n),this._bindTextureDirectly(r,null,!0)}_prepareWebGLTextureContinuation(e,t,i,n,s){const r=this._gl;if(!r)return;const a=this._getSamplingParameters(s,!i);r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,a.mag),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,a.min),i||n||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,n,s,r,a,o,l=3){const h=this.getCaps().maxTextureSize,c=Math.min(h,this.needPOTTextures?ie.GetExponentOfTwo(n.width,h):n.width),d=Math.min(h,this.needPOTTextures?ie.GetExponentOfTwo(n.height,h):n.height),u=this._gl;u&&(e._hardwareTexture?(this._bindTextureDirectly(u.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),e.baseWidth=n.width,e.baseHeight=n.height,e.width=c,e.height=d,e.isReady=!0,o(c,d,n,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,r,a,l)}))||this._prepareWebGLTextureContinuation(e,i,r,a,l)):i&&i.removePendingData(e))}_setupFramebufferDepthAttachments(e,t,i,n,s=1){const r=this._gl;if(e&&t)return this._createRenderBuffer(i,n,s,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,n,s,e,e,r.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,n,s,r.STENCIL_INDEX8,r.STENCIL_INDEX8,r.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,n,s,r,a=!0){const o=this._gl.createRenderbuffer();return this._updateRenderBuffer(o,e,t,i,n,s,r,a)}_updateRenderBuffer(e,t,i,n,s,r,a,o=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),n>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,n,r,t,i):l.renderbufferStorage(l.RENDERBUFFER,s,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,a,l.RENDERBUFFER,e),o&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){var t;this._deleteTexture(null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource),this.unbindAllTextures();const i=this._internalTexturesCache.indexOf(e);-1!==i&&this._internalTexturesCache.splice(i,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){const t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t-1;if(i&&o&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||n){if(this._activateCurrentTexture(),t&&t.isMultiview)throw console.error(e,t),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,null!==(r=null===(s=null==t?void 0:t._hardwareTexture)||void 0===s?void 0:s.underlyingResource)&&void 0!==r?r:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(a=!0,this._activateCurrentTexture());return o&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),a}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;const n=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(n,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,n){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 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,n=!1,s=""){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,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let r;r=n?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=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;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,n){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e;this._isDisposed=!0,this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),null===(e=this.releaseComputeEffects)||void 0===e||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},r()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),window.removeEventListener("resize",this._checkForMobile)),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,U.ResetCache();for(const e of this._activeRequests)e.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}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(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),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 s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,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,n=t.UNSIGNED_BYTE,s=new Uint8Array(4);t.readPixels(0,0,1,1,e,n,s),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(n),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._gl.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:i=this._gl.RED;break;case 7:i=this._gl.RG;break;case 4:i=t?this._gl.SRGB:this._gl.RGB;break;case 5:i=t?this._gl.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._gl.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._gl.SRGB8:this._gl.RGB8;case 5:return i?this._gl.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._gl.SRGB8_ALPHA8:this._gl.RGBA8}_getRGBAMultiSampleBufferFormat(e){return 1===e?this._gl.RGBA32F:2===e?this._gl.RGBA16F:this._gl.RGBA8}_loadFile(e,t,i,n,s,r){const a=ie._FileToolsLoadFile(e,t,i,n,s,r);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}static _FileToolsLoadFile(e,t,i,n,s,r){throw _("FileTools")}readPixels(e,t,i,n,s=!0,r=!0){const a=s?4:3,o=s?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(n*i*a);return r&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,n,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=this._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=this._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}static CeilingPOT(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}static FloorPOT(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}static NearestPOT(e){const t=ie.CeilingPOT(e),i=ie.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let n;switch(i){case 1:n=ie.FloorPOT(e);break;case 2:n=ie.NearestPOT(e);break;default:n=ie.CeilingPOT(e)}return Math.min(n,t)}static QueueNewFrame(e,t){if(r()){const{requestPostAnimationFrame:i,requestAnimationFrame:n}=t||window;if("function"==typeof i)return i(e);if("function"==typeof n)return n(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:o()?document:null}}ie.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:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],ie._TextureLoaders=[],ie.CollisionsEpsilon=.001,ie._IsSupported=null,ie._HasMajorPerformanceCaveat=null;class ne{static SetImmediate(e){r()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}const se=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class re extends A{constructor(e,t){super(e,4e3),this.name="LoadFileError",E._setPrototypeOf(this,re.prototype),t instanceof p?this.request=t:this.file=t}}class ae extends A{constructor(e,t){super(e,4001),this.request=t,this.name="RequestFileError",E._setPrototypeOf(this,ae.prototype)}}class oe extends A{constructor(e,t){super(e,4002),this.file=t,this.name="ReadFileError",E._setPrototypeOf(this,oe.prototype)}}const le={DefaultRetryStrategy:class{static ExponentialBackoff(e=3,t=500){return(i,n,s)=>0!==n.status||s>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,s)*t}}.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e},he=e=>e.replace(/#/gm,"%23"),ce=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&le.CorsBehavior)if("string"==typeof le.CorsBehavior||le.CorsBehavior instanceof String)t.crossOrigin=le.CorsBehavior;else{const i=le.CorsBehavior(e);i&&(t.crossOrigin=i)}},de=(e,t,i,n,s="",r)=>{var a;let o,l=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(o=URL.createObjectURL(new Blob([e],{type:s})),l=!0):o=`data:${s};base64,`+v(e):e instanceof Blob?(o=URL.createObjectURL(e),l=!0):(o=he(e),o=le.PreprocessUrl(e));const h=m.LastCreatedEngine,c=t=>{if(i){const n=o||e.toString();i(`Error while trying to load image: ${0===n.indexOf("http")||n.length<=128?n:n.slice(0,128)+"..."}`,t)}};if("undefined"==typeof Image||null!==(a=null==h?void 0:h._features.forceBitmapOverHTMLImageElement)&&void 0!==a&&a)return fe(o,(n=>{h.createImageBitmap(new Blob([n],{type:s}),{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,n||void 0,!0,((e,t)=>{c(t)})),null;const d=new Image;ce(o,d);const u=[],f=()=>{u.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),u.length=0};u.push({target:d,name:"load",handler:()=>{f(),t(d),l&&d.src&&URL.revokeObjectURL(d.src)}}),u.push({target:d,name:"error",handler:e=>{f(),c(e),l&&d.src&&URL.revokeObjectURL(d.src)}}),u.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==d.src)return;f();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);m.UseFallbackTexture=!1,c(t),l&&d.src&&URL.revokeObjectURL(d.src),d.src=""}}),u.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const _="blob:"===o.substring(0,5),p="data:"===o.substring(0,5),E=()=>{_||p?d.src=o:fe(o,((e,t,i)=>{const n=new Blob([e],{type:!s&&i?i:s}),r=URL.createObjectURL(n);l=!0,d.src=r}),void 0,n||void 0,!0,((e,t)=>{c(t)}))};if(!_&&!p&&n&&n.enableTexturesOffline)n.open((()=>{n&&n.loadImage(o,d)}),E);else{if(-1!==o.indexOf("file:")){const e=decodeURIComponent(o.substring(5).toLowerCase());if(g.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(g.FilesToLoad[e])}catch(i){t=URL.createObjectURL(g.FilesToLoad[e])}d.src=t,l=!0}catch(e){d.src=""}return d}}E()}return d},ue=(e,t,i,n,r)=>{const a=new FileReader,o={onCompleteObservable:new s,abort:()=>a.abort()};return a.onloadend=()=>o.onCompleteObservable.notifyObservers(o),r&&(a.onerror=()=>{r(new oe(`Unable to read ${e.name}`,e))}),a.onload=e=>{t(e.target.result)},i&&(a.onprogress=i),n?a.readAsArrayBuffer(e):a.readAsText(e),o},fe=(e,t,i,n,r,a,o)=>{if(e.name)return ue(e,t,i,r,a?e=>{a(void 0,e)}:void 0);const l=e;if(-1!==l.indexOf("file:")){let e=decodeURIComponent(l.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const n=g.FilesToLoad[e];if(n)return ue(n,t,i,r,a?e=>a(void 0,new re(e.message,e.file)):void 0)}const{match:h,type:d}=ge(l);if(h){const e={onCompleteObservable:new s,abort:()=>()=>{}};try{const e=r?Ee(l):Te(l);t(e,void 0,d)}catch(e){a?a(void 0,e):c.Error(e.message||"Failed to parse the Data URL")}return ne.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return _e(l,((e,i)=>{t(e,null==i?void 0:i.responseURL,null==i?void 0:i.getResponseHeader("content-type"))}),i,n,r,a?e=>{a(e.request,new re(e.message,e.request))}:void 0,o)},_e=(e,t,i,n,a,o,l)=>{e=he(e),e=le.PreprocessUrl(e);const h=le.BaseUrl+e;let d=!1;const u={onCompleteObservable:new s,abort:()=>d=!0},f=()=>{let e,n=new p,s=null;const f=()=>{n&&(i&&n.removeEventListener("progress",i),e&&n.removeEventListener("readystatechange",e),n.removeEventListener("loadend",_))};let _=()=>{f(),u.onCompleteObservable.notifyObservers(u),u.onCompleteObservable.clear(),i=void 0,e=null,_=null,o=void 0,l=void 0,t=void 0};u.abort=()=>{d=!0,_&&_(),n&&n.readyState!==(XMLHttpRequest.DONE||4)&&n.abort(),null!==s&&(clearTimeout(s),s=null),n=null};const m=e=>{const t=e.message||"Unknown error";o&&n?o(new ae(t,n)):c.Error(t)},g=c=>{if(n){if(n.open("GET",h),l)try{l(n)}catch(e){return void m(e)}a&&(n.responseType="arraybuffer"),i&&n.addEventListener("progress",i),_&&n.addEventListener("loadend",_),e=()=>{if(!d&&n&&n.readyState===(XMLHttpRequest.DONE||4)){if(e&&n.removeEventListener("readystatechange",e),n.status>=200&&n.status<300||0===n.status&&(!r()||pe())){try{t&&t(a?n.response:n.responseText,n)}catch(e){m(e)}return}const i=le.DefaultRetryStrategy;if(i){const e=i(h,n,c);if(-1!==e)return f(),n=new p,void(s=setTimeout((()=>g(c+1)),e))}const l=new ae("Error status: "+n.status+" "+n.statusText+" - Unable to load "+h,n);o&&o(l)}},n.addEventListener("readystatechange",e),n.send()}};g(0)};if(n&&n.enableSceneOffline){const s=e=>{e&&e.status>400?o&&o(e):f()},r=()=>{n&&n.loadFile(le.BaseUrl+e,(e=>{!d&&t&&t(e),u.onCompleteObservable.notifyObservers(u)}),i?e=>{!d&&i&&i(e)}:void 0,s,a)};n.open(r,s)}else f();return u},pe=()=>"undefined"!=typeof location&&"file:"===location.protocol,me=e=>se.test(e),ge=e=>{const t=se.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function Ee(e){return(e=>{const t=S(e),i=t.length,n=new Uint8Array(new ArrayBuffer(i));for(let e=0;eS(e.split(",")[1]);let Ae;ie._FileToolsLoadImage=de,ie._FileToolsLoadFile=fe,w._FileToolsLoadFile=fe,((e,t,i,n,s,r,a,o,l,h)=>{Ae={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:n,IsFileURL:s,LoadFile:r,LoadImage:a,ReadFile:o,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(Ae,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(Ae,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(Ae,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(Ae,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})})(Ee,Te,le,me,pe,fe,de,ue,_e,ce);const ve={};function Se(e,t){ve[e]=t}function Re(e){return ve[e]}class Ce{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=Re(e);if(t)return t;c.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let n=window||this;for(let e=0,t=i.length;e{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}Ce.RegisteredExternalClasses={};class Me{static get BaseUrl(){return le.BaseUrl}static set BaseUrl(e){le.BaseUrl=e}static get DefaultRetryStrategy(){return le.DefaultRetryStrategy}static set DefaultRetryStrategy(e){le.DefaultRetryStrategy=e}static get CorsBehavior(){return le.CorsBehavior}static set CorsBehavior(e){le.CorsBehavior=e}static get UseFallbackTexture(){return m.UseFallbackTexture}static set UseFallbackTexture(e){m.UseFallbackTexture=e}static get RegisteredExternalClasses(){return Ce.RegisteredExternalClasses}static set RegisteredExternalClasses(e){Ce.RegisteredExternalClasses=e}static get fallbackTexture(){return m.FallbackTexture}static set fallbackTexture(e){m.FallbackTexture=e}static FetchToRef(e,t,i,n,s,r){const a=4*((Math.abs(e)*i%i|0)+(Math.abs(t)*n%n|0)*i);r.r=s[a]/255,r.g=s[a+1]/255,r.b=s[a+2]/255,r.a=s[a+3]/255}static Mix(e,t,i){return e*(1-i)+t*i}static Instantiate(e){return Ce.Instantiate(e)}static SetImmediate(e){ne.SetImmediate(e)}static IsExponentOfTwo(e){let t=1;do{t*=2}while(t{fe(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{n(t)}))}))}static LoadScript(e,t,i,n){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){null==i||i(`Unable to load script '${e}' in worker`,t)}return}if(!r())return void(null==i||i(`Cannot load script '${e}' outside of a window or a worker`));const s=document.getElementsByTagName("head")[0],a=document.createElement("script");a.setAttribute("type","text/javascript"),a.setAttribute("src",e),n&&(a.id=n),a.onload=()=>{t&&t()},a.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},s.appendChild(a)}static LoadScriptAsync(e){return new Promise(((t,i)=>{this.LoadScript(e,(()=>{t()}),((e,t)=>{i(t||new Error(e))}))}))}static ReadFileAsDataURL(e,t,i){const n=new FileReader,r={onCompleteObservable:new s,abort:()=>n.abort()};return n.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},n.onload=e=>{t(e.target.result)},n.onprogress=i,n.readAsDataURL(e),r}static ReadFile(e,t,i,n,s){return ue(e,t,i,n,s)}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,n){u.DeepCopy(e,t,i,n)}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{const n=atob(this.toDataURL(t,i).split(",")[1]),s=n.length,r=new Uint8Array(s);for(let e=0;e{n.parentElement&&n.parentElement.removeChild(n)})),n.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,n,s="image/png"){throw _("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,n="image/png"){throw _("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,n,s="image/png",r=1,a=!1,o){throw _("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,n="image/png",s=1,r=!1,a){throw _("ScreenshotTools")}static RandomId(){return xe()}static IsBase64(e){return me(e)}static DecodeBase64(e){return Ee(e)}static get errorsCount(){return c.errorsCount}static Log(e){c.Log(e)}static Warn(e){c.Warn(e)}static Error(e){c.Error(e)}static get LogCache(){return c.LogCache}static ClearLogCache(){c.ClearLogCache()}static set LogLevels(e){c.LogLevels=e}static set PerformanceLogLevel(e){return(e&Me.PerformanceUserMarkLogLevel)===Me.PerformanceUserMarkLogLevel?(Me.StartPerformanceCounter=Me._StartUserMark,void(Me.EndPerformanceCounter=Me._EndUserMark)):(e&Me.PerformanceConsoleLogLevel)===Me.PerformanceConsoleLogLevel?(Me.StartPerformanceCounter=Me._StartPerformanceConsole,void(Me.EndPerformanceCounter=Me._EndPerformanceConsole)):(Me.StartPerformanceCounter=Me._StartPerformanceCounterDisabled,void(Me.EndPerformanceCounter=Me._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Me._Performance){if(!r())return;Me._Performance=window.performance}t&&Me._Performance.mark&&Me._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&Me._Performance.mark&&(Me._Performance.mark(e+"-End"),Me._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Me._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Me._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return f.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),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,n=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,n=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=n?n+".":"")+i:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!a()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}Me.UseCustomRequestHeaders=!1,Me.CustomRequestHeaders=p.CustomRequestHeaders,Me._TmpFloatArray=new Float32Array(1),Me.GetDOMTextContent=l,Me.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.")},Me.NoneLogLevel=c.NoneLogLevel,Me.MessageLogLevel=c.MessageLogLevel,Me.WarningLogLevel=c.WarningLogLevel,Me.ErrorLogLevel=c.ErrorLogLevel,Me.AllLogLevel=c.AllLogLevel,Me.IsWindowObjectExist=r,Me.PerformanceNoneLogLevel=0,Me.PerformanceUserMarkLogLevel=1,Me.PerformanceConsoleLogLevel=2,Me.StartPerformanceCounter=Me._StartPerformanceCounterDisabled,Me.EndPerformanceCounter=Me._EndPerformanceCounterDisabled;class Ie{constructor(e,t,i,n=0){this.iterations=e,this.index=n-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{s&&s()?n.breakLoop():setTimeout((()=>{for(let r=0;r=e)break;if(i(a),s&&s()){n.breakLoop();break}}n.executeNext()}),r)}),n)}}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 be{constructor(e){this.length=0,this.data=new Array(e),this._id=be._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}be._GlobalId=0;class ye extends be{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;tthis.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 De{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),De._HandleParenthesisContent(e,t)))):De._HandleParenthesisContent(e,t))||"false"!==e&&De.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const n=e.split("||");for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e)){let s=De._SimplifyNegation(n[e].trim());const r=s.split("&&");if(r.length>1)for(let e=0;e(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}class Oe{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>Oe.HasTags(e),e.addTags=t=>Oe.AddTagsTo(e,t),e.removeTags=t=>Oe.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Oe.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){t&&"string"==typeof t&&t.split(" ").forEach((function(t){Oe._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Oe.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!Oe.HasTags(e))return;const i=t.split(" ");for(const t in i)Oe._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?Oe.HasTags(e):De.Eval(t,(t=>Oe.HasTags(e)&&e._tags[t])))}}class Le{static WithinEpsilon(e,t,i=1401298e-51){return Math.abs(e-t)<=i}static ToHex(e){const t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}static Sign(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1}static Clamp(e,t=0,i=1){return Math.min(i,Math.max(t,e))}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=Le.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=Le.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let n=Le.Clamp(i);return n=-2*n*n*n+3*n*n,t*n+e*(1-n)}static MoveTowards(e,t,i){let n=0;return n=Math.abs(t-e)<=i?t:e+Le.Sign(t-e)*i,n}static MoveTowardsAngle(e,t,i){const n=Le.DeltaAngle(e,t);let s=0;return-i180&&(n-=360),e+n*Le.Clamp(i)}static InverseLerp(e,t,i){let n=0;return n=e!=t?Le.Clamp((i-e)/(t-e)):0,n}static Hermite(e,t,i,n,s){const r=s*s,a=s*r;return e*(2*a-3*r+1)+i*(-2*a+3*r)+t*(a-2*r+s)+n*(a-r)}static Hermite1stDerivative(e,t,i,n,s){const r=s*s;return 6*(r-s)*e+(3*r-4*s+1)*t+6*(-r+s)*i+(3*r-2*s)*n}static RandomRange(e,t){return e===t?e:Math.random()*(t-e)+e}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static NormalizeRadians(e){return e-Le.TwoPi*Math.floor((e+Math.PI)/Le.TwoPi)}static HCF(e,t){const i=e%t;return 0===i?t:Le.HCF(t,i)}}Le.TwoPi=2*Math.PI;const Ne=1/2.2,Fe=2.2,we=(Math.sqrt(5),.001);class Be{static BuildArray(e,t){const i=[];for(let n=0;nfunction(e,t,i){const n=e[t];if("function"!=typeof n)return null;const s=function(){const n=e.length,r=s.previous.apply(e,arguments);return i(t,n),r};return n.next=s,s.previous=n,e[t]=s,()=>{const i=s.previous;if(!i)return;const n=s.next;n?(i.next=n,n.previous=i):(i.next=void 0,e[t]=i),s.next=void 0,s.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{null==e||e()}))}}const Ge=e=>parseInt(e.toString().replace(/\W/g,""));class Ve{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=Ge(this.x);return e=397*e^Ge(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return Ve.FromArrayToRef(e,t,this),this}asArray(){const e=new Array;return this.toArray(e,0),e}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)}add(e){return new this.constructor(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}addVector3(e){return new this.constructor(this.x+e.x,this.y+e.y)}subtract(e){return new this.constructor(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 this.constructor(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 this.constructor(this.x*e,this.y*t)}divide(e){return new this.constructor(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.divideToRef(e,this)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.copyFromFloats(-1*this.x,-1*this.y)}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){const t=new this.constructor(0,0);return this.scaleToRef(e,t),t}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=.001){return e&&Le.WithinEpsilon(this.x,e.x,t)&&Le.WithinEpsilon(this.y,e.y,t)}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}rotateToRef(e,t){const i=Math.cos(e),n=Math.sin(e);return t.x=i*this.x-n*this.y,t.y=n*this.x+i*this.y,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return Ve.NormalizeToRef(this,this),this}clone(){return new this.constructor(this.x,this.y)}static Zero(){return new Ve(0,0)}static One(){return new Ve(1,1)}static Random(e=0,t=1){return new Ve(Le.RandomRange(e,t),Le.RandomRange(e,t))}static get ZeroReadOnly(){return Ve._ZeroReadOnly}static FromArray(e,t=0){return new Ve(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static CatmullRom(e,t,i,n,s){const r=s*s,a=s*r,o=.5*(2*t.x+(-e.x+i.x)*s+(2*e.x-5*t.x+4*i.x-n.x)*r+(-e.x+3*t.x-3*i.x+n.x)*a),l=.5*(2*t.y+(-e.y+i.y)*s+(2*e.y-5*t.y+4*i.y-n.y)*r+(-e.y+3*t.y-3*i.y+n.y)*a);return new e.constructor(o,l)}static Clamp(e,t,i){let n=e.x;n=n>i.x?i.x:n,n=ni.y?i.y:s,s=st.x?e.x:t.x,n=e.y>t.y?e.y:t.y;return new e.constructor(i,n)}static Transform(e,t){const i=new e.constructor;return Ve.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){const n=t.m,s=e.x*n[0]+e.y*n[4]+n[12],r=e.x*n[1]+e.y*n[5]+n[13];return i.x=s,i.y=r,i}static PointInTriangle(e,t,i,n){const s=.5*(-i.y*n.x+t.y*(-i.x+n.x)+t.x*(i.y-n.y)+i.x*n.y),r=s<0?-1:1,a=(t.y*n.x-t.x*n.y+(n.y-t.y)*e.x+(t.x-n.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*s*r}static Distance(e,t){return Math.sqrt(Ve.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,n=e.y-t.y;return i*i+n*n}static Center(e,t){const i=new e.constructor;return Ve.CenterToRef(e,t,i)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const n=Ve.DistanceSquared(t,i);if(0===n)return Ve.Distance(e,t);const s=i.subtract(t),r=Math.max(0,Math.min(1,Ve.Dot(e.subtract(t),s)/n)),a=t.add(s.multiplyByFloats(r,r));return Ve.Distance(e,a)}}Ve._ZeroReadOnly=Ve.Zero();class ze{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=Ge(this._x);return e=397*e^Ge(this._y),e=397*e^Ge(this._z),e}asArray(){const e=[];return this.toArray(e,0),e}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 ze.FromArrayToRef(e,t,this),this}toQuaternion(){return We.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this.addInPlaceFromFloats(e._x,e._y,e._z)}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new this.constructor(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 this.constructor(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 this.constructor(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,n){return n.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new this.constructor(-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 this.constructor(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 n=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const s=t*Math.sin(i)*Math.cos(n),r=t*Math.cos(i),a=t*Math.sin(i)*Math.sin(n);return e.set(s,r,a),e}applyRotationQuaternionToRef(e,t){const i=e._w*this._x+e._y*this._z-e._z*this._y,n=e._w*this._y+e._z*this._x-e._x*this._z,s=e._w*this._z+e._x*this._y-e._y*this._x,r=-e._x*this._x-e._y*this._y-e._z*this._z;return t._x=i*e._w+r*-e._x+n*-e._z-s*-e._y,t._y=n*e._w+r*-e._y+s*-e._x-i*-e._z,t._z=s*e._w+r*-e._z+i*-e._y-n*-e._x,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new this.constructor)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){const i=new this.constructor;return this.projectOnPlaneToRef(e,t,i),i}projectOnPlaneToRef(e,t,i){const n=e.normal,s=e.d,r=Ye.Vector3[0];this.subtractToRef(t,r),r.normalize();const a=ze.Dot(r,n);if(Math.abs(a)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(!Le.WithinEpsilon(t,i,e))return!0;const n=Math.abs(this._z);return!Le.WithinEpsilon(t,n,e)||!Le.WithinEpsilon(i,n,e)}get isNonUniform(){const e=Math.abs(this._x);return e!==Math.abs(this._y)||e!==Math.abs(this._z)}floor(){return new this.constructor(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fract(){return new this.constructor(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z)}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){return"xyz"===(e=e.toLowerCase())||(Ye.Vector3[0].copyFrom(this),["x","y","z"].forEach(((t,i)=>{this[t]=Ye.Vector3[0][e[i]]}))),this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(Ye.Matrix[0]),ze.TransformCoordinatesToRef(this,Ye.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,Ye.Vector3[0]),Ye.Vector3[0].rotateByQuaternionToRef(e,Ye.Vector3[0]),t.addToRef(Ye.Vector3[0],i),i}cross(e){const t=new this.constructor;return ze.CrossToRef(this,e,t)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor(0,0,0);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.scaleToRef(1/t,e)}clone(){return new this.constructor(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,n){const s=ze.Dot(e,i)-n;return s/(s-(ze.Dot(t,i)-n))}static GetAngleBetweenVectors(e,t,i){const n=e.normalizeToRef(Ye.Vector3[1]),s=t.normalizeToRef(Ye.Vector3[2]);let r=ze.Dot(n,s);r=Le.Clamp(r,-1,1);const a=Math.acos(r),o=Ye.Vector3[3];return ze.CrossToRef(n,s,o),ze.Dot(o,i)>0?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(r)}static GetAngleBetweenVectorsOnPlane(e,t,i){Ye.Vector3[0].copyFrom(e);const n=Ye.Vector3[0];Ye.Vector3[1].copyFrom(t);const s=Ye.Vector3[1];Ye.Vector3[2].copyFrom(i);const r=Ye.Vector3[2],a=Ye.Vector3[3],o=Ye.Vector3[4];n.normalize(),s.normalize(),r.normalize(),ze.CrossToRef(r,n,a),ze.CrossToRef(a,r,o);const l=Math.atan2(ze.Dot(s,a),ze.Dot(s,o));return Le.NormalizeRadians(l)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const n=Ke.Vector3[0];return t.subtractToRef(e,n),i._y=Math.atan2(n.x,n.z)||0,i._x=Math.atan2(Math.sqrt(n.x**2+n.z**2),n.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=ze.Zero();return ze.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,n){i=Le.Clamp(i,0,1);const s=Ye.Vector3[0],r=Ye.Vector3[1];s.copyFrom(e);const a=s.length();s.normalizeFromLength(a),r.copyFrom(t);const o=r.length();r.normalizeFromLength(o);const l=ze.Dot(s,r);let h,c;if(l<.999){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 s.scaleInPlace(h),r.scaleInPlace(c),n.copyFrom(s).addInPlace(r),n.scaleInPlace(Le.Lerp(a,o,i)),n}static SmoothToRef(e,t,i,n,s){return ze.SlerpToRef(e,t,0===n?1:i/n,s),s}static FromArray(e,t=0){return new ze(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return ze.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 ze.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,n){return n.copyFromFloats(e,t,i),n}static Zero(){return new ze(0,0,0)}static One(){return new ze(1,1,1)}static Up(){return new ze(0,1,0)}static get UpReadOnly(){return ze._UpReadOnly}static get DownReadOnly(){return ze._DownReadOnly}static get RightReadOnly(){return ze._RightReadOnly}static get LeftReadOnly(){return ze._LeftReadOnly}static get LeftHandedForwardReadOnly(){return ze._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return ze._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return ze._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return ze._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return ze._ZeroReadOnly}static Down(){return new ze(0,-1,0)}static Forward(e=!1){return new ze(0,0,e?-1:1)}static Backward(e=!1){return new ze(0,0,e?1:-1)}static Right(){return new ze(1,0,0)}static Left(){return new ze(-1,0,0)}static Random(e=0,t=1){return new ze(Le.RandomRange(e,t),Le.RandomRange(e,t),Le.RandomRange(e,t))}static TransformCoordinates(e,t){const i=ze.Zero();return ze.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return ze.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,n,s){const r=n.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 s._x=a*h,s._y=o*h,s._z=l*h,s._isDirty=!0,s}static TransformNormal(e,t){const i=ze.Zero();return ze.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,n,s){const r=n.m;return s._x=e*r[0]+t*r[4]+i*r[8],s._y=e*r[1]+t*r[5]+i*r[9],s._z=e*r[2]+t*r[6]+i*r[10],s._isDirty=!0,s}static CatmullRom(e,t,i,n,s){const r=s*s,a=s*r,o=.5*(2*t._x+(-e._x+i._x)*s+(2*e._x-5*t._x+4*i._x-n._x)*r+(-e._x+3*t._x-3*i._x+n._x)*a),l=.5*(2*t._y+(-e._y+i._y)*s+(2*e._y-5*t._y+4*i._y-n._y)*r+(-e._y+3*t._y-3*i._y+n._y)*a),h=.5*(2*t._z+(-e._z+i._z)*s+(2*e._z-5*t._z+4*i._z-n._z)*r+(-e._z+3*t._z-3*i._z+n._z)*a);return new e.constructor(o,l,h)}static Clamp(e,t,i){const n=new e.constructor;return ze.ClampToRef(e,t,i,n),n}static ClampToRef(e,t,i,n){let s=e._x;s=s>i._x?i._x:s,s=si._y?i._y:r,r=ri._z?i._z:a,a=a0&&x<0?(I.copyFrom(r),b=t,y=i):x>0&&M<0?(I.copyFrom(o),b=i,y=n):(I.copyFrom(a).scaleInPlace(-1),b=n,y=t);const P=Ye.Vector3[9],D=Ye.Vector3[4];if(b.subtractToRef(g,v),y.subtractToRef(g,P),ze.CrossToRef(v,P,D),!(ze.Dot(D,l)<0))return s.copyFrom(g),Math.abs(_*p);const O=Ye.Vector3[5];ze.CrossToRef(I,D,O),O.normalize();const L=Ye.Vector3[9];L.copyFrom(b).subtractInPlace(g);const N=L.length();if(Nthis.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}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fract(){return new this.constructor(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(){const e=this.length();return 0===e?this:this.scaleInPlace(1/e)}toVector3(){return new ze(this.x,this.y,this.z)}clone(){return new this.constructor(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,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}set(e,t,i,n){return this.copyFromFloats(e,t,i,n)}setAll(e){return this.x=this.y=this.z=this.w=e,this}static FromArray(e,t){return t||(t=0),new He(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 He.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,n,s){return s.x=e,s.y=t,s.z=i,s.w=n,s}static Zero(){return new He(0,0,0,0)}static One(){return new He(1,1,1,1)}static Random(e=0,t=1){return new He(Le.RandomRange(e,t),Le.RandomRange(e,t),Le.RandomRange(e,t),Le.RandomRange(e,t))}static get ZeroReadOnly(){return He._ZeroReadOnly}static Normalize(e){const t=He.Zero();return He.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return t.copyFrom(e),t.normalize(),t}static Minimize(e,t){const i=new e.constructor;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new e.constructor;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(He.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,n=e.y-t.y,s=e.z-t.z,r=e.w-t.w;return i*i+n*n+s*s+r*r}static Center(e,t){return He.CenterToRef(e,t,He.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)}static TransformCoordinates(e,t){const i=He.Zero();return He.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return He.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,n,s){const r=n.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 s.x=a,s.y=o,s.z=l,s.w=h,s}static TransformNormal(e,t){const i=new e.constructor;return He.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){const n=t.m,s=e.x*n[0]+e.y*n[4]+e.z*n[8],r=e.x*n[1]+e.y*n[5]+e.z*n[9],a=e.x*n[2]+e.y*n[6]+e.z*n[10];return i.x=s,i.y=r,i.z=a,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,n,s,r){const a=s.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=n,r}static FromVector3(e,t=0){return new He(e._x,e._y,e._z,t)}}He._ZeroReadOnly=He.Zero();class We{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,n=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=n}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=Ge(this._x);return e=397*e^Ge(this._y),e=397*e^Ge(this._z),e=397*e^Ge(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}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=.001){return e&&Le.WithinEpsilon(this._x,e._x,t)&&Le.WithinEpsilon(this._y,e._y,t)&&Le.WithinEpsilon(this._z,e._z,t)&&Le.WithinEpsilon(this._w,e._w,t)}clone(){return new this.constructor(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,n){return this._x=e,this._y=t,this._z=i,this._w=n,this._isDirty=!0,this}set(e,t,i,n){return this.copyFromFloats(e,t,i,n)}add(e){return new this.constructor(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}subtract(e){return new this.constructor(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 this.constructor(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 this.constructor(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,n=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,s=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,n,s,r),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}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 this.constructor(-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(){const e=this.length();if(0===e)return this;const t=1/e;return this.scaleInPlace(t),this}normalizeToNew(){const e=this.length();if(0===e)return this.clone();const t=1/e;return this.scale(t)}toEulerAngles(){const e=ze.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,n=this._y,s=this._w,r=n*t-i*s,a=.4999999;if(r<-a)e._y=2*Math.atan2(n,s),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(r>a)e._y=2*Math.atan2(n,s),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const a=s*s,o=t*t,l=i*i,h=n*n;e._z=Math.atan2(2*(i*n+t*s),-o-l+h+a),e._x=Math.asin(-2*r),e._y=Math.atan2(2*(t*i+n*s),o-l-h+a),e._isDirty=!0}return e}toRotationMatrix(e){return Xe.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return We.FromRotationMatrixToRef(e,this),this}static FromRotationMatrix(e){const t=new We;return We.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,n=i[0],s=i[4],r=i[8],a=i[1],o=i[5],l=i[9],h=i[2],c=i[6],d=i[10],u=n+o+d;let f;return u>0?(f=.5/Math.sqrt(u+1),t._w=.25/f,t._x=(c-l)*f,t._y=(r-h)*f,t._z=(a-s)*f,t._isDirty=!0):n>o&&n>d?(f=2*Math.sqrt(1+n-o-d),t._w=(c-l)/f,t._x=.25*f,t._y=(s+a)/f,t._z=(r+h)/f,t._isDirty=!0):o>d?(f=2*Math.sqrt(1+o-n-d),t._w=(r-h)/f,t._x=(s+a)/f,t._y=.25*f,t._z=(l+c)/f,t._isDirty=!0):(f=2*Math.sqrt(1+d-n-o),t._w=(a-s)/f,t._x=(r+h)/f,t._y=(l+c)/f,t._z=.25*f,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 n=We.Dot(e,t);return 1-n*n<=i}static SmoothToRef(e,t,i,n,s){let r=0===n?1:i/n;return r=Le.Clamp(r,0,1),We.SlerpToRef(e,t,r,s),s}static Zero(){return new We(0,0,0,0)}static Inverse(e){return new e.constructor(-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 We(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 We.RotationAxisToRef(e,t,new We)}static RotationAxisToRef(e,t,i){const n=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*n,i._y=e._y*n,i._z=e._z*n,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new We(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 FromEulerAngles(e,t,i){const n=new We;return We.RotationYawPitchRollToRef(t,e,i,n),n}static FromEulerAnglesToRef(e,t,i,n){return We.RotationYawPitchRollToRef(t,e,i,n),n}static FromEulerVector(e){const t=new We;return We.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return We.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i){const n=ze.Dot(e,t)+1;return nMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(ze.CrossToRef(e,t,Ke.Vector3[0]),i.set(Ke.Vector3[0].x,Ke.Vector3[0].y,Ke.Vector3[0].z,n)),i.normalize()}static RotationYawPitchRoll(e,t,i){const n=new We;return We.RotationYawPitchRollToRef(e,t,i,n),n}static RotationYawPitchRollToRef(e,t,i,n){const s=.5*i,r=.5*t,a=.5*e,o=Math.sin(s),l=Math.cos(s),h=Math.sin(r),c=Math.cos(r),d=Math.sin(a),u=Math.cos(a);return n._x=u*h*l+d*c*o,n._y=d*c*l-u*h*o,n._z=u*c*o-d*h*l,n._w=u*c*l+d*h*o,n._isDirty=!0,n}static RotationAlphaBetaGamma(e,t,i){const n=new We;return We.RotationAlphaBetaGammaToRef(e,t,i,n),n}static RotationAlphaBetaGammaToRef(e,t,i,n){const s=.5*(i+e),r=.5*(i-e),a=.5*t;return n._x=Math.cos(r)*Math.sin(a),n._y=Math.sin(r)*Math.sin(a),n._z=Math.sin(s)*Math.cos(a),n._w=Math.cos(s)*Math.cos(a),n._isDirty=!0,n}static RotationQuaternionFromAxis(e,t,i){const n=new We(0,0,0,0);return We.RotationQuaternionFromAxisToRef(e,t,i,n),n}static RotationQuaternionFromAxisToRef(e,t,i,n){const s=Ye.Matrix[0];return Xe.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),s),We.FromRotationMatrixToRef(s,n),n}static FromLookDirectionLH(e,t){const i=new We;return We.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const n=Ye.Matrix[0];return Xe.LookDirectionLHToRef(e,t,n),We.FromRotationMatrixToRef(n,i),i}static FromLookDirectionRH(e,t){const i=new We;return We.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const n=Ye.Matrix[0];return Xe.LookDirectionRHToRef(e,t,n),We.FromRotationMatrixToRef(n,i)}static Slerp(e,t,i){const n=We.Identity();return We.SlerpToRef(e,t,i,n),n}static SlerpToRef(e,t,i,n){let s,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,s=o?-i:i;else{const e=Math.acos(a),t=1/Math.sin(e);r=Math.sin((1-i)*e)*t,s=o?-Math.sin(i*e)*t:Math.sin(i*e)*t}return n._x=r*e._x+s*t._x,n._y=r*e._y+s*t._y,n._z=r*e._z+s*t._z,n._w=r*e._w+s*t._w,n._isDirty=!0,n}static Hermite(e,t,i,n,s){const r=s*s,a=s*r,o=2*a-3*r+1,l=-2*a+3*r,h=a-2*r+s,c=a-r,d=e._x*o+i._x*l+t._x*h+n._x*c,u=e._y*o+i._y*l+t._y*h+n._y*c,f=e._z*o+i._z*l+t._z*h+n._z*c,_=e._w*o+i._w*l+t._w*h+n._w*c;return new e.constructor(d,u,f,_)}static Hermite1stDerivative(e,t,i,n,s){const r=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,n,s,r),r}static Hermite1stDerivativeToRef(e,t,i,n,s,r){const a=s*s;return r._x=6*(a-s)*e._x+(3*a-4*s+1)*t._x+6*(-a+s)*i._x+(3*a-2*s)*n._x,r._y=6*(a-s)*e._y+(3*a-4*s+1)*t._y+6*(-a+s)*i._y+(3*a-2*s)*n._y,r._z=6*(a-s)*e._z+(3*a-4*s+1)*t._z+6*(-a+s)*i._z+(3*a-2*s)*n._z,r._w=6*(a-s)*e._w+(3*a-4*s+1)*t._w+6*(-a+s)*i._w+(3*a-2*s)*n._w,r._isDirty=!0,r}}class Xe{static get Use64Bits(){return Z.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=Xe._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,n=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&n}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,Z.MatrixTrackPrecisionChange&&Z.MatrixTrackedMatrices.push(this),this._m=new Z.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],n=e[2],s=e[3],r=e[4],a=e[5],o=e[6],l=e[7],h=e[8],c=e[9],d=e[10],u=e[11],f=e[12],_=e[13],p=e[14],m=e[15],g=d*m-p*u,E=c*m-_*u,T=c*p-_*d,A=h*m-f*u,v=h*p-d*f,S=h*_-f*c;return t*+(a*g-o*E+l*T)+i*-(r*g-o*A+l*v)+n*+(r*E-a*A+l*S)+s*-(r*T-a*v+o*S)}toArray(){return this._m}asArray(){return this._m}invert(){return this.invertToRef(this),this}reset(){return Xe.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 this.constructor;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,n=t._m,s=e.m;for(let e=0;e<16;e++)n[e]=i[e]+s[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}invertToRef(e){if(!0===this._isIdentity)return Xe.IdentityToRef(e),e;const t=this._m,i=t[0],n=t[1],s=t[2],r=t[3],a=t[4],o=t[5],l=t[6],h=t[7],c=t[8],d=t[9],u=t[10],f=t[11],_=t[12],p=t[13],m=t[14],g=t[15],E=u*g-m*f,T=d*g-p*f,A=d*m-p*u,v=c*g-_*f,S=c*m-u*_,R=c*p-_*d,C=+(o*E-l*T+h*A),x=-(a*E-l*v+h*S),M=+(a*T-o*v+h*R),I=-(a*A-o*S+l*R),b=i*C+n*x+s*M+r*I;if(0===b)return e.copyFrom(this),e;const y=1/b,P=l*g-m*h,D=o*g-p*h,O=o*m-p*l,L=a*g-_*h,N=a*m-_*l,F=a*p-_*o,w=l*f-u*h,B=o*f-d*h,U=o*u-d*l,k=a*f-c*h,G=a*u-c*l,V=a*d-c*o,z=-(n*E-s*T+r*A),H=+(i*E-s*v+r*S),W=-(i*T-n*v+r*R),X=+(i*A-n*S+s*R),Y=+(n*P-s*D+r*O),K=-(i*P-s*L+r*N),j=+(i*D-n*L+r*F),q=-(i*O-n*N+s*F),Q=-(n*w-s*B+r*U),Z=+(i*w-s*k+r*G),J=-(i*B-n*k+r*V),$=+(i*U-n*G+s*V);return Xe.FromValuesToRef(C*y,z*y,Y*y,Q*y,x*y,H*y,K*y,Z*y,M*y,W*y,j*y,J*y,I*y,X*y,q*y,$*y,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 ze(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 Xe.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}multiply(e){const t=new this.constructor;return this.multiplyToRef(e,t),t}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}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 n=this._m,s=e.m,r=n[0],a=n[1],o=n[2],l=n[3],h=n[4],c=n[5],d=n[6],u=n[7],f=n[8],_=n[9],p=n[10],m=n[11],g=n[12],E=n[13],T=n[14],A=n[15],v=s[0],S=s[1],R=s[2],C=s[3],x=s[4],M=s[5],I=s[6],b=s[7],y=s[8],P=s[9],D=s[10],O=s[11],L=s[12],N=s[13],F=s[14],w=s[15];return t[i]=r*v+a*x+o*y+l*L,t[i+1]=r*S+a*M+o*P+l*N,t[i+2]=r*R+a*I+o*D+l*F,t[i+3]=r*C+a*b+o*O+l*w,t[i+4]=h*v+c*x+d*y+u*L,t[i+5]=h*S+c*M+d*P+u*N,t[i+6]=h*R+c*I+d*D+u*F,t[i+7]=h*C+c*b+d*O+u*w,t[i+8]=f*v+_*x+p*y+m*L,t[i+9]=f*S+_*M+p*P+m*N,t[i+10]=f*R+_*I+p*D+m*F,t[i+11]=f*C+_*b+p*O+m*w,t[i+12]=g*v+E*x+T*y+A*L,t[i+13]=g*S+E*M+T*P+A*N,t[i+14]=g*R+E*I+T*D+A*F,t[i+15]=g*C+E*b+T*O+A*w,this}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,n=t.m;return i[0]===n[0]&&i[1]===n[1]&&i[2]===n[2]&&i[3]===n[3]&&i[4]===n[4]&&i[5]===n[5]&&i[6]===n[6]&&i[7]===n[7]&&i[8]===n[8]&&i[9]===n[9]&&i[10]===n[10]&&i[11]===n[11]&&i[12]===n[12]&&i[13]===n[13]&&i[14]===n[14]&&i[15]===n[15]}clone(){const e=new this.constructor;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=Ge(this._m[0]);for(let t=1;t<16;t++)e=397*e^Ge(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new We,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,n){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const s=this._m;if(i&&i.copyFromFloats(s[12],s[13],s[14]),(e=e||Ye.Vector3[0]).x=Math.sqrt(s[0]*s[0]+s[1]*s[1]+s[2]*s[2]),e.y=Math.sqrt(s[4]*s[4]+s[5]*s[5]+s[6]*s[6]),e.z=Math.sqrt(s[8]*s[8]+s[9]*s[9]+s[10]*s[10]),n){const t=n.scaling.x<0?-1:1,i=n.scaling.y<0?-1:1,s=n.scaling.z<0?-1:1;e.x*=t,e.y*=i,e.z*=s}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,n=1/e._y,r=1/e._z;Xe.FromValuesToRef(s[0]*i,s[1]*i,s[2]*i,0,s[4]*n,s[5]*n,s[6]*n,0,s[8]*r,s[9]*r,s[10]*r,0,0,0,0,1,Ye.Matrix[0]),We.FromRotationMatrixToRef(Ye.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new He(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 this.constructor;return Xe.TransposeToRef(this,e),e}transposeToRef(e){return Xe.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,n,s){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]=n,this._m[r+3]=s,this.markAsUpdated(),this}scale(e){const t=new this.constructor;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}toNormalMatrix(e){const t=Ye.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return Xe.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 this.constructor;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=Ye.Vector3[0];if(!this.decompose(t))return Xe.IdentityToRef(e),e;const i=this._m,n=1/t._x,s=1/t._y,r=1/t._z;return Xe.FromValuesToRef(i[0]*n,i[1]*n,i[2]*n,0,i[4]*s,i[5]*s,i[6]*s,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 Xe;return Xe.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let n=0;n<16;n++)i._m[n]=e[n+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,n){for(let s=0;s<16;s++)n._m[s]=e[s+t]*i;return n.markAsUpdated(),n}static get IdentityReadOnly(){return Xe._IdentityReadOnly}static FromValuesToRef(e,t,i,n,s,r,a,o,l,h,c,d,u,f,_,p,m){const g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=n,g[4]=s,g[5]=r,g[6]=a,g[7]=o,g[8]=l,g[9]=h,g[10]=c,g[11]=d,g[12]=u,g[13]=f,g[14]=_,g[15]=p,m.markAsUpdated()}static FromValues(e,t,i,n,s,r,a,o,l,h,c,d,u,f,_,p){const m=new Xe,g=m._m;return g[0]=e,g[1]=t,g[2]=i,g[3]=n,g[4]=s,g[5]=r,g[6]=a,g[7]=o,g[8]=l,g[9]=h,g[10]=c,g[11]=d,g[12]=u,g[13]=f,g[14]=_,g[15]=p,m.markAsUpdated(),m}static Compose(e,t,i){const n=new Xe;return Xe.ComposeToRef(e,t,i,n),n}static ComposeToRef(e,t,i,n){const s=n._m,r=t._x,a=t._y,o=t._z,l=t._w,h=r+r,c=a+a,d=o+o,u=r*h,f=r*c,_=r*d,p=a*c,m=a*d,g=o*d,E=l*h,T=l*c,A=l*d,v=e._x,S=e._y,R=e._z;return s[0]=(1-(p+g))*v,s[1]=(f+A)*v,s[2]=(_-T)*v,s[3]=0,s[4]=(f-A)*S,s[5]=(1-(u+g))*S,s[6]=(m+E)*S,s[7]=0,s[8]=(_+T)*R,s[9]=(m-E)*R,s[10]=(1-(u+p))*R,s[11]=0,s[12]=i._x,s[13]=i._y,s[14]=i._z,s[15]=1,n.markAsUpdated(),n}static Identity(){const e=Xe.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 Xe.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=Xe.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 Xe;return Xe.RotationXToRef(e,t),t}static Invert(e){const t=new e.constructor;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),n=Math.cos(e);return Xe.FromValuesToRef(1,0,0,0,0,n,i,0,0,-i,n,0,0,0,0,1,t),t._updateIdentityStatus(1===n&&0===i),t}static RotationY(e){const t=new Xe;return Xe.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),n=Math.cos(e);return Xe.FromValuesToRef(n,0,-i,0,0,1,0,0,i,0,n,0,0,0,0,1,t),t._updateIdentityStatus(1===n&&0===i),t}static RotationZ(e){const t=new Xe;return Xe.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),n=Math.cos(e);return Xe.FromValuesToRef(n,i,0,0,-i,n,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===n&&0===i),t}static RotationAxis(e,t){const i=new Xe;return Xe.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const n=Math.sin(-t),s=Math.cos(-t),r=1-s;e.normalize();const a=i._m;return a[0]=e._x*e._x*r+s,a[1]=e._x*e._y*r-e._z*n,a[2]=e._x*e._z*r+e._y*n,a[3]=0,a[4]=e._y*e._x*r+e._z*n,a[5]=e._y*e._y*r+s,a[6]=e._y*e._z*r-e._x*n,a[7]=0,a[8]=e._z*e._x*r-e._y*n,a[9]=e._z*e._y*r+e._x*n,a[10]=e._z*e._z*r+s,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i){const n=ze.Dot(t,e),s=i._m;if(n<-.999)s[0]=-1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=-1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0;else{const i=ze.Cross(t,e),r=1/(1+n);s[0]=i._x*i._x*r+n,s[1]=i._y*i._x*r-i._z,s[2]=i._z*i._x*r+i._y,s[3]=0,s[4]=i._x*i._y*r+i._z,s[5]=i._y*i._y*r+n,s[6]=i._z*i._y*r-i._x,s[7]=0,s[8]=i._x*i._z*r-i._y,s[9]=i._y*i._z*r+i._x,s[10]=i._z*i._z*r+n,s[11]=0}return s[12]=0,s[13]=0,s[14]=0,s[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const n=new Xe;return Xe.RotationYawPitchRollToRef(e,t,i,n),n}static RotationYawPitchRollToRef(e,t,i,n){return We.RotationYawPitchRollToRef(e,t,i,Ye.Quaternion[0]),Ye.Quaternion[0].toRotationMatrix(n),n}static Scaling(e,t,i){const n=new Xe;return Xe.ScalingToRef(e,t,i,n),n}static ScalingToRef(e,t,i,n){return Xe.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,n),n._updateIdentityStatus(1===e&&1===t&&1===i),n}static Translation(e,t,i){const n=new Xe;return Xe.TranslationToRef(e,t,i,n),n}static TranslationToRef(e,t,i,n){return Xe.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,n),n._updateIdentityStatus(0===e&&0===t&&0===i),n}static Lerp(e,t,i){const n=new e.constructor;return Xe.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){const s=n._m,r=e.m,a=t.m;for(let e=0;e<16;e++)s[e]=r[e]*(1-i)+a[e]*i;return n.markAsUpdated(),n}static DecomposeLerp(e,t,i){const n=new e.constructor;return Xe.DecomposeLerpToRef(e,t,i,n),n}static DecomposeLerpToRef(e,t,i,n){const s=Ye.Vector3[0],r=Ye.Quaternion[0],a=Ye.Vector3[1];e.decompose(s,r,a);const o=Ye.Vector3[2],l=Ye.Quaternion[1],h=Ye.Vector3[3];t.decompose(o,l,h);const c=Ye.Vector3[4];ze.LerpToRef(s,o,i,c);const d=Ye.Quaternion[2];We.SlerpToRef(r,l,i,d);const u=Ye.Vector3[5];return ze.LerpToRef(a,h,i,u),Xe.ComposeToRef(c,d,u,n),n}static LookAtLH(e,t,i){const n=new Xe;return Xe.LookAtLHToRef(e,t,i,n),n}static LookAtLHToRef(e,t,i,n){const s=Ye.Vector3[0],r=Ye.Vector3[1],a=Ye.Vector3[2];t.subtractToRef(e,a),a.normalize(),ze.CrossToRef(i,a,s);const o=s.lengthSquared();0===o?s.x=1:s.normalizeFromLength(Math.sqrt(o)),ze.CrossToRef(a,s,r),r.normalize();const l=-ze.Dot(s,e),h=-ze.Dot(r,e),c=-ze.Dot(a,e);Xe.FromValuesToRef(s._x,r._x,a._x,0,s._y,r._y,a._y,0,s._z,r._z,a._z,0,l,h,c,1,n)}static LookAtRH(e,t,i){const n=new Xe;return Xe.LookAtRHToRef(e,t,i,n),n}static LookAtRHToRef(e,t,i,n){const s=Ye.Vector3[0],r=Ye.Vector3[1],a=Ye.Vector3[2];e.subtractToRef(t,a),a.normalize(),ze.CrossToRef(i,a,s);const o=s.lengthSquared();0===o?s.x=1:s.normalizeFromLength(Math.sqrt(o)),ze.CrossToRef(a,s,r),r.normalize();const l=-ze.Dot(s,e),h=-ze.Dot(r,e),c=-ze.Dot(a,e);return Xe.FromValuesToRef(s._x,r._x,a._x,0,s._y,r._y,a._y,0,s._z,r._z,a._z,0,l,h,c,1,n),n}static LookDirectionLH(e,t){const i=new Xe;return Xe.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const n=Ye.Vector3[0];n.copyFrom(e),n.scaleInPlace(-1);const s=Ye.Vector3[1];return ze.CrossToRef(t,n,s),Xe.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,n._x,n._y,n._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new Xe;return Xe.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const n=Ye.Vector3[2];return ze.CrossToRef(t,e,n),Xe.FromValuesToRef(n._x,n._y,n._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,n,s){const r=new Xe;return Xe.OrthoLHToRef(e,t,i,n,r,s),r}static OrthoLHToRef(e,t,i,n,s,r){const a=2/e,o=2/t,l=2/(n-i),h=-(n+i)/(n-i);return Xe.FromValuesToRef(a,0,0,0,0,o,0,0,0,0,l,0,0,0,h,1,s),r&&s.multiplyToRef(je,s),s._updateIdentityStatus(1===a&&1===o&&1===l&&0===h),s}static OrthoOffCenterLH(e,t,i,n,s,r,a){const o=new Xe;return Xe.OrthoOffCenterLHToRef(e,t,i,n,s,r,o,a),o}static OrthoOffCenterLHToRef(e,t,i,n,s,r,a,o){const l=2/(t-e),h=2/(n-i),c=2/(r-s),d=-(r+s)/(r-s),u=(e+t)/(e-t),f=(n+i)/(i-n);return Xe.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,0,u,f,d,1,a),o&&a.multiplyToRef(je,a),a.markAsUpdated(),a}static OrthoOffCenterRH(e,t,i,n,s,r,a){const o=new Xe;return Xe.OrthoOffCenterRHToRef(e,t,i,n,s,r,o,a),o}static OrthoOffCenterRHToRef(e,t,i,n,s,r,a,o){return Xe.OrthoOffCenterLHToRef(e,t,i,n,s,r,a,o),a._m[10]*=-1,a}static PerspectiveLH(e,t,i,n,s,r=0){const a=new Xe,o=2*i/e,l=2*i/t,h=(n+i)/(n-i),c=-2*n*i/(n-i),d=Math.tan(r);return Xe.FromValuesToRef(o,0,0,0,0,l,0,d,0,0,h,1,0,0,c,0,a),s&&a.multiplyToRef(je,a),a._updateIdentityStatus(!1),a}static PerspectiveFovLH(e,t,i,n,s,r=0,a=!1){const o=new Xe;return Xe.PerspectiveFovLHToRef(e,t,i,n,o,!0,s,r,a),o}static PerspectiveFovLHToRef(e,t,i,n,s,r=!0,a,o=0,l=!1){const h=i,c=n,d=1/Math.tan(.5*e),u=r?d/t:d,f=r?d:d*t,_=l&&0===h?-1:0!==c?(c+h)/(c-h):1,p=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,m=Math.tan(o);return Xe.FromValuesToRef(u,0,0,0,0,f,0,m,0,0,_,1,0,0,p,0,s),a&&s.multiplyToRef(je,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(e,t,i,n,s,r=!0,a,o=0){const l=1/Math.tan(.5*e),h=r?l/t:l,c=r?l:l*t,d=Math.tan(o);return Xe.FromValuesToRef(h,0,0,0,0,c,0,d,0,0,-i,1,0,0,1,0,s),a&&s.multiplyToRef(je,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(e,t,i,n,s,r=0,a=!1){const o=new Xe;return Xe.PerspectiveFovRHToRef(e,t,i,n,o,!0,s,r,a),o}static PerspectiveFovRHToRef(e,t,i,n,s,r=!0,a,o=0,l=!1){const h=i,c=n,d=1/Math.tan(.5*e),u=r?d/t:d,f=r?d:d*t,_=l&&0===h?1:0!==c?-(c+h)/(c-h):-1,p=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,m=Math.tan(o);return Xe.FromValuesToRef(u,0,0,0,0,f,0,m,0,0,_,-1,0,0,p,0,s),a&&s.multiplyToRef(je,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(e,t,i,n,s,r=!0,a,o=0){const l=1/Math.tan(.5*e),h=r?l/t:l,c=r?l:l*t,d=Math.tan(o);return Xe.FromValuesToRef(h,0,0,0,0,c,0,d,0,0,-i,-1,0,0,-1,0,s),a&&s.multiplyToRef(je,s),s._updateIdentityStatus(!1),s}static PerspectiveFovWebVRToRef(e,t,i,n,s=!1,r,a=0){const o=s?-1:1,l=Math.tan(e.upDegrees*Math.PI/180),h=Math.tan(e.downDegrees*Math.PI/180),c=Math.tan(e.leftDegrees*Math.PI/180),d=Math.tan(e.rightDegrees*Math.PI/180),u=2/(c+d),f=2/(l+h),_=Math.tan(a),p=n._m;return p[0]=u,p[1]=p[2]=p[3]=p[4]=0,p[5]=f,p[6]=0,p[7]=_,p[8]=(c-d)*u*.5,p[9]=-(l-h)*f*.5,p[10]=-i/(t-i),p[11]=1*o,p[12]=p[13]=p[15]=0,p[14]=-2*i*t/(i-t),r&&n.multiplyToRef(je,n),n.markAsUpdated(),n}static GetFinalMatrix(e,t,i,n,s,r){const a=e.width,o=e.height,l=e.x,h=e.y,c=Xe.FromValues(a/2,0,0,0,0,-o/2,0,0,0,0,r-s,0,l+a/2,o/2+h,s,1),d=new t.constructor;return t.multiplyToRef(i,d),d.multiplyToRef(n,d),d.multiplyToRef(c,d)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return Z.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 Z.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new e.constructor;return Xe.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=t._m,n=e.m;return i[0]=n[0],i[1]=n[4],i[2]=n[8],i[3]=n[12],i[4]=n[1],i[5]=n[5],i[6]=n[9],i[7]=n[13],i[8]=n[2],i[9]=n[6],i[10]=n[10],i[11]=n[14],i[12]=n[3],i[13]=n[7],i[14]=n[11],i[15]=n[15],t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new Xe;return Xe.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,n=e.normal.y,s=e.normal.z,r=-2*i,a=-2*n,o=-2*s;return Xe.FromValuesToRef(r*i+1,a*i,o*i,0,r*n,a*n+1,o*n,0,r*s,a*s,o*s+1,0,r*e.d,a*e.d,o*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,n){return Xe.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,n),n}static FromQuaternionToRef(e,t){const i=e._x*e._x,n=e._y*e._y,s=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*(n+s),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*(s+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*(n+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}Xe._UpdateFlagSeed=0,Xe._IdentityReadOnly=Xe.Identity();class Ye{}Ye.Vector3=Be.BuildTuple(11,ze.Zero),Ye.Matrix=Be.BuildTuple(2,Xe.Identity),Ye.Quaternion=Be.BuildTuple(3,We.Zero);class Ke{}Ke.Vector2=Be.BuildTuple(3,Ve.Zero),Ke.Vector3=Be.BuildTuple(13,ze.Zero),Ke.Vector4=Be.BuildTuple(3,He.Zero),Ke.Quaternion=Be.BuildTuple(2,We.Zero),Ke.Matrix=Be.BuildTuple(8,Xe.Identity),Se("BABYLON.Vector2",Ve),Se("BABYLON.Vector3",ze),Se("BABYLON.Vector4",He),Se("BABYLON.Matrix",Xe);const je=Xe.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class qe{constructor(){this.rootNodes=new Array,this.cameras=new Array,this.lights=new Array,this.meshes=new Array,this.skeletons=new Array,this.particleSystems=new Array,this.animations=[],this.animationGroups=new Array,this.multiMaterials=new Array,this.materials=new Array,this.morphTargetManagers=new Array,this.geometries=new Array,this.transformNodes=new Array,this.actionManagers=new Array,this.textures=new Array,this._environmentTexture=null,this.postProcesses=new Array}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,n){for(const s in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,s)&&this._BabylonFileParsers[s](e,t,i,n)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=new Array;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 Qe(e,t,i,n){var s,r=arguments.length,a=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(s=e[o])&&(a=(r<3?s(a):r>3?s(t,i,a):s(t,i))||a);return r>3&&a&&Object.defineProperty(t,i,a),a}function Ze(e){return Math.pow(e,Fe)}function Je(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function $e(e){return Math.pow(e,Ne)}function et(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}qe._BabylonFileParsers={},qe._IndividualBabylonFileParsers={},Object.create,Object.create;class tt{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|0),e=397*e^(255*this.b|0),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 tt.FromArrayToRef(e,t,this),this}toColor4(e=1){return new it(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 tt(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,this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}scale(e){return new tt(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,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,this}clampToRef(e=0,t=1,i){return i.r=Le.Clamp(this.r,e,t),i.g=Le.Clamp(this.g,e,t),i.b=Le.Clamp(this.b,e,t),this}add(e){return new tt(this.r+e.r,this.g+e.g,this.b+e.b)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,this}subtract(e){return new tt(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,this}clone(){return new tt(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)}toHexString(){const e=Math.round(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+Le.ToHex(e)+Le.ToHex(t)+Le.ToHex(i)}toHSV(){const e=new tt;return this.toHSVToRef(e),e}toHSVToRef(e){const t=this.r,i=this.g,n=this.b,s=Math.max(t,i,n),r=Math.min(t,i,n);let a=0,o=0;const l=s,h=s-r;0!==s&&(o=h/s),s!=r&&(s==t?(a=(i-n)/h,i=0&&r<=1?(o=s,l=a):r>=1&&r<=2?(o=a,l=s):r>=2&&r<=3?(l=s,h=a):r>=3&&r<=4?(l=a,h=s):r>=4&&r<=5?(o=a,h=s):r>=5&&r<=6&&(o=s,h=a);const c=i-s;n.set(o+c,l+c,h+c)}static FromHSV(e,t,i){const n=new tt(0,0,0);return tt.HSVtoRGBToRef(e,t,i,n),n}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new tt(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),n=parseInt(e.substring(5,7),16);return tt.FromInts(t,i,n)}static FromArray(e,t=0){return new tt(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 tt(e/255,t/255,i/255)}static Lerp(e,t,i){const n=new tt(0,0,0);return tt.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){n.r=e.r+(t.r-e.r)*i,n.g=e.g+(t.g-e.g)*i,n.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,n,s){const r=s*s,a=s*r,o=2*a-3*r+1,l=-2*a+3*r,h=a-2*r+s,c=a-r,d=e.r*o+i.r*l+t.r*h+n.r*c,u=e.g*o+i.g*l+t.g*h+n.g*c,f=e.b*o+i.b*l+t.b*h+n.b*c;return new tt(d,u,f)}static Hermite1stDerivative(e,t,i,n,s){const r=tt.Black();return this.Hermite1stDerivativeToRef(e,t,i,n,s,r),r}static Hermite1stDerivativeToRef(e,t,i,n,s,r){const a=s*s;r.r=6*(a-s)*e.r+(3*a-4*s+1)*t.r+6*(-a+s)*i.r+(3*a-2*s)*n.r,r.g=6*(a-s)*e.g+(3*a-4*s+1)*t.g+6*(-a+s)*i.g+(3*a-2*s)*n.g,r.b=6*(a-s)*e.b+(3*a-4*s+1)*t.b+6*(-a+s)*i.b+(3*a-2*s)*n.b}static Red(){return new tt(1,0,0)}static Green(){return new tt(0,1,0)}static Blue(){return new tt(0,0,1)}static Black(){return new tt(0,0,0)}static get BlackReadOnly(){return tt._BlackReadOnly}static White(){return new tt(1,1,1)}static Purple(){return new tt(.5,0,.5)}static Magenta(){return new tt(1,0,1)}static Yellow(){return new tt(1,1,0)}static Gray(){return new tt(.5,.5,.5)}static Teal(){return new tt(0,1,1)}static Random(){return new tt(Math.random(),Math.random(),Math.random())}}tt._BlackReadOnly=tt.Black();class it{constructor(e=0,t=0,i=0,n=1){this.r=e,this.g=t,this.b=i,this.a=n}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}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 it.FromArrayToRef(e,t,this),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 it(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new it(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,this}scale(e){return new it(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,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,this}clampToRef(e=0,t=1,i){return i.r=Le.Clamp(this.r,e,t),i.g=Le.Clamp(this.g,e,t),i.b=Le.Clamp(this.b,e,t),i.a=Le.Clamp(this.a,e,t),this}multiply(e){return new it(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}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|0),e=397*e^(255*this.b|0),e=397*e^(255*this.a|0),e}clone(){return new it(this.r,this.g,this.b,this.a)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,n){return this.r=e,this.g=t,this.b=i,this.a=n,this}set(e,t,i,n){return this.copyFromFloats(e,t,i,n)}toHexString(e=!1){const t=Math.round(255*this.r),i=Math.round(255*this.g),n=Math.round(255*this.b);if(e)return"#"+Le.ToHex(t)+Le.ToHex(i)+Le.ToHex(n);const s=Math.round(255*this.a);return"#"+Le.ToHex(t)+Le.ToHex(i)+Le.ToHex(n)+Le.ToHex(s)}toLinearSpace(e=!1){const t=new it;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=Je(this.r),e.g=Je(this.g),e.b=Je(this.b)):(e.r=Ze(this.r),e.g=Ze(this.g),e.b=Ze(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new it;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=et(this.r),e.g=et(this.g),e.b=et(this.b)):(e.r=$e(this.r),e.g=$e(this.g),e.b=$e(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new it(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),n=parseInt(e.substring(5,7),16),s=9===e.length?parseInt(e.substring(7,9),16):255;return it.FromInts(t,i,n,s)}static Lerp(e,t,i){const n=new it(0,0,0,0);return it.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){n.r=e.r+(t.r-e.r)*i,n.g=e.g+(t.g-e.g)*i,n.b=e.b+(t.b-e.b)*i,n.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,n,s){const r=s*s,a=s*r,o=2*a-3*r+1,l=-2*a+3*r,h=a-2*r+s,c=a-r,d=e.r*o+i.r*l+t.r*h+n.r*c,u=e.g*o+i.g*l+t.g*h+n.g*c,f=e.b*o+i.b*l+t.b*h+n.b*c,_=e.a*o+i.a*l+t.a*h+n.a*c;return new it(d,u,f,_)}static Hermite1stDerivative(e,t,i,n,s){const r=new it;return this.Hermite1stDerivativeToRef(e,t,i,n,s,r),r}static Hermite1stDerivativeToRef(e,t,i,n,s,r){const a=s*s;r.r=6*(a-s)*e.r+(3*a-4*s+1)*t.r+6*(-a+s)*i.r+(3*a-2*s)*n.r,r.g=6*(a-s)*e.g+(3*a-4*s+1)*t.g+6*(-a+s)*i.g+(3*a-2*s)*n.g,r.b=6*(a-s)*e.b+(3*a-4*s+1)*t.b+6*(-a+s)*i.b+(3*a-2*s)*n.b,r.a=6*(a-s)*e.a+(3*a-4*s+1)*t.a+6*(-a+s)*i.a+(3*a-2*s)*n.a}static FromColor3(e,t=1){return new it(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new it(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,n){return new it(e/255,t/255,i/255,n/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;inew it(0,0,0,0))),Se("BABYLON.Color3",tt),Se("BABYLON.Color4",it);const st={},rt={},at=function(e,t,i){const n=e();Oe&&Oe.HasTags(t)&&Oe.AddTagsTo(n,Oe.GetTags(t,!0));const s=ot(n);for(const e in s){const r=s[e],a=t[e],o=r.type;if(null!=a&&("uniqueId"!==e||gt.AllowLoadingUniqueId))switch(o){case 0:case 6:case 11:n[e]=a;break;case 1:n[e]=i||a.isRenderTarget?a:a.clone();break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:n[e]=i?a:a.clone()}}return n};function ot(e){const t=e.getClassName();if(rt[t])return rt[t];rt[t]={};const i=rt[t];let n=e,s=t;for(;s;){const e=st[s];for(const t in e)i[t]=e[t];let t,r=!1;do{if(t=Object.getPrototypeOf(n),!t.getClassName){r=!0;break}if(t.getClassName()!==s)break;n=t}while(t);if(r)break;s=t.getClassName(),n=t}return i}function lt(e,t){return(i,n)=>{const s=function(e){const t=e.getClassName();return st[t]||(st[t]={}),st[t]}(i);s[n]||(s[n]={type:e,sourceName:t})}}function ht(e,t=null){return function(e,t=null){return(i,n)=>{const s=t||"_"+n;Object.defineProperty(i,n,{get:function(){return this[s]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[s]!==t&&(this[s]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function ct(e){return lt(0,e)}function dt(e){return lt(1,e)}function ut(e){return lt(2,e)}function ft(e){return lt(3,e)}function _t(e){return lt(4,e)}function pt(e){return lt(5,e)}function mt(e){return lt(8,e)}class gt{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{let r=s;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];r=n?(...t)=>n(...t)?e(...t):s(...t):e}return e[t]=r,r(...i)}}gt.AllowLoadingUniqueId=!1,gt._ImageProcessingConfigurationParser=e=>{throw _("ImageProcessingConfiguration")},gt._FresnelParametersParser=e=>{throw _("FresnelParameters")},gt._ColorCurvesParser=e=>{throw _("ColorCurves")},gt._TextureParser=(e,t,i)=>{throw _("Texture")},Et.filter=function(e){return(t,i,n)=>Et(t,i,n,e)};class Tt{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._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;tthis._setDefaultValue(e)))}_setDefaultValue(e){var t,i,n,s,r;const a=null!==(n=null===(i=null===(t=this._externalProperties)||void 0===t?void 0:t[e])||void 0===i?void 0:i.type)&&void 0!==n?n:typeof this[e],o=null===(r=null===(s=this._externalProperties)||void 0===s?void 0:s[e])||void 0===r?void 0:r.default;switch(a){case"number":this[e]=null!=o?o:0;break;case"string":this[e]=null!=o?o:"";break;default:this[e]=null!=o&&o}}toString(){let e="";for(let t=0;tnew At),this)}serialize(){return gt.Serialize(this)}static Parse(e){return gt.Parse((()=>new At),e,null,null)}}Qe([ct()],At.prototype,"_globalHue",void 0),Qe([ct()],At.prototype,"_globalDensity",void 0),Qe([ct()],At.prototype,"_globalSaturation",void 0),Qe([ct()],At.prototype,"_globalExposure",void 0),Qe([ct()],At.prototype,"_highlightsHue",void 0),Qe([ct()],At.prototype,"_highlightsDensity",void 0),Qe([ct()],At.prototype,"_highlightsSaturation",void 0),Qe([ct()],At.prototype,"_highlightsExposure",void 0),Qe([ct()],At.prototype,"_midtonesHue",void 0),Qe([ct()],At.prototype,"_midtonesDensity",void 0),Qe([ct()],At.prototype,"_midtonesSaturation",void 0),Qe([ct()],At.prototype,"_midtonesExposure",void 0),gt._ColorCurvesParser=At.Parse;class vt extends Tt{constructor(){super(),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,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.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class St{constructor(){this.colorCurves=new At,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=St.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new it(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=St.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new s}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"}static PrepareUniforms(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&&At.PrepareUniforms(e),t.DITHER&&e.push("ditherIntensity")}static PrepareSamplers(e,t){t.COLORGRADING&&e.push("txColorTransform")}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled)return e.VIGNETTE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,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);e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===St._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType===St.TONEMAPPING_ACES?e.TONEMAPPING_ACES=!0:e.TONEMAPPING_ACES=!1,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&&At.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),n=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,n),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const s=null!=t?t:n/i;let r=Math.tan(.5*this.vignetteCameraFov),a=r*s;const o=Math.sqrt(a*r);a=Me.Mix(a,o,this.vignetteStretch),r=Me.Mix(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 gt.Clone((()=>new St),this)}serialize(){return gt.Serialize(this)}static Parse(e){const t=gt.Parse((()=>new St),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}}var Rt,Ct,xt,Mt,It,bt,yt,Pt;St.TONEMAPPING_STANDARD=0,St.TONEMAPPING_ACES=1,St._VIGNETTEMODE_MULTIPLY=0,St._VIGNETTEMODE_OPAQUE=1,Qe([lt(7,undefined)],St.prototype,"colorCurves",void 0),Qe([ct()],St.prototype,"_colorCurvesEnabled",void 0),Qe([dt("colorGradingTexture")],St.prototype,"_colorGradingTexture",void 0),Qe([ct()],St.prototype,"_colorGradingEnabled",void 0),Qe([ct()],St.prototype,"_colorGradingWithGreenDepth",void 0),Qe([ct()],St.prototype,"_colorGradingBGR",void 0),Qe([ct()],St.prototype,"_exposure",void 0),Qe([ct()],St.prototype,"_toneMappingEnabled",void 0),Qe([ct()],St.prototype,"_toneMappingType",void 0),Qe([ct()],St.prototype,"_contrast",void 0),Qe([ct()],St.prototype,"vignetteStretch",void 0),Qe([ct()],St.prototype,"vignetteCenterX",void 0),Qe([ct()],St.prototype,"vignetteCenterY",void 0),Qe([ct()],St.prototype,"vignetteWeight",void 0),Qe([mt()],St.prototype,"vignetteColor",void 0),Qe([ct()],St.prototype,"vignetteCameraFov",void 0),Qe([ct()],St.prototype,"_vignetteBlendMode",void 0),Qe([ct()],St.prototype,"_vignetteEnabled",void 0),Qe([ct()],St.prototype,"_ditheringEnabled",void 0),Qe([ct()],St.prototype,"_ditheringIntensity",void 0),Qe([ct()],St.prototype,"_skipFinalColorClamp",void 0),Qe([ct()],St.prototype,"_applyByPostProcess",void 0),Qe([ct()],St.prototype,"_isEnabled",void 0),gt._ImageProcessingConfigurationParser=St.Parse,ie.prototype.createUniformBuffer=function(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");const i=new j(t);return this.bindUniformBuffer(i),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),i.references=1,i},ie.prototype.createDynamicUniformBuffer=function(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");const i=new j(t);return this.bindUniformBuffer(i),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),i.references=1,i},ie.prototype.updateUniformBuffer=function(e,t,i,n){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===n?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+n)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+n)),this.bindUniformBuffer(null)},ie.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},ie.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},ie.prototype.bindUniformBlock=function(e,t,i){const n=e.program,s=this._gl.getUniformBlockIndex(n,t);4294967295!==s&&this._gl.uniformBlockBinding(n,s,i)};class Dt{constructor(e,t,i,n,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=null!=n?n:"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;e0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t?t*=i:t=t*i+(4-t)*i,n=[];for(let e=0;e1&&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&&(Dt._UpdatedUbosInFrame[this._name]||(Dt._UpdatedUbosInFrame[this._name]=0),Dt._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+10?(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 n=this._uniformLocations[e];if(void 0===n){if(this._buffer)return void c.Error("Cannot add an uniform after UBO has been created.");this.addUniform(e,i),n=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;ee[i]=t)),e}if(!(i instanceof Array||i instanceof Float32Array)||0!==this.byteOffset||i.length!==s){if(i instanceof Array){const e=this.byteOffset/4;return i.slice(e,e+s)}if(i instanceof ArrayBuffer)return new Float32Array(i,this.byteOffset,s);{let e=i.byteOffset+this.byteOffset;if(t){const t=new Float32Array(s),n=new Float32Array(i.buffer,e,s);return t.set(n),t}const n=e%4;return n&&(e=Math.max(0,e-n)),new Float32Array(i.buffer,e,s)}}return t?i.slice():i}getBuffer(){return this._buffer.getBuffer()}getStrideSize(){return this.byteStride/Lt.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/Lt.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*Lt.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e)}update(e){this._buffer.update(e)}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i)}dispose(){this._ownsBuffer&&this._buffer.dispose()}forEach(e,t){Lt.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}static DeduceStride(e){switch(e){case Lt.UVKind:case Lt.UV2Kind:case Lt.UV3Kind:case Lt.UV4Kind:case Lt.UV5Kind:case Lt.UV6Kind:return 2;case Lt.NormalKind:case Lt.PositionKind:return 3;case Lt.ColorKind:case Lt.MatricesIndicesKind:case Lt.MatricesIndicesExtraKind:case Lt.MatricesWeightsKind:case Lt.MatricesWeightsExtraKind:case Lt.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetTypeByteLength(e){switch(e){case Lt.BYTE:case Lt.UNSIGNED_BYTE:return 1;case Lt.SHORT:case Lt.UNSIGNED_SHORT:return 2;case Lt.INT:case Lt.UNSIGNED_INT:case Lt.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,n,s,r,a,o){if(e instanceof Array){let s=t/4;const a=i/4;for(let t=0;t{let i=e.getWorldMatrix();e.nonUniformScaling&&(Ke.Matrix[0].copyFrom(i),i=Ke.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(Ke.Matrix[1]),i=Ke.Matrix[1]),ze.TransformNormalToRef(t,i,t)};if(e&&s(this.pickedMesh,n),this.ray){const t=Ke.Vector3[0].copyFrom(n);e||s(this.pickedMesh,t),ze.Dot(t,this.ray.direction)>0&&n.negateInPlace()}return n.normalize(),n}getTextureCoordinates(){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(Lt.UVKind))return null;const e=this.pickedMesh.getIndices();if(!e)return null;const t=this.pickedMesh.getVerticesData(Lt.UVKind);if(!t)return null;let i=Ve.FromArray(t,2*e[3*this.faceId]),n=Ve.FromArray(t,2*e[3*this.faceId+1]),s=Ve.FromArray(t,2*e[3*this.faceId+2]);return i=i.scale(this.bu),n=n.scale(this.bv),s=s.scale(1-this.bu-this.bv),new Ve(i.x+n.x+s.x,i.y+n.y+s.y)}}class Ft{constructor(e,t,i,n,s,r){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=n,this.sourceEvent=s,this.additionalData=r}static CreateNew(e,t,i){const n=e.getScene();return new Ft(e,n.pointerX,n.pointerY,n.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,n){return new Ft(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,n)}static CreateNewFromScene(e,t){return new Ft(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,n){return new Ft(e,t.x,t.y,null,i,n)}}class wt{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[Lt.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[Lt.PositionKind]=new Lt(this._scene.getEngine(),e,Lt.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[Lt.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,n=0,s=0,r=!1){var a;const o=this._scene.getEngine();for(let l=0;lnull!=e))).length||!this._scene.postProcessesEnabled)return;const o=this._scene.getEngine();for(let l=0,h=n.length;lt._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),n=t.getMesh();return i.material&&n.material?i.material.uniqueId-n.material.uniqueId:i.uniqueId-n.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._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=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in Yt.Triggers)if(Object.prototype.hasOwnProperty.call(Yt.Triggers,t)&&parseInt(t)===e)return!0;return!1}}Yt.Triggers={};class Kt{}Kt.KEYDOWN=1,Kt.KEYUP=2;class jt{constructor(e,t){this.type=e,this.event=t}}class qt extends jt{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}}!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"}(Rt||(Rt={})),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"}(Ct||(Ct={})),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"}(xt||(xt={})),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"}(Mt||(Mt={})),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"}(It||(It={})),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"}(bt||(bt={})),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"}(yt||(yt={})),function(e){e[e.PointerMove=0]="PointerMove",e[e.PointerDown=1]="PointerDown",e[e.PointerUp=2]="PointerUp"}(Pt||(Pt={}));class Qt{}Qt.DOM_DELTA_PIXEL=0,Qt.DOM_DELTA_LINE=1,Qt.DOM_DELTA_PAGE=2;class Zt{static CreateDeviceEvent(e,t,i,n,s,r,a){switch(e){case Rt.Keyboard:return this._CreateKeyboardEvent(i,n,s,r);case Rt.Mouse:if(i===Ct.MouseWheelX||i===Ct.MouseWheelY||i===Ct.MouseWheelZ)return this._CreateWheelEvent(e,t,i,n,s,r);case Rt.Touch:return this._CreatePointerEvent(e,t,i,n,s,r,a);default:throw`Unable to generate event for device ${Rt[e]}`}}static _CreatePointerEvent(e,t,i,n,s,r,a){const o=this._CreateMouseEvent(e,t,i,n,s,r);return e===Rt.Mouse?(o.deviceType=Rt.Mouse,o.pointerId=1,o.pointerType="mouse"):(o.deviceType=Rt.Touch,o.pointerId=null!=a?a:t,o.pointerType="touch"),i===Ct.Move?o.type="pointermove":i>=Ct.LeftClick&&i<=Ct.RightClick&&(o.type=1===n?"pointerdown":"pointerup",o.button=i-2),o}static _CreateWheelEvent(e,t,i,n,s,r){const a=this._CreateMouseEvent(e,t,i,n,s,r);switch(a.type="wheel",a.deltaMode=Qt.DOM_DELTA_PIXEL,a.deltaX=0,a.deltaY=0,a.deltaZ=0,i){case Ct.MouseWheelX:a.deltaX=n;break;case Ct.MouseWheelY:a.deltaY=n;break;case Ct.MouseWheelZ:a.deltaZ=n}return a}static _CreateMouseEvent(e,t,i,n,s,r){const a=this._CreateEvent(r),o=s.pollInput(e,t,Ct.Horizontal),l=s.pollInput(e,t,Ct.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=s.pollInput(e,t,xt.DeltaHorizontal),a.movementY=s.pollInput(e,t,xt.DeltaVertical),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,s),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,n){const s=this._CreateEvent(n);return this._CheckNonCharacterKeys(s,i),s.deviceType=Rt.Keyboard,s.deviceSlot=0,s.inputIndex=e,s.type=1===t?"keydown":"keyup",s.key=String.fromCharCode(e),s.keyCode=e,s}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(Rt.Keyboard),n=i&&1===t.pollInput(Rt.Keyboard,0,18),s=i&&1===t.pollInput(Rt.Keyboard,0,17),r=i&&(1===t.pollInput(Rt.Keyboard,0,91)||1===t.pollInput(Rt.Keyboard,0,92)||1===t.pollInput(Rt.Keyboard,0,93)),a=i&&1===t.pollInput(Rt.Keyboard,0,16);e.altKey=n,e.ctrlKey=s,e.metaKey=r,e.shiftKey=a}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class Jt{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,n,s)=>{const r=Zt.CreateDeviceEvent(e,t,n,s,this);i(e,t,r)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===Rt.Mouse||e===Rt.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const $t=Object.keys(Ct).length/2;class ei{constructor(e,t,i,n){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Me.IsSafari(),this._usingMacOS=a()&&/(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._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=h.IsNavigatorAvailable()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=Me.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=n,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const n=this._inputs[e][t];if(!n)throw`Unable to find device ${Rt[e]}`;e>=Rt.DualShock&&e<=Rt.DualSense&&this._updateDevice(e,t,i);const s=n[i];if(void 0===s)throw`Unable to find input ${i} for device ${Rt[e]} in slot ${t}`;return i===Ct.Move&&Me.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),s}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=null==this?void 0: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{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Rt.Keyboard,0,255));const t=this._inputs[Rt.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(Rt.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Rt.Keyboard,0,255));const t=this._inputs[Rt.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=Zt.CreateDeviceEvent(Rt.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(Rt.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(Rt.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[Rt.Keyboard][0];for(let t=0;t{const t=this._getPointerType(e),i=t===Rt.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const n=this._inputs[t][i];if(n){const s=e;s.inputIndex=Ct.Move,n[Ct.Horizontal]=e.clientX,n[Ct.Vertical]=e.clientY,this._onInputChanged(t,i,s),this._usingSafari||-1===e.button||(s.inputIndex=e.button+2,n[e.button+2]=n[e.button+2]?0:1,this._onInputChanged(t,i,s))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===Rt.Mouse?0:e.pointerId;if(t===Rt.Touch){const t=this._activeTouchIds.indexOf(-1);if(!(t>=0))return void Me.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===Rt.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const n=this._inputs[t][i];if(n){const s=n[Ct.Horizontal],r=n[Ct.Vertical];if(t===Rt.Mouse){if(-1===this._mouseId&&(void 0===e.pointerId?this._mouseId=this._isUsingFirefox?0:1:this._mouseId=e.pointerId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}n[Ct.Horizontal]=e.clientX,n[Ct.Vertical]=e.clientY,n[e.button+2]=1;const a=e;a.inputIndex=e.button+2,this._onInputChanged(t,i,a),s===e.clientX&&r===e.clientY||(a.inputIndex=Ct.Move,this._onInputChanged(t,i,a))}},this._pointerUpEvent=e=>{var t,i,n,s,r;const a=this._getPointerType(e),o=a===Rt.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(a===Rt.Touch){if(-1===o)return;this._activeTouchIds[o]=-1}const l=null===(t=this._inputs[a])||void 0===t?void 0:t[o];if(l&&0!==l[e.button+2]){const t=l[Ct.Horizontal],h=l[Ct.Vertical];l[Ct.Horizontal]=e.clientX,l[Ct.Vertical]=e.clientY,l[e.button+2]=0;const c=e;t===e.clientX&&h===e.clientY||(c.inputIndex=Ct.Move,this._onInputChanged(a,o,c)),c.inputIndex=e.button+2,a===Rt.Mouse&&this._mouseId>=0&&(null===(n=(i=this._elementToAttachTo).hasPointerCapture)||void 0===n?void 0:n.call(i,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&(null===(r=(s=this._elementToAttachTo).hasPointerCapture)||void 0===r?void 0:r.call(s,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(a,o,c),a===Rt.Touch&&this._onDeviceDisconnected(a,o)}},this._pointerCancelEvent=e=>{var t,i,n,s;if("mouse"===e.pointerType){const e=this._inputs[Rt.Mouse][0];this._mouseId>=0&&(null===(i=(t=this._elementToAttachTo).hasPointerCapture)||void 0===i?void 0:i.call(t,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=Ct.LeftClick;t<=Ct.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=Zt.CreateDeviceEvent(Rt.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Rt.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);(null===(s=(n=this._elementToAttachTo).hasPointerCapture)||void 0===s?void 0:s.call(n,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[Rt.Touch][t][Ct.LeftClick]=0;const i=Zt.CreateDeviceEvent(Rt.Touch,t,Ct.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(Rt.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(Rt.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=()=>{var e,t,i,n,s;if(this.isDeviceAvailable(Rt.Mouse)){const i=this._inputs[Rt.Mouse][0];this._mouseId>=0&&(null===(t=(e=this._elementToAttachTo).hasPointerCapture)||void 0===t?void 0:t.call(e,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let e=Ct.LeftClick;e<=Ct.BrowserForward;e++)if(1===i[e]){i[e]=0;const t=Zt.CreateDeviceEvent(Rt.Mouse,0,e,0,this,this._elementToAttachTo);this._onInputChanged(Rt.Mouse,0,t)}}if(this.isDeviceAvailable(Rt.Touch)){const e=this._inputs[Rt.Touch];for(let t=0;t{const t=Rt.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,$t));const i=this._inputs[t][0];if(i){i[Ct.MouseWheelX]=e.deltaX||0,i[Ct.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[Ct.MouseWheelZ]=e.deltaZ||0;const n=e;0!==i[Ct.MouseWheelX]&&(n.inputIndex=Ct.MouseWheelX,this._onInputChanged(t,0,n)),0!==i[Ct.MouseWheelY]&&(n.inputIndex=Ct.MouseWheelY,this._onInputChanged(t,0,n)),0!==i[Ct.MouseWheelZ]&&(n.inputIndex=Ct.MouseWheelZ,this._onInputChanged(t,0,n))}},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(Rt.Mouse)){const e=this._inputs[Rt.Mouse][0];e[Ct.MouseWheelX]=0,e[Ct.MouseWheelY]=0,e[Ct.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 n=navigator.getGamepads()[t];if(n&&e===this._gamepads[t]){const s=this._inputs[e][t];i>=n.buttons.length?s[i]=n.axes[i-n.buttons.length].valueOf():s[i]=n.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?Rt.DualSense:Rt.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?Rt.Xbox:-1!==e.indexOf("057e")?Rt.Switch:Rt.Generic}_getPointerType(e){let t=Rt.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=Rt.Touch),t}}class ti{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new s,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class ii{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(Rt).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 n=new ti(this._deviceInputSystem,e,t);i._addDevice(n)}},n=(e,t)=>{var i;(null===(i=this._devices[e])||void 0===i?void 0:i[t])&&delete this._devices[e][t];for(const i of this._registeredManagers)i._removeDevice(e,t)},s=(e,t,i)=>{if(i)for(const n of this._registeredManagers)n._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new Jt(i,n,s):this._deviceInputSystem=new ei(e,i,n,s)}dispose(){this._deviceInputSystem.dispose()}}class ni{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(Rt).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new ii(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new s((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new s,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){var i,n;const s=null===(i=this._devices[e])||void 0===i?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(s),(null===(n=this._devices[e])||void 0===n?void 0:n[t])&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var n,s;null===(s=null===(n=this._devices[e])||void 0===n?void 0:n[t])||void 0===s||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case Rt.Keyboard:case Rt.Mouse:this._firstDevice[e]=0;break;case Rt.Touch:case Rt.DualSense:case Rt.DualShock:case Rt.Xbox:case Rt.Switch:case Rt.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i=Ct.MouseWheelX&&t.inputIndex<=Ct.MouseWheelZ?zt.POINTERWHEEL:zt.POINTERMOVE;let a;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,r)),e?(a=new Xt(r,t,e),this._setRayOnPointerInfo(e,t)):(a=new Xt(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,Xe.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 n=this._scene,s=new Wt(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(s.originalPickingInfo=e,s.ray=e.ray,e.originMesh&&(s.nearInteractionPickingInfo=e)),n.onPrePointerObservable.notifyObservers(s,i),!!s.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,!1,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const n=i.getEngine().getInputElement();if(null==e?void 0:e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&n&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(n.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=Ct.Move,this._checkPrePointerObservable(e,i,zt.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,zt.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(null==e?void 0:e.pickedMesh){this._pickedDownMesh=e.pickedMesh;const n=e.pickedMesh._getActionManagerForTrigger();if(n){if(n.hasPickTriggers)switch(n.processTrigger(5,Ft.CreateNew(e.pickedMesh,t)),t.button){case 0:n.processTrigger(2,Ft.CreateNew(e.pickedMesh,t));break;case 1:n.processTrigger(4,Ft.CreateNew(e.pickedMesh,t));break;case 2:n.processTrigger(3,Ft.CreateNew(e.pickedMesh,t))}n.hasSpecificTrigger(8)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);(null==e?void 0:e.pickedMesh)&&n&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>ri.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,n.processTrigger(8,Ft.CreateNew(e.pickedMesh,t)))}),ri.LongPressDelay)}}else for(const n of i._pointerDownStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let n;const s=zt.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,s),n=new Xt(s,t,e),this._setRayOnPointerInfo(e,t)):n=new Xt(s,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(n,s)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const n=new PointerEvent("pointerup",t);n.inputIndex=Ct.Move;const s=new si;i?s.doubleClick=!0:s.singleClick=!0,this._checkPrePointerObservable(e,n,zt.POINTERUP)||this._processPointerUp(e,n,s)}_processPointerUp(e,t,i){const n=this._scene;if(null==e?void 0:e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(n.onPointerPick&&n.onPointerPick(t,e),i.singleClick&&!i.ignore&&n.onPointerObservable.observers.length>this._cameraObserverCount)){const i=zt.POINTERPICK,s=new Xt(i,t,e);this._setRayOnPointerInfo(e,t),n.onPointerObservable.notifyObservers(s,i)}const s=e.pickedMesh._getActionManagerForTrigger();if(s&&!i.ignore){s.processTrigger(7,Ft.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&s.processTrigger(1,Ft.CreateNew(e.pickedMesh,t,e));const n=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&n&&n.processTrigger(6,Ft.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const s of n._pointerUpStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,Ft.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const s=new Xt(zt.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),n.onPointerObservable.notifyObservers(s,zt.POINTERUP),n.onPointerUp&&n.onPointerUp(t,e,zt.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let s=0;if(i.singleClick?s=zt.POINTERTAP:i.doubleClick&&(s=zt.POINTERDOUBLETAP),s){const i=new Xt(s,t,e);n.onPointerObservable.hasObservers()&&n.onPointerObservable.hasSpecificMask(s)&&n.onPointerObservable.notifyObservers(i,s)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,n=null){const s=this._scene,r=s.getEngine();n||(n=r.getInputElement()),this._alreadyAttached&&this.detachControl(),n&&(this._alreadyAttachedTo=n),this._deviceSourceManager=new ni(r),this._initActionManager=e=>{if(!this._meshPickProceed){const t=s.skipPointerUpPicking||0===s._registeredActions&&!this._checkForPicking()&&!s.onPointerUp?null:s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerUpPredicate,!1,s.cameraToUseForPointers);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>ri.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=zt.POINTERTAP,n=new Xt(i,t,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(i)&&s.onPointerObservable.notifyObservers(n,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,n)=>{var s,r;const a=new si;this._currentPickResult=null;let o=null,l=e.hasSpecificMask(zt.POINTERPICK)||t.hasSpecificMask(zt.POINTERPICK)||e.hasSpecificMask(zt.POINTERTAP)||t.hasSpecificMask(zt.POINTERTAP)||e.hasSpecificMask(zt.POINTERDOUBLETAP)||t.hasSpecificMask(zt.POINTERDOUBLETAP);!l&&Yt&&(o=this._initActionManager(o,a),o&&(l=o.hasPickTriggers));let h=!1;if(l){const l=i.button;if(a.hasSwiped=this._isPointerSwiping(),!a.hasSwiped){let c=!ri.ExclusiveDoubleClickMode;if(c||(c=!e.hasSpecificMask(zt.POINTERDOUBLETAP)&&!t.hasSpecificMask(zt.POINTERDOUBLETAP),c&&!Yt.HasSpecificTrigger(6)&&(o=this._initActionManager(o,a),o&&(c=!o.hasSpecificTrigger(6)))),c)(Date.now()-this._previousStartingPointerTime>ri.DoubleClickDelay||l!==this._previousButtonPressed)&&(a.singleClick=!0,n(a,this._currentPickResult),h=!0);else{const e={evt:i,clickInfo:a,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,l,a,n),ri.DoubleClickDelay)};this._delayedClicks[l]=e}let d=e.hasSpecificMask(zt.POINTERDOUBLETAP)||t.hasSpecificMask(zt.POINTERDOUBLETAP);!d&&Yt.HasSpecificTrigger(6)&&(o=this._initActionManager(o,a),o&&(d=o.hasSpecificTrigger(6))),d&&(l===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(void 0===e.pointerId&&(e.pointerId=0),this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>ri.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>ri.DragMovementThreshold),this._checkPrePointerObservable(null,e,e.inputIndex>=Ct.MouseWheelX&&e.inputIndex<=Ct.MouseWheelZ?zt.POINTERWHEEL:zt.POINTERMOVE))return;if(!s.cameraToUseForPointers&&!s.activeCamera)return;if(s.skipPointerMovePicking)return void this._processPointerMove(new Nt,e);s.pointerMovePredicate||(s.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||s.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!s.cameraToUseForPointers||0!=(s.cameraToUseForPointers.layerMask&e.layerMask)));const t=s._registeredActions>0?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{var t;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,void 0===e.pointerId&&(e.pointerId=0),ri.ExclusiveDoubleClickMode)for(let i=0;ie.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||0!=(s.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,i=s.skipPointerDownPicking||0===s._registeredActions&&!this._checkForPicking()&&!s.onPointerDown?new Nt:s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerDownPredicate,!1,s.cameraToUseForPointers),this._processPointerDown(i,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,void 0===e.pointerId&&(e.pointerId=0),this._updatePointerPosition(e),s.preventDefaultOnPointerUp&&n&&(e.preventDefault(),n.focus()),this._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,e,((t,i)=>{if(s.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,zt.POINTERUP))return void(this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1));t.hasSwiped||(t.singleClick&&s.onPrePointerObservable.hasSpecificMask(zt.POINTERTAP)&&this._checkPrePointerObservable(null,e,zt.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&s.onPrePointerObservable.hasSpecificMask(zt.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,zt.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(s.cameraToUseForPointers||s.activeCamera)&&(s.pointerUpPredicate||(s.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||0!=(s.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(Yt&&Yt.HasTriggers||this._checkForPicking()||s.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=Kt.KEYDOWN;if(s.onPreKeyboardObservable.hasObservers()){const i=new qt(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){const i=new jt(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(14,Ft.CreateNewFromScene(s,e))},this._onKeyUp=e=>{const t=Kt.KEYUP;if(s.onPreKeyboardObservable.hasObservers()){const i=new qt(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){const i=new jt(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(15,Ft.CreateNewFromScene(s,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((n=>{n.deviceType===Rt.Mouse?n.onInputChangedObservable.add((s=>{s.inputIndex===Ct.LeftClick||s.inputIndex===Ct.MiddleClick||s.inputIndex===Ct.RightClick||s.inputIndex===Ct.BrowserBack||s.inputIndex===Ct.BrowserForward?t&&1===n.getInput(s.inputIndex)?this._onPointerDown(s):e&&0===n.getInput(s.inputIndex)&&this._onPointerUp(s):i&&(s.inputIndex===Ct.Move?this._onPointerMove(s):s.inputIndex!==Ct.MouseWheelX&&s.inputIndex!==Ct.MouseWheelY&&s.inputIndex!==Ct.MouseWheelZ||this._onPointerMove(s))})):n.deviceType===Rt.Touch?n.onInputChangedObservable.add((s=>{s.inputIndex===Ct.LeftClick&&(t&&1===n.getInput(s.inputIndex)?(this._onPointerDown(s),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===n.getInput(s.inputIndex)&&(this._onPointerUp(s),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&s.inputIndex===Ct.Move&&this._onPointerMove(s)})):n.deviceType===Rt.Keyboard&&n.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,n){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const s=this._meshUnderPointerId[t];let r;s&&(r=s._getActionManagerForTrigger(10),r&&r.processTrigger(10,Ft.CreateNew(s,n,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,r=e._getActionManagerForTrigger(9),r&&r.processTrigger(9,Ft.CreateNew(e,n,{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]}}ri.DragMovementThreshold=10,ri.LongPressDelay=500,ri.DoubleClickDelay=300,ri.ExclusiveDoubleClickMode=!1;class ai{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){ai.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){ai.Enabled&&(this._startMonitoringTime=f.Now)}endMonitoring(e=!0){if(!ai.Enabled)return;e&&this.fetchNewFrame();const t=f.Now;this._current=t-this._startMonitoringTime,e&&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=f.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}ai.Enabled=!0;class oi{constructor(e,t,i,n){this.normal=new ze(e,t,i),this.d=n}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new oi(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^(0|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=oi._TmpMatrix;e.invertToRef(t);const i=t.m,n=this.normal.x,s=this.normal.y,r=this.normal.z,a=this.d,o=n*i[0]+s*i[1]+r*i[2]+a*i[3],l=n*i[4]+s*i[5]+r*i[6]+a*i[7],h=n*i[8]+s*i[9]+r*i[10]+a*i[11],c=n*i[12]+s*i[13]+r*i[14]+a*i[15];return new oi(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 n=t.x-e.x,s=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=s*l-r*o,c=r*a-n*l,d=n*o-s*a,u=Math.sqrt(h*h+c*c+d*d);let f;return f=0!==u?1/u:0,this.normal.x=h*f,this.normal.y=c*f,this.normal.z=d*f,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return ze.Dot(this.normal,e)<=t}signedDistanceTo(e){return ze.Dot(e,this.normal)+this.d}static FromArray(e){return new oi(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const n=new oi(0,0,0,0);return n.copyFromPoints(e,t,i),n}static FromPositionAndNormal(e,t){const i=new oi(0,0,0,0);return t.normalize(),i.normal=t,i.d=-(t.x*e.x+t.y*e.y+t.z*e.z),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const n=-(t.x*e.x+t.y*e.y+t.z*e.z);return ze.Dot(i,t)+n}}oi._TmpMatrix=Xe.Identity();class li{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new oi(0,0,0,0));return li.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){li.GetNearPlaneToRef(e,t[0]),li.GetFarPlaneToRef(e,t[1]),li.GetLeftPlaneToRef(e,t[2]),li.GetRightPlaneToRef(e,t[3]),li.GetTopPlaneToRef(e,t[4]),li.GetBottomPlaneToRef(e,t[5])}}class hi{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}hi._UniqueIdCounter=1;class ci{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}var di,ui,fi,_i;ci.FALLOFF_DEFAULT=0,ci.FALLOFF_PHYSICAL=1,ci.FALLOFF_GLTF=2,ci.FALLOFF_STANDARD=3,ci.LIGHTMAP_DEFAULT=0,ci.LIGHTMAP_SPECULAR=1,ci.LIGHTMAP_SHADOWSONLY=2,ci.INTENSITYMODE_AUTOMATIC=0,ci.INTENSITYMODE_LUMINOUSPOWER=1,ci.INTENSITYMODE_LUMINOUSINTENSITY=2,ci.INTENSITYMODE_ILLUMINANCE=3,ci.INTENSITYMODE_LUMINANCE=4,ci.LIGHTTYPEID_POINTLIGHT=0,ci.LIGHTTYPEID_DIRECTIONALLIGHT=1,ci.LIGHTTYPEID_SPOTLIGHT=2,ci.LIGHTTYPEID_HEMISPHERICLIGHT=3,function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(di||(di={}));class pi extends qe{static DefaultMaterialFactory(e){throw _("StandardMaterial")}static CollisionCoordinatorFactory(){throw _("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case di.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case di.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case di.Aggressive: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(16))}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(16))}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 unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return ri.DragMovementThreshold}static set DragMovementThreshold(e){ri.DragMovementThreshold=e}static get LongPressDelay(){return ri.LongPressDelay}static set LongPressDelay(e){ri.LongPressDelay=e}static get DoubleClickDelay(){return ri.DoubleClickDelay}static set DoubleClickDelay(e){ri.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return ri.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){ri.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){var n;const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:null!==(n=this.activeCamera.globalPosition)&&void 0!==n?n:this.activeCamera.devicePosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return Ke.Vector4[0].set(s.x,s.y,s.z,r?-1:1),e&&(i?e.setFloat3(t,Ke.Vector4[0].x,Ke.Vector4[0].y,Ke.Vector4[0].z):e.setVector4(t,Ke.Vector4[0])),Ke.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(16))}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(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}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(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=ke(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=pi.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=pi.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 ri(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new it(.2,.2,.3,1),this.ambientColor=new tt(0,0,0),this.environmentIntensity=1,this._performancePriority=di.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new s,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=new Array,this.onDisposeObservable=new s,this._onDisposeObserver=null,this.onBeforeRenderObservable=new s,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new s,this.onAfterRenderCameraObservable=new s,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new s,this.onAfterAnimationsObservable=new s,this.onBeforeDrawPhaseObservable=new s,this.onAfterDrawPhaseObservable=new s,this.onReadyObservable=new s,this.onBeforeCameraRenderObservable=new s,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new s,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new s,this.onAfterActiveMeshesEvaluationObservable=new s,this.onBeforeParticlesRenderingObservable=new s,this.onAfterParticlesRenderingObservable=new s,this.onDataLoadedObservable=new s,this.onNewCameraAddedObservable=new s,this.onCameraRemovedObservable=new s,this.onNewLightAddedObservable=new s,this.onLightRemovedObservable=new s,this.onNewGeometryAddedObservable=new s,this.onGeometryRemovedObservable=new s,this.onNewTransformNodeAddedObservable=new s,this.onTransformNodeRemovedObservable=new s,this.onNewMeshAddedObservable=new s,this.onMeshRemovedObservable=new s,this.onNewSkeletonAddedObservable=new s,this.onSkeletonRemovedObservable=new s,this.onNewMaterialAddedObservable=new s,this.onNewMultiMaterialAddedObservable=new s,this.onMaterialRemovedObservable=new s,this.onMultiMaterialRemovedObservable=new s,this.onNewTextureAddedObservable=new s,this.onTextureRemovedObservable=new s,this.onBeforeRenderTargetsRenderObservable=new s,this.onAfterRenderTargetsRenderObservable=new s,this.onBeforeStepObservable=new s,this.onAfterStepObservable=new s,this.onActiveCameraChanged=new s,this.onActiveCamerasChanged=new s,this.onBeforeRenderingGroupObservable=new s,this.onAfterRenderingGroupObservable=new s,this.onMeshImportedObservable=new s,this.onAnimationFileImportedObservable=new s,this._registeredForLateAnimationBindings=new ye(256),this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1,this.onPrePointerObservable=new s,this.onPointerObservable=new s,this.onPreKeyboardObservable=new s,this.onKeyboardObservable=new s,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=pi.FOGMODE_NONE,this.fogColor=new tt(.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 ze(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=new Array,this.importedMeshesFiles=new Array,this.probesEnabled=!0,this._meshesForIntersections=new ye(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new ai,this._activeIndices=new ai,this._activeParticles=new ai,this._activeBones=new ai,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 be(256),this._processedMaterials=new be(256),this._renderTargets=new ye(256),this._materialsRenderTargets=new ye(256),this._activeParticleSystems=new be(256),this._activeSkeletons=new ye(32),this._softwareSkinnedMeshes=new ye(32),this._activeAnimatables=new Array,this._transformMatrix=Xe.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=Vt.Create(),this._beforeClearStage=Vt.Create(),this._beforeRenderTargetClearStage=Vt.Create(),this._gatherRenderTargetsStage=Vt.Create(),this._gatherActiveCameraRenderTargetsStage=Vt.Create(),this._isReadyForMeshStage=Vt.Create(),this._beforeEvaluateActiveMeshStage=Vt.Create(),this._evaluateSubMeshStage=Vt.Create(),this._preActiveMeshStage=Vt.Create(),this._cameraDrawRenderTargetStage=Vt.Create(),this._beforeCameraDrawStage=Vt.Create(),this._beforeRenderTargetDrawStage=Vt.Create(),this._beforeRenderingGroupDrawStage=Vt.Create(),this._beforeRenderingMeshStage=Vt.Create(),this._afterRenderingMeshStage=Vt.Create(),this._afterRenderingGroupDrawStage=Vt.Create(),this._afterCameraDrawStage=Vt.Create(),this._afterCameraPostProcessStage=Vt.Create(),this._afterRenderTargetDrawStage=Vt.Create(),this._afterRenderTargetPostProcessStage=Vt.Create(),this._afterRenderStage=Vt.Create(),this._pointerMoveStage=Vt.Create(),this._pointerDownStage=Vt.Create(),this._pointerUpStage=Vt.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=new Array;const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};this._engine=e||m.LastCreatedEngine,i.virtual?this._engine._virtualScenes.push(this):(m._LastCreatedScene=this,this._engine.scenes.push(this)),this._uid=null,this._renderingManager=new kt(this),wt&&(this.postProcessManager=new wt(this)),r()&&this.attachControl(),this._createUbo(),St&&(this._imageProcessingConfiguration=new St),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,t&&t.virtual||this._engine.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.bind(this),this.getActiveSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this),this.getIntersectingSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this),this.getCollidingSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this)}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();let n=!0;for(this._pendingData.length>0&&(n=!1),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;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(!n)return!1;if(!i.areAllEffectsReady())return!1;if(e)for(t=0;t0){for(const e of this.activeCameras)if(!e.isReady(!0))return!1}else if(this.activeCamera&&!this.activeCamera.isReady(!0))return!1;for(const e of this.particleSystems)if(!e.isReady())return!1;return!0}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=f.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,n){i||n||!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?li.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=li.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,n):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 Dt(this._engine,void 0,!1,null!=e?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 hi.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&&tt.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=0;t--)if(this.meshes[t].id===e)return this.meshes[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 n=this.getLightById(e);if(n)return n;const s=this.getCameraById(e);if(s)return s;return this.getBoneById(e)||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const n=this.getLightByName(e);if(n)return n;const s=this.getCameraByName(e);if(s)return s;return this.getBoneByName(e)||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(this.activeCamera){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=s,this._skipEvaluateActiveMeshesCompletely=e,n)for(let e=0;ee.dispose()))}_evaluateActiveMeshes(){var e;if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode)return void(this._activeMeshes.length>0&&(null===(e=this.activeCamera)||void 0===e||e._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;t0&&0!=(i.layerMask&this.activeCamera.layerMask)&&(this._skipFrustumClipping||i.alwaysSelectAsActiveMesh||i.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(i),this.activeCamera._activeMeshes.push(i),n!==i&&n._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(i);i._activate(this._renderId,!1)&&(i.isAnInstance?i._internalAbstractMeshDataInfo._actAsRegularMesh&&(n=i):n._internalAbstractMeshDataInfo._onlyForInstances=!1,n._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(i,n)),i._postActivate()}}if(this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){const n=this.getActiveSubMeshCandidates(t),s=n.length;i=i||1===s;for(let r=0;r0&&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 o=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Me.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)o=e.action(this.activeCamera)||o;this._intermediateRendering=!1}this._engine.currentRenderPassId=null!==(r=null!==(s=null===(n=e.outputRenderTarget)||void 0===n?void 0:n.renderPassId)&&void 0!==s?s:e.renderPassId)&&void 0!==r?r:0,o&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),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),a.snapshotRendering&&1===a.snapshotRenderingMode&&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(0===e.cameraRigMode||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-1&&(13===i.trigger&&i._executeCurrent(Ft.CreateNew(t,void 0,n)),t.actionManager.hasSpecificTrigger(13,(e=>{const t=e.mesh?e.mesh:e;return n===t}))&&13!==i.trigger||t._intersectionsInProgress.splice(r,1))}}}}_advancePhysicsEngineStep(e){}_animate(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(pi.MinDeltaTime,Math.min(this._engine.getDeltaTime(),pi.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let n=0;const s=this._engine.getLockstepMaxSteps();let r=Math.floor(e/t);for(r=Math.min(r,s);e>0&&n0)for(let e=0;e0),this._intermediateRendering=!0;for(let e=0;e0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=null!==(s=null==a?void 0:a.renderPassId)&&void 0!==s?s:0,this.activeCamera=a,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!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;e0);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;ee.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=null!=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!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const n=e.getBoundingInfo(),s=n.boundingBox.minimumWorld,r=n.boundingBox.maximumWorld;ze.CheckExtends(s,t,i),ze.CheckExtends(r,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,n,s=!1){throw _("Ray")}createPickingRayToRef(e,t,i,n,s,r=!1,a=!1){throw _("Ray")}createPickingRayInCameraSpace(e,t,i){throw _("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,n){throw _("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,n,s,r){return new Nt}pickWithBoundingInfo(e,t,i,n,s){return new Nt}pickWithRay(e,t,i,n){throw _("Ray")}multiPick(e,t,i,n,s){throw _("Ray")}multiPickWithRay(e,t,i){throw _("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();this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(void 0===t)return e;const n=[];i=i||(e=>{});for(const s in e){const r=e[s];Oe&&Oe.MatchesQuery(r,t)&&(n.push(r),i(r))}return n}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,n=null){this._renderingManager.setRenderingOrder(e,t,i,n)}setRenderingAutoClearDepthStencil(e,t,i=!0,n=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,n)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,n,s,r,a){const o=fe(e,t,i,n?this.offlineProvider:void 0,s,r,a);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}_loadFileAsync(e,t,i,n,s){return new Promise(((r,a)=>{this._loadFile(e,(e=>{r(e)}),t,i,n,((e,t)=>{a(t)}),s)}))}_requestFile(e,t,i,n,s,r,a){const o=_e(e,t,i,n?this.offlineProvider:void 0,s,r,a);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}_requestFileAsync(e,t,i,n,s){return new Promise(((r,a)=>{this._requestFile(e,(e=>{r(e)}),t,i,n,(e=>{a(e)}),s)}))}_readFile(e,t,i,n,s){const r=ue(e,t,i,n,s);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(((n,s)=>{this._readFile(e,(e=>{n(e)}),t,i,(e=>{s(e)}))}))}getPerfCollector(){throw _("performanceViewerSceneExtension")}}pi.FOGMODE_NONE=0,pi.FOGMODE_EXP=1,pi.FOGMODE_EXP2=2,pi.FOGMODE_LINEAR=3,pi.MinDeltaTime=1,pi.MaxDeltaTime=1e3,pi.prototype.setActiveCameraByID=function(e){return this.setActiveCameraById(e)},pi.prototype.getLastMaterialByID=function(e){return this.getLastMaterialById(e)},pi.prototype.getMaterialByID=function(e){return this.getMaterialById(e)},pi.prototype.getTextureByUniqueID=function(e){return this.getTextureByUniqueId(e)},pi.prototype.getCameraByID=function(e){return this.getCameraById(e)},pi.prototype.getCameraByUniqueID=function(e){return this.getCameraByUniqueId(e)},pi.prototype.getBoneByID=function(e){return this.getBoneById(e)},pi.prototype.getLightByID=function(e){return this.getLightById(e)},pi.prototype.getLightByUniqueID=function(e){return this.getLightByUniqueId(e)},pi.prototype.getParticleSystemByID=function(e){return this.getParticleSystemById(e)},pi.prototype.getGeometryByID=function(e){return this.getGeometryById(e)},pi.prototype.getMeshByID=function(e){return this.getMeshById(e)},pi.prototype.getMeshesByID=function(e){return this.getMeshesById(e)},pi.prototype.getTransformNodeByID=function(e){return this.getTransformNodeById(e)},pi.prototype.getTransformNodeByUniqueID=function(e){return this.getTransformNodeByUniqueId(e)},pi.prototype.getTransformNodesByID=function(e){return this.getTransformNodesById(e)},pi.prototype.getMeshByUniqueID=function(e){return this.getMeshByUniqueId(e)},pi.prototype.getLastMeshByID=function(e){return this.getLastMeshById(e)},pi.prototype.getLastEntryByID=function(e){return this.getLastEntryById(e)},pi.prototype.getNodeByID=function(e){return this.getNodeById(e)},pi.prototype.getLastSkeletonByID=function(e){return this.getLastSkeletonById(e)};class mi{static CreateScene(i){const n=e(),s=new t,r=new pi(n.engine);return i(r,n,s),r}}class gi{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new s,this._onClonedObservable=new s}}class Ei{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,n){const s=this._NodeConstructors[e];return s?s(t,i,n):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._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){this._isDirty=!1,this._nodeDataStorage=new gi,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new s,this._parentContainer=null,this.animations=new Array,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=Xe.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new s,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()}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={},this._cache.parent=void 0}updateCache(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,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._cache.parent!==this._parentNode?(this._cache.parent=this._parentNode,!1):!(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 n=0;n(!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{throw _("AnimationRange")},Ei._NodeConstructors={},Qe([ct()],Ei.prototype,"name",void 0),Qe([ct()],Ei.prototype,"id",void 0),Qe([ct()],Ei.prototype,"uniqueId",void 0),Qe([ct()],Ei.prototype,"state",void 0),Qe([ct()],Ei.prototype,"metadata",void 0);class Ti extends Ei{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())}constructor(e,t){super(e,t),this.diffuse=new tt(1,1,1),this.specular=new tt(1,1,1),this.falloffType=Ti.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=Ti.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 Dt(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=new Array,this.excludedMeshes=new Array,this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,n,s=!0){var r;const a=e.toString();let o=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+a),this._renderId!==t.getRenderId()||this._lastUseSpecular!==n||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=n;const e=this.getScaledIntensity();this.transferToEffect(i,a),this.diffuse.scaleToRef(e,nt.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",nt.Color3[0],this.range,a),n&&(this.specular.scaleToRef(e,nt.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",nt.Color3[1],this.radius,a)),o=!0}if(this.transferTexturesToEffect(i,a),t.shadowsEnabled&&this.shadowEnabled&&s){const e=null!==(r=this.getShadowGenerator(t.activeCamera))&&void 0!==r?r:this.getShadowGenerator();e&&(e.bindShadowLight(a,i),o=!0)}o?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;i0&&-1===this.includedOnlyMeshes.indexOf(e)||this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)||0!==this.includeOnlyWithLayerMask&&0==(this.includeOnlyWithLayerMask&e.layerMask)||0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(const e of this.getScene().meshes)e._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const i=Ti.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const n=gt.Clone(i,this);return e&&(n.name=e),t&&(n.parent=t),n.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(n),n}serialize(){const e=gt.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)}))),gt.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return Ei.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){const i=Ti.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const n=gt.Parse(i,e,t);if(e.excludedMeshesIds&&(n._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(n._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(n.falloffType=e.falloffType),void 0!==e.lightmapMode&&(n.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{const n=t.apply(e,i);for(const e of i)e._resyncLightSource(this);return n};const i=e.splice;e.splice=(t,n)=>{const s=i.apply(e,[t,n]);for(const e of s)e._resyncLightSource(this);return s};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...i)=>{const n=t.apply(e,i);return this._resyncMeshes(),n};const i=e.splice;e.splice=(t,n)=>{const s=i.apply(e,[t,n]);return this._resyncMeshes(),s},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===Ti.INTENSITYMODE_AUTOMATIC&&(i=t===Ti.LIGHTTYPEID_DIRECTIONALLIGHT?Ti.INTENSITYMODE_ILLUMINANCE:Ti.INTENSITYMODE_LUMINOUSINTENSITY),t){case Ti.LIGHTTYPEID_POINTLIGHT:case Ti.LIGHTTYPEID_SPOTLIGHT:switch(i){case Ti.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Ti.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Ti.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case Ti.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Ti.INTENSITYMODE_ILLUMINANCE:e=1;break;case Ti.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001),e=2*Math.PI*(1-Math.cos(t));break}}break;case Ti.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Ti.FALLOFF_DEFAULT=ci.FALLOFF_DEFAULT,Ti.FALLOFF_PHYSICAL=ci.FALLOFF_PHYSICAL,Ti.FALLOFF_GLTF=ci.FALLOFF_GLTF,Ti.FALLOFF_STANDARD=ci.FALLOFF_STANDARD,Ti.LIGHTMAP_DEFAULT=ci.LIGHTMAP_DEFAULT,Ti.LIGHTMAP_SPECULAR=ci.LIGHTMAP_SPECULAR,Ti.LIGHTMAP_SHADOWSONLY=ci.LIGHTMAP_SHADOWSONLY,Ti.INTENSITYMODE_AUTOMATIC=ci.INTENSITYMODE_AUTOMATIC,Ti.INTENSITYMODE_LUMINOUSPOWER=ci.INTENSITYMODE_LUMINOUSPOWER,Ti.INTENSITYMODE_LUMINOUSINTENSITY=ci.INTENSITYMODE_LUMINOUSINTENSITY,Ti.INTENSITYMODE_ILLUMINANCE=ci.INTENSITYMODE_ILLUMINANCE,Ti.INTENSITYMODE_LUMINANCE=ci.INTENSITYMODE_LUMINANCE,Ti.LIGHTTYPEID_POINTLIGHT=ci.LIGHTTYPEID_POINTLIGHT,Ti.LIGHTTYPEID_DIRECTIONALLIGHT=ci.LIGHTTYPEID_DIRECTIONALLIGHT,Ti.LIGHTTYPEID_SPOTLIGHT=ci.LIGHTTYPEID_SPOTLIGHT,Ti.LIGHTTYPEID_HEMISPHERICLIGHT=ci.LIGHTTYPEID_HEMISPHERICLIGHT,Qe([ut()],Ti.prototype,"diffuse",void 0),Qe([ut()],Ti.prototype,"specular",void 0),Qe([ct()],Ti.prototype,"falloffType",void 0),Qe([ct()],Ti.prototype,"intensity",void 0),Qe([ct()],Ti.prototype,"range",null),Qe([ct()],Ti.prototype,"intensityMode",null),Qe([ct()],Ti.prototype,"radius",null),Qe([ct()],Ti.prototype,"_renderPriority",void 0),Qe([ht("_reorderLightsInScene")],Ti.prototype,"renderPriority",void 0),Qe([ct("shadowEnabled")],Ti.prototype,"_shadowEnabled",void 0),Qe([ct("excludeWithLayerMask")],Ti.prototype,"_excludeWithLayerMask",void 0),Qe([ct("includeOnlyWithLayerMask")],Ti.prototype,"_includeOnlyWithLayerMask",void 0),Qe([ct("lightmapMode")],Ti.prototype,"_lightmapMode",void 0),Ei.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new Ai(e,ze.Zero(),t)));class Ai extends Ti{constructor(e,t,i){super(e,i),this.groundColor=new tt(0,0,0),this.direction=t||ze.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=ze.Normalize(e.subtract(ze.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=ze.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=ze.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=Xe.Identity()),this._worldMatrix}getTypeID(){return Ti.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}Qe([ut()],Ai.prototype,"groundColor",void 0),Qe([pt()],Ai.prototype,"direction",void 0),function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(ui||(ui={}));class vi{}vi.X=new ze(1,0,0),vi.Y=new ze(0,1,0),vi.Z=new ze(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(fi||(fi={})),function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(_i||(_i={}));class Si{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^(0|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 Si(this.width*e,this.height*t)}clone(){return new Si(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 Si(0,0)}add(e){return new Si(this.width+e.width,this.height+e.height)}subtract(e){return new Si(this.width-e.width,this.height-e.height)}static Lerp(e,t,i){const n=e.width+(t.width-e.width)*i,s=e.height+(t.height-e.height)*i;return new Si(n,s)}}class Ri{constructor(e,t,i,n){this.x=e,this.y=t,this.width=i,this.height=n}toGlobal(e,t){return new Ri(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 Ri(this.x,this.y,this.width,this.height)}}class Ci{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,n,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=n.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const s=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==s.frameId&&(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=n.clone()}}}class xi{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class Mi{constructor(e,t,i){this.vectors=Be.BuildArray(8,ze.Zero),this.center=ze.Zero(),this.centerWorld=ze.Zero(),this.extendSize=ze.Zero(),this.extendSizeWorld=ze.Zero(),this.directions=Be.BuildArray(3,ze.Zero),this.vectorsWorld=Be.BuildArray(8,ze.Zero),this.minimumWorld=ze.Zero(),this.maximumWorld=ze.Zero(),this.minimum=ze.Zero(),this.maximum=ze.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const n=e.x,s=e.y,r=e.z,a=t.x,o=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(n,s,r),this.maximum.copyFromFloats(a,o,l),h[0].copyFromFloats(n,s,r),h[1].copyFromFloats(a,o,l),h[2].copyFromFloats(a,s,r),h[3].copyFromFloats(n,o,r),h[4].copyFromFloats(n,s,l),h[5].copyFromFloats(a,o,r),h[6].copyFromFloats(n,o,l),h[7].copyFromFloats(a,s,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||Xe.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=Mi._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),n=i.length();i.normalizeFromLength(n);const s=n*e,r=i.scaleInPlace(.5*s),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,n=this.directions,s=this.vectorsWorld,r=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)s[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 n=0;n<8;++n){const a=s[n];ze.TransformCoordinatesToRef(r[n],e,a),t.minimizeInPlace(a),i.maximizeInPlace(a)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}ze.FromArrayToRef(e.m,0,n[0]),ze.FromArrayToRef(e.m,4,n[1]),ze.FromArrayToRef(e.m,8,n[2]),this._worldMatrix=e}isInFrustum(e){return Mi.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return Mi.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,n=t.x,s=t.y,r=t.z,a=i.x,o=i.y,l=i.z,h=e.x,c=e.y,d=e.z,u=-.001;return!(a-hh-n||o-cc-s||l-dd-r)}intersectsSphere(e){return Mi.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,n=this.maximumWorld,s=i.x,r=i.y,a=i.z,o=n.x,l=n.y,h=n.z,c=e.x,d=e.y,u=e.z,f=t.x,_=t.y,p=t.z;return!(of||l_||hp)}dispose(){var e,t;null===(e=this._drawWrapperFront)||void 0===e||e.dispose(),null===(t=this._drawWrapperBack)||void 0===t||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,n){const s=Mi._TmpVector3[0];return ze.ClampToRef(i,e,t,s),ze.DistanceSquared(i,s)<=n*n}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const n=t[i];for(let t=0;t<8;++t)if(n.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let n=!0;const s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])>=0){n=!1;break}if(n)return!1}return!0}}Mi._TmpVector3=Be.BuildArray(3,ze.Zero);class Ii{constructor(e,t,i){this.center=ze.Zero(),this.centerWorld=ze.Zero(),this.minimum=ze.Zero(),this.maximum=ze.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const n=ze.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*n,this._update(i||Xe.IdentityReadOnly)}scale(e){const t=this.radius*e,i=Ii._TmpVector3,n=i[0].setAll(t),s=this.center.subtractToRef(n,i[1]),r=this.center.addToRef(n,i[2]);return this.reConstruct(s,r,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{ze.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=Ii._TmpVector3[0];ze.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 n=0;n<6;n++)if(e[n].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=ze.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const n=ze.Dot(t.centerWorld,e),s=Math.abs(ze.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(ze.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(ze.Dot(t.directions[2],e))*t.extendSize.z;i.min=n-s,i.max=n+s},Di=(e,t,i)=>(Pi(e,t,bi),Pi(e,i,yi),!(bi.min>yi.max||yi.min>bi.max));class Oi{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new Mi(e,t,i),this.boundingSphere=new Ii(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=Oi._TmpVector3[0].copyFrom(e).subtractInPlace(t),n=Oi._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,n,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,n,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=ze.Minimize(this.minimum,e),i=ze.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){return this.encapsulate(e.boundingBox.centerWorld.subtract(e.boundingBox.extendSizeWorld)),this.encapsulate(e.boundingBox.centerWorld.add(e.boundingBox.extendSizeWorld)),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return!(2!==t&&3!==t||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(1!==t&&3!==t)||this.boundingBox.isInFrustum(e))}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,Oi._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(!Ii.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!Mi.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,n=e.boundingBox;return!!(Di(i.directions[0],i,n)&&Di(i.directions[1],i,n)&&Di(i.directions[2],i,n)&&Di(n.directions[0],i,n)&&Di(n.directions[1],i,n)&&Di(n.directions[2],i,n)&&Di(ze.Cross(i.directions[0],n.directions[0]),i,n)&&Di(ze.Cross(i.directions[0],n.directions[1]),i,n)&&Di(ze.Cross(i.directions[0],n.directions[2]),i,n)&&Di(ze.Cross(i.directions[1],n.directions[0]),i,n)&&Di(ze.Cross(i.directions[1],n.directions[1]),i,n)&&Di(ze.Cross(i.directions[1],n.directions[2]),i,n)&&Di(ze.Cross(i.directions[2],n.directions[0]),i,n)&&Di(ze.Cross(i.directions[2],n.directions[1]),i,n)&&Di(ze.Cross(i.directions[2],n.directions[2]),i,n))}}Oi._TmpVector3=Be.BuildArray(2,ze.Zero);class Li{static extractMinAndMaxIndexed(e,t,i,n,s,r){for(let a=i;a!Array.isArray(e)&&!Array.isArray(t)))],Li,"extractMinAndMaxIndexed",null),Qe([Et.filter(((...[e])=>!Array.isArray(e)))],Li,"extractMinAndMax",null);class Fi{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:null===(e=this._getDrawWrapper())||void 0===e?void 0:e.defines}set materialDefines(e){var t;(null!==(t=this._mainDrawWrapperOverride)&&void 0!==t?t:this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=null!=e?e:this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new $(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&(null===(i=this._drawWrappers[e])||void 0===i||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:null!==(t=null===(e=this._getDrawWrapper())||void 0===e?void 0:e.effect)&&void 0!==t?t:null}get _drawWrapper(){var e;return null!==(e=this._mainDrawWrapperOverride)&&void 0!==e?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,n=!0){const s=this._drawWrapper;s.setEffect(e,t,n),void 0!==i&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)null==e||e.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,n,s,r,a,o=!0){return new Fi(e,t,i,n,s,r,a,o)}constructor(e,t,i,n,s,r,a,o=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=n,this.indexCount=s,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.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(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh}getMaterial(e=!0){var t;const i=null!==(t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))&&void 0!==t?t:this._renderingMesh.material;if(!i)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(i)){const e=i.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return i}_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(Lt.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,n,s=null){const r=new ze(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new ze(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return Li.extractMinAndMaxIndexed(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,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new Oi(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;to&&(o=t)}return new Fi(e,a,o-a+1,t,i,n,s,r)}}class wi extends Ei{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var e,t,i,n;let s=0,r=0;if(this.mode===wi.PERSPECTIVE_CAMERA)this.fovMode===wi.FOVMODE_VERTICAL_FIXED?(r=2*this.minZ*Math.tan(this.fov/2),s=this.getEngine().getAspectRatio(this)*r):(s=2*this.minZ*Math.tan(this.fov/2),r=s/this.getEngine().getAspectRatio(this));else{const a=this.getEngine().getRenderWidth()/2,o=this.getEngine().getRenderHeight()/2;s=(null!==(e=this.orthoRight)&&void 0!==e?e:a)-(null!==(t=this.orthoLeft)&&void 0!==t?t:-a),r=(null!==(i=this.orthoTop)&&void 0!==i?i:o)-(null!==(n=this.orthoBottom)&&void 0!==n?n:-o)}return s*r}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}constructor(e,t,i,n=!0){super(e,i),this._position=ze.Zero(),this._upVector=ze.Up(),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=wi.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Ri(0,0,1,1),this.layerMask=268435455,this.fovMode=wi.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=wi.RIG_MODE_NONE,this.customRenderTargets=new Array,this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new s,this.onProjectionMatrixChangedObservable=new s,this.onAfterCheckInputsObservable=new s,this.onRestoreStateObservable=new s,this.isRigCamera=!1,this._rigCameras=new Array,this._webvrViewMatrix=Xe.Identity(),this._skipRendering=!1,this._projectionMatrix=new Xe,this._postProcesses=new Array,this._activeMeshes=new be(256),this._globalPosition=ze.Zero(),this._computedViewMatrix=Xe.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=Xe.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=We.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),n&&!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}_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-1?(c.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 Xe.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(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){var t,i,n,s,r,a,o,l;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 h=this.getEngine(),c=this.getScene(),d=h.useReverseDepthBuffer;if(this.mode===wi.PERSPECTIVE_CAMERA){let e;this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=h.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),e=c.useRightHandedSystem?Xe.PerspectiveFovRHToRef:Xe.PerspectiveFovLHToRef,e(this.fov,h.getAspectRatio(this),d?this.maxZ:this.minZ,d?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===wi.FOVMODE_VERTICAL_FIXED,h.isNDCHalfZRange,this.projectionPlaneTilt,d)}else{const e=h.getRenderWidth()/2,u=h.getRenderHeight()/2;c.useRightHandedSystem?Xe.OrthoOffCenterRHToRef(null!==(t=this.orthoLeft)&&void 0!==t?t:-e,null!==(i=this.orthoRight)&&void 0!==i?i:e,null!==(n=this.orthoBottom)&&void 0!==n?n:-u,null!==(s=this.orthoTop)&&void 0!==s?s:u,d?this.maxZ:this.minZ,d?this.minZ:this.maxZ,this._projectionMatrix,h.isNDCHalfZRange):Xe.OrthoOffCenterLHToRef(null!==(r=this.orthoLeft)&&void 0!==r?r:-e,null!==(a=this.orthoRight)&&void 0!==a?a:e,null!==(o=this.orthoBottom)&&void 0!==o?o:-u,null!==(l=this.orthoTop)&&void 0!==l?l:u,d?this.maxZ:this.minZ,d?this.minZ:this.maxZ,this._projectionMatrix,h.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=h.getRenderWidth(),this._cache.renderHeight=h.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?li.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=li.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 _("Ray")}getForwardRayToRef(e,t=100,i,n){throw _("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!==wi.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=Me.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==wi.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 Xe.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}_updateCameraRotationMatrix(){}_updateWebVRCameraRotationMatrix(){}_getWebVRProjectionMatrix(){return Xe.Identity()}_getWebVRViewMatrix(){return Xe.Identity()}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=Me.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;ewi._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,n=wi.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),s=gt.Parse(n,e,t);if(void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),s.inputs&&(s.inputs.parse(e),s._setupInputs()),e.upVector&&(s.upVector=ze.FromArray(e.upVector)),s.setPosition&&(s.position.copyFromFloats(0,0,0),s.setPosition(ze.FromArray(e.position))),e.target&&s.setTarget&&s.setTarget(ze.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};s.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t{throw _("UniversalCamera")},wi.PERSPECTIVE_CAMERA=0,wi.ORTHOGRAPHIC_CAMERA=1,wi.FOVMODE_VERTICAL_FIXED=0,wi.FOVMODE_HORIZONTAL_FIXED=1,wi.RIG_MODE_NONE=0,wi.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,wi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,wi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,wi.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,wi.RIG_MODE_STEREOSCOPIC_INTERLACED=14,wi.RIG_MODE_VR=20,wi.RIG_MODE_WEBVR=21,wi.RIG_MODE_CUSTOM=22,wi.ForceAttachControlToAlwaysPreventDefault=!1,Qe([pt("position")],wi.prototype,"_position",void 0),Qe([pt("upVector")],wi.prototype,"_upVector",void 0),Qe([ct()],wi.prototype,"orthoLeft",null),Qe([ct()],wi.prototype,"orthoRight",null),Qe([ct()],wi.prototype,"orthoBottom",null),Qe([ct()],wi.prototype,"orthoTop",null),Qe([ct()],wi.prototype,"fov",void 0),Qe([ct()],wi.prototype,"projectionPlaneTilt",void 0),Qe([ct()],wi.prototype,"minZ",void 0),Qe([ct()],wi.prototype,"maxZ",void 0),Qe([ct()],wi.prototype,"inertia",void 0),Qe([ct()],wi.prototype,"mode",null),Qe([ct()],wi.prototype,"layerMask",void 0),Qe([ct()],wi.prototype,"fovMode",void 0),Qe([ct()],wi.prototype,"cameraRigMode",void 0),Qe([ct()],wi.prototype,"interaxialDistance",void 0),Qe([ct()],wi.prototype,"isStereoscopicSideBySide",void 0);class zi{static BindSceneUniformBuffer(e,t){t.bindToEffect(e,"Scene")}static PrepareDefinesForMergedUV(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}static BindTextureMatrix(e,t,i){const n=e.getTextureMatrix();t.updateMatrix(i+"Matrix",n)}static GetFogState(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==pi.FOGMODE_NONE}static PrepareDefinesForMisc(e,t,i,n,s,r,a){a._areMiscDirty&&(a.LOGARITHMICDEPTH=i,a.POINTSIZE=n,a.FOG=s&&this.GetFogState(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=r)}static PrepareDefinesForCamera(e,t){let i=!1;if(e.activeCamera){const n=t.CAMERA_ORTHOGRAPHIC?1:0,s=t.CAMERA_PERSPECTIVE?1:0,r=e.activeCamera.mode===wi.ORTHOGRAPHIC_CAMERA?1:0,a=e.activeCamera.mode===wi.PERSPECTIVE_CAMERA?1:0;(n^r||s^a)&&(t.CAMERA_ORTHOGRAPHIC=1===r,t.CAMERA_PERSPECTIVE=1===a,i=!0)}return i}static PrepareDefinesForFrameBoundValues(e,t,i,n,s,r=null,a=!1){let o=zi.PrepareDefinesForCamera(e,n);!1!==r&&(o=Ui(i,e,n)),n.DEPTHPREPASS!==!t.getColorWrite()&&(n.DEPTHPREPASS=!n.DEPTHPREPASS,o=!0),n.INSTANCES!==s&&(n.INSTANCES=s,o=!0),n.THIN_INSTANCES!==a&&(n.THIN_INSTANCES=a,o=!0),o&&n.markAsUnprocessed()}static PrepareDefinesForBones(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 n=e.getScene().prePassRenderer;if(n&&n.enabled){const i=-1===n.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}static PrepareDefinesForMorphTargets(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.MORPHTARGETS=i.numInfluencers>0,t.NUM_MORPH_INFLUENCERS=i.numInfluencers,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)}static PrepareDefinesForBakedVertexAnimation(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}static PrepareDefinesForAttributes(e,t,i,n,s=!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(Lt.NormalKind),t._needNormals&&e.isVerticesDataPresent(Lt.TangentKind)&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){const i=e.useVertexColors&&e.isVerticesDataPresent(Lt.ColorKind);t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&r}return e.isVerticesDataPresent(Lt.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),n&&this.PrepareDefinesForBones(e,t),s&&this.PrepareDefinesForMorphTargets(e,t),a&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(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()}}static PrepareDefinesForOIT(e,t,i){const n=t.ORDER_INDEPENDENT_TRANSPARENCY,s=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,n===t.ORDER_INDEPENDENT_TRANSPARENCY&&s===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){const n=t.PREPASS;if(!t._arePrePassDirty)return;const s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount;for(let i=0;i0&&(a.shadowEnabled=!0,t.prepareDefines(s,n))}}i.lightmapMode!=ci.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+n]=!0,s["LIGHTMAPNOSPECULAR"+n]=i.lightmapMode==ci.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+n]=!1,s["LIGHTMAPNOSPECULAR"+n]=!1)}static PrepareDefinesForLights(e,t,i,n,s=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 r of t.lightSources)if(this.PrepareDefinesForLight(e,t,r,a,i,n,o),a++,a===s)break;i.SPECULARTERM=o.specularEnabled,i.SHADOWS=o.shadowEnabled;for(let e=a;e0&&(s=n+r,t.addFallback(s,"LIGHT"+r)),e.SHADOWS||(e["SHADOW"+r]&&t.addFallback(n,"SHADOW"+r),e["SHADOWPCF"+r]&&t.addFallback(n,"SHADOWPCF"+r),e["SHADOWPCSS"+r]&&t.addFallback(n,"SHADOWPCSS"+r),e["SHADOWPOISSON"+r]&&t.addFallback(n,"SHADOWPOISSON"+r),e["SHADOWESM"+r]&&t.addFallback(n,"SHADOWESM"+r),e["SHADOWCLOSEESM"+r]&&t.addFallback(n,"SHADOWCLOSEESM"+r));return s++}static PrepareAttributesForMorphTargetsInfluencers(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)}static PrepareAttributesForMorphTargets(e,t,i){const n=i.NUM_MORPH_INFLUENCERS;if(n>0&&m.LastCreatedEngine){const s=m.LastCreatedEngine.getCaps().maxVertexAttribs,r=t.morphTargetManager;if(null==r?void 0: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;is&&c.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,n){i.NUM_BONE_INFLUENCERS>0&&(n.addCPUSkinningFallback(0,t),e.push(Lt.MatricesIndicesKind),e.push(Lt.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(Lt.MatricesIndicesExtraKind),e.push(Lt.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(Lt.ColorInstanceKind)}static PushAttributesForInstances(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"))}static BindLightProperties(e,t,i){e.transferToEffect(t,i+"")}static BindLight(e,t,i,n,s,r=!0){e._bindLight(t,i,n,s,r)}static BindLights(e,t,i,n,s=4){const r=Math.min(t.lightSources.length,s);for(let s=0;s-1){const i=n.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(n.bones.length+1))}else{const s=n.getTransformMatrices(e);s&&(t.setMatrices("mBones",s),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=s.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),zi._CopyBonesTransformationMatrices(s,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}static BindLogDepth(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=i.activeCamera;e.mode===wi.ORTHOGRAPHIC_CAMERA&&c.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}}zi._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},zi._TempFogColor=tt.Black();class Hi{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}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){gt.Clone((()=>e),this)}serialize(){return gt.Serialize(this)}parse(e,t,i){gt.Parse((()=>this),e,t,i)}}var Wi,Xi;Qe([ct()],Hi.prototype,"func",null),Qe([ct()],Hi.prototype,"funcRef",null),Qe([ct()],Hi.prototype,"funcMask",null),Qe([ct()],Hi.prototype,"opStencilFail",null),Qe([ct()],Hi.prototype,"opDepthFail",null),Qe([ct()],Hi.prototype,"opStencilDepthPass",null),Qe([ct()],Hi.prototype,"mask",null),Qe([ct()],Hi.prototype,"enabled",null),(Xi=Wi||(Wi={}))[Xi.Created=1]="Created",Xi[Xi.Disposed=2]="Disposed",Xi[Xi.GetDefineNames=4]="GetDefineNames",Xi[Xi.PrepareUniformBuffer=8]="PrepareUniformBuffer",Xi[Xi.IsReadyForSubMesh=16]="IsReadyForSubMesh",Xi[Xi.PrepareDefines=32]="PrepareDefines",Xi[Xi.BindForSubMesh=64]="BindForSubMesh",Xi[Xi.PrepareEffect=128]="PrepareEffect",Xi[Xi.GetAnimatables=256]="GetAnimatables",Xi[Xi.GetActiveTextures=512]="GetActiveTextures",Xi[Xi.HasTexture=1024]="HasTexture",Xi[Xi.FillRenderTargetTextures=2048]="FillRenderTargetTextures",Xi[Xi.HasRenderTargetTextures=4096]="HasRenderTargetTextures",Xi[Xi.HardBindForSubMesh=8192]="HardBindForSubMesh";class Yi{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(Yi.MiscDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(Yi.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(Yi.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 s),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 s),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new s),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(Yi.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(Yi.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case Yi.WireFrameFillMode:case Yi.LineListDrawMode:case Yi.LineLoopDrawMode:case Yi.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?Yi.WireFrameFillMode:Yi.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case Yi.PointFillMode:case Yi.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?Yi.PointFillMode:Yi.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(Yi.MiscDirtyFlag))}_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.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new s,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=2,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 Hi,this._useUBO=!1,this._fillMode=Yi.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 n=t||m.LastCreatedScene;n&&(this._scene=n,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||Me.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new $(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=Yi.ClockWiseSideOrientation:this.sideOrientation=Yi.CounterClockWiseSideOrientation,this._uniformBuffer=new Dt(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),Yi.OnEventObservable.notifyObservers(this,Wi.Created))}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 n=t.materialDefines;return!!n&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===Yi.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Yi.MATERIAL_OPAQUE||this._transparencyMode===Yi.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)t.getMaterial()===this&&t.effect&&(t.effect._wasPreviouslyReady=!1,t.effect._wasPreviouslyUsingInstances=null,t.effect._forceRebindOnNextCall=e);e&&this.markAsDirty(Yi.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),n=(null==t?this.sideOrientation:t)===Yi.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,n,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),n}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(Wi.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const n=i.effect;n&&(this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),n._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){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,zi.BindSceneUniformBuffer(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(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(Wi.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(Wi.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(Wi.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}getBindedMeshes(){if(this.meshMap){const e=new Array;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,n){const s={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(s.clipPlane&&(r.clipPlane=new oi(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,r=null;if(e.subMeshes){const t=new Fi(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,s.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?r=t.effect.getCompilationError():(i=!1,setTimeout(o,16)))}i&&(this.allowShaderHotSwapping=a,r&&n&&n(r),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(o,16);s.clipPlane&&(r.clipPlane=i)};o()}forceCompilationAsync(e,t){return new Promise(((i,n)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{n(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(Yi._DirtyCallbackArray.length=0,e&Yi.TextureDirtyFlag&&Yi._DirtyCallbackArray.push(Yi._TextureDirtyCallBack),e&Yi.LightDirtyFlag&&Yi._DirtyCallbackArray.push(Yi._LightsDirtyCallBack),e&Yi.FresnelDirtyFlag&&Yi._DirtyCallbackArray.push(Yi._FresnelDirtyCallBack),e&Yi.AttributesDirtyFlag&&Yi._DirtyCallbackArray.push(Yi._AttributeDirtyCallBack),e&Yi.MiscDirtyFlag&&Yi._DirtyCallbackArray.push(Yi._MiscDirtyCallBack),e&Yi.PrePassDirtyFlag&&Yi._DirtyCallbackArray.push(Yi._PrePassDirtyCallBack),Yi._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Yi._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(Yi._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Yi._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Yi._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Yi._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Yi._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Yi._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Yi._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Yi._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Yi._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Yi._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==di.BackwardCompatible){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 n=this.getScene();if(n.stopAnimation(this),n.freeProcessedMaterials(),n.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(Wi.Disposed,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=n.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){if(e.geometry){const i=e.geometry;if(this._storeEffectOnSubMeshes)for(const n of e.subMeshes)i._releaseVertexArrayObject(n.effect),t&&n.effect&&n.effect.dispose();else i._releaseVertexArrayObject(this._drawWrapper.effect)}}serialize(){const e=gt.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,e}static Parse(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return c.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 n=Me.Instantiate(e.customType).Parse(e,t,i);return n._loadedUniqueId=e.uniqueId,n}}Yi.TriangleFillMode=0,Yi.WireFrameFillMode=1,Yi.PointFillMode=2,Yi.PointListDrawMode=3,Yi.LineListDrawMode=4,Yi.LineLoopDrawMode=5,Yi.LineStripDrawMode=6,Yi.TriangleStripDrawMode=7,Yi.TriangleFanDrawMode=8,Yi.ClockWiseSideOrientation=0,Yi.CounterClockWiseSideOrientation=1,Yi.TextureDirtyFlag=1,Yi.LightDirtyFlag=2,Yi.FresnelDirtyFlag=4,Yi.AttributesDirtyFlag=8,Yi.MiscDirtyFlag=16,Yi.PrePassDirtyFlag=32,Yi.AllDirtyFlag=63,Yi.MATERIAL_OPAQUE=0,Yi.MATERIAL_ALPHATEST=1,Yi.MATERIAL_ALPHABLEND=2,Yi.MATERIAL_ALPHATESTANDBLEND=3,Yi.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,Yi.MATERIAL_NORMALBLENDMETHOD_RNM=1,Yi.OnEventObservable=new s,m.OnEnginesDisposedObservable.addOnce((()=>{Yi.OnEventObservable.clear()})),Yi._AllDirtyCallBack=e=>e.markAllAsDirty(),Yi._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),Yi._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),Yi._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),Yi._MiscDirtyCallBack=e=>e.markAsMiscDirty(),Yi._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),Yi._LightsDirtyCallBack=e=>e.markAsLightDirty(),Yi._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),Yi._FresnelAndMiscDirtyCallBack=e=>{Yi._FresnelDirtyCallBack(e),Yi._MiscDirtyCallBack(e)},Yi._TextureAndMiscDirtyCallBack=e=>{Yi._TextureDirtyCallBack(e),Yi._MiscDirtyCallBack(e)},Yi._DirtyCallbackArray=[],Yi._RunDirtyCallBacks=e=>{for(const t of Yi._DirtyCallbackArray)t(e)},Qe([ct()],Yi.prototype,"id",void 0),Qe([ct()],Yi.prototype,"uniqueId",void 0),Qe([ct()],Yi.prototype,"name",void 0),Qe([ct()],Yi.prototype,"metadata",void 0),Qe([ct()],Yi.prototype,"checkReadyOnEveryCall",void 0),Qe([ct()],Yi.prototype,"checkReadyOnlyOnce",void 0),Qe([ct()],Yi.prototype,"state",void 0),Qe([ct("alpha")],Yi.prototype,"_alpha",void 0),Qe([ct("backFaceCulling")],Yi.prototype,"_backFaceCulling",void 0),Qe([ct("cullBackFaces")],Yi.prototype,"_cullBackFaces",void 0),Qe([ct()],Yi.prototype,"sideOrientation",void 0),Qe([ct("alphaMode")],Yi.prototype,"_alphaMode",void 0),Qe([ct()],Yi.prototype,"_needDepthPrePass",void 0),Qe([ct()],Yi.prototype,"disableDepthWrite",void 0),Qe([ct()],Yi.prototype,"disableColorWrite",void 0),Qe([ct()],Yi.prototype,"forceDepthWrite",void 0),Qe([ct()],Yi.prototype,"depthFunction",void 0),Qe([ct()],Yi.prototype,"separateCullingPass",void 0),Qe([ct("fogEnabled")],Yi.prototype,"_fogEnabled",void 0),Qe([ct()],Yi.prototype,"pointSize",void 0),Qe([ct()],Yi.prototype,"zOffset",void 0),Qe([ct()],Yi.prototype,"zOffsetUnits",void 0),Qe([ct()],Yi.prototype,"pointsCloud",null),Qe([ct()],Yi.prototype,"fillMode",null),Qe([ct()],Yi.prototype,"transparencyMode",null);class Ki extends Yi{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new Xe,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){super._afterBind(e,t),this.getScene()._cachedEffect=t,t&&(t._forceRebindOnNextCall=!1)}_mustRebind(e,t,i=1){return e.isCachedMaterialInvalid(this,t,i)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}class ji{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!==(null==e?void 0:e._shareDepth)}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=Si.Zero(),this._cachedBaseSize=Si.Zero(),this._initialSamplingMode=2,this._texture=ji._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(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 qi extends ji{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(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._markAllSubMeshesAsTexturesDirty()}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){this._texture&&(this._texture._isRGBD=e)}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=xe()),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=0,this.wrapR=1,this.anisotropicFilteringLevel=qi.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=new Array,this.onDisposeObservable=new s,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?qi._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}checkTransformsAreIdentical(e){return null!==e}getTextureMatrix(){return Xe.IdentityReadOnly}getReflectionTextureMatrix(){return Xe.IdentityReadOnly}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,n,s,r){const a=this._getEngine();if(!a)return null;const o=a._getUseSRGBBuffer(!!s,t),l=a.getLoadedTexturesCache();for(let a=0;a=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=gt.Serialize(this);return gt.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let n=0;n{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}function Qi(e,t,i=!1){const n=t.width,s=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let n=e[t];n<0?n=0:n>1&&(n=1),i[t]=255*n}e=i}const r=document.createElement("canvas");r.width=n,r.height=s;const a=r.getContext("2d");if(!a)return null;const o=a.createImageData(n,s);if(o.data.set(e),a.putImageData(o,0,0),i){const e=document.createElement("canvas");e.width=n,e.height=s;const t=e.getContext("2d");return t?(t.translate(0,s),t.scale(1,-1),t.drawImage(r,0,0),e.toDataURL("image/png")):null}return r.toDataURL("image/png")}qi.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,Qe([ct()],qi.prototype,"uniqueId",void 0),Qe([ct()],qi.prototype,"name",void 0),Qe([ct()],qi.prototype,"metadata",void 0),Qe([ct("hasAlpha")],qi.prototype,"_hasAlpha",void 0),Qe([ct("getAlphaFromRGB")],qi.prototype,"_getAlphaFromRGB",void 0),Qe([ct()],qi.prototype,"level",void 0),Qe([ct("coordinatesIndex")],qi.prototype,"_coordinatesIndex",void 0),Qe([ct()],qi.prototype,"optimizeUVAllocation",void 0),Qe([ct("coordinatesMode")],qi.prototype,"_coordinatesMode",void 0),Qe([ct()],qi.prototype,"wrapU",null),Qe([ct()],qi.prototype,"wrapV",null),Qe([ct()],qi.prototype,"wrapR",void 0),Qe([ct()],qi.prototype,"anisotropicFilteringLevel",void 0),Qe([ct()],qi.prototype,"isCube",null),Qe([ct()],qi.prototype,"is3D",null),Qe([ct()],qi.prototype,"is2DArray",null),Qe([ct()],qi.prototype,"gammaSpace",null),Qe([ct()],qi.prototype,"invertZ",void 0),Qe([ct()],qi.prototype,"lodLevelInAlpha",void 0),Qe([ct()],qi.prototype,"lodGenerationOffset",null),Qe([ct()],qi.prototype,"lodGenerationScale",null),Qe([ct()],qi.prototype,"linearSpecularLOD",null),Qe([dt()],qi.prototype,"irradianceTexture",null),Qe([ct()],qi.prototype,"isRenderTarget",void 0);class Zi{}Zi.UseOpenGLOrientationForUV=!1;class Ji extends qi{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,n,r=Ji.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=null,h=!1,c,d,u,f,_){var p,m,g,E,T,A,v,S,R;let C;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._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 s,this._isBlocking=!0,this.name=e||"",this.url=e;let x=!1,M=null;"object"==typeof i&&null!==i?(C=null!==(p=i.noMipmap)&&void 0!==p&&p,n=null!==(m=i.invertY)&&void 0!==m?m:!Zi.UseOpenGLOrientationForUV,r=null!==(g=i.samplingMode)&&void 0!==g?g:Ji.TRILINEAR_SAMPLINGMODE,a=null!==(E=i.onLoad)&&void 0!==E?E:null,o=null!==(T=i.onError)&&void 0!==T?T:null,l=null!==(A=i.buffer)&&void 0!==A?A:null,h=null!==(v=i.deleteBuffer)&&void 0!==v&&v,c=i.format,d=i.mimeType,u=i.loaderOptions,f=i.creationFlags,x=null!==(S=i.useSRGBBuffer)&&void 0!==S&&S,M=null!==(R=i.internalTexture)&&void 0!==R?R:null):C=!!i,this._noMipmap=C,this._invertY=void 0===n?!Zi.UseOpenGLOrientationForUV:n,this._initialSamplingMode=r,this._buffer=l,this._deleteBuffer=h,this._mimeType=d,this._loaderOptions=u,this._creationFlags=f,this._useSRGBBuffer=x,this._forcedExtension=_,c&&(this._format=c);const I=this.getScene(),b=this._getEngine();if(!b)return;b.onBeforeTextureInitObservable.notifyObservers(this);const y=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),a&&a(),!this.isBlocking&&I&&I.resetCachedMaterial()},P=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},o&&o(e,t),Ji.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!M)return this._delayedOnLoad=y,void(this._delayedOnError=P);if(this._texture=null!=M?M:this._getFromCache(this.url,C,r,this._invertY,x),this._texture)if(this._texture.isReady)ne.SetImmediate((()=>y()));else{const e=this._texture.onLoadedObservable.add(y);this._texture.onErrorObservable.add((t=>{var i;P(t.message,t.exception),null===(i=this._texture)||void 0===i||i.onLoadedObservable.remove(e)}))}else if(I&&I.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=y,this._delayedOnError=P;else{try{this._texture=b.createTexture(this.url,C,this._invertY,I,r,y,P,this._buffer,void 0,this._format,this._forcedExtension,d,u,f,x)}catch(e){throw P("error loading",e),e}h&&(this._buffer=null)}}updateURL(e,t=null,i,n){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1)),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=n,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;const e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer),this._texture?this._delayedOnLoad&&(this._texture.isReady?ne.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,n){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,ze.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,n),n.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,n.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,n.z+=this.wRotationCenter}checkTransformsAreIdentical(e){return null!==e&&this.uOffset===e.uOffset&&this.vOffset===e.vOffset&&this.uScale===e.uScale&&this.vScale===e.vScale&&this.uAng===e.uAng&&this.vAng===e.vAng&&this.wAng===e.wAng}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=Xe.Zero(),this._rowGenerationMatrix=new Xe,this._t0=ze.Zero(),this._t1=ze.Zero(),this._t2=ze.Zero()),Xe.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(Xe.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,Ke.Matrix[0]),Xe.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,Ke.Matrix[1]),Xe.ScalingToRef(this._cachedUScale,this._cachedVScale,0,Ke.Matrix[2]),Xe.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,Ke.Matrix[3]),Ke.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(Ke.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(Ke.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(Ke.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),Xe.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();return t?(this.optimizeUVAllocation&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedTextureMatrix):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!==Ji.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=Xe.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=Xe.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 Ji.PLANAR_MODE:Xe.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 Ji.PROJECTION_MODE:{Xe.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:Xe.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(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 gt.Clone((()=>new Ji(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){var e,t;const i=this.name;Ji.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const n=super.serialize(Ji._SerializeInternalTextureUniqueId);return n?((Ji.SerializeBuffers||Ji.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(n.base64String=this._buffer,n.name=n.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?n.base64String="data:image/png;base64,"+v(this._buffer):(Ji.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(n.base64String=!this._engine||this._engine._features.supportSyncTextureRead?function(e,t=0,i=0){const n=e.getInternalTexture();if(!n)return null;const s=e._readPixelsSync(t,i);return s?Qi(s,e.getSize(),n.invertY):null}(this):async function(e,t=0,i=0){const n=e.getInternalTexture();if(!n)return null;const s=await e.readPixels(t,i);return s?Qi(s,e.getSize(),n.invertY):null}(this))),n.invertY=this._invertY,n.samplingMode=this.samplingMode,n._creationFlags=this._creationFlags,n._useSRGBBuffer=this._useSRGBBuffer,Ji._SerializeInternalTextureUniqueId&&(n.internalTextureUniqueId=null!==(t=null===(e=this._texture)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:void 0),this.name=i,n):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 n=Ce.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&n.updateSamplingMode&&n._samplingMode&&n._samplingMode!==e.samplingMode&&n.updateSamplingMode(e.samplingMode),n}if(e.isCube&&!e.isRenderTarget)return Ji._CubeTextureParser(e,t,i);const n=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!n)return null;let s;if(n){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){s=t;break}}const r=t=>{var i;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{var n,a,o;let l=!0;if(e.noMipmap&&(l=!1),e.mirrorPlane){const i=Ji._CreateMirror(e.name,e.renderTargetSize,t,l);return i._waitingRenderList=e.renderList,i.mirrorPlane=oi.FromArray(e.mirrorPlane),r(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{r(n)}),null!==(a=e._creationFlags)&&void 0!==a?a:0,null!==(o=e._useSRGBBuffer)&&void 0!==o&&o),n.name=e.name;else{let a;a=e.name&&e.name.indexOf("://")>0?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||Ji.UseSerializedUrlIfAny)&&(a=e.url);const o={noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{r(n)},internalTexture:s};n=new Ji(a,t,o)}return n}}),e,t)}static CreateFromBase64String(e,t,i,n,s,r=Ji.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=5,h){return new Ji("data:"+t,i,n,s,r,a,o,e,!1,l,void 0,void 0,h)}static LoadFromDataString(e,t,i,n=!1,s,r=!0,a=Ji.TRILINEAR_SAMPLINGMODE,o=null,l=null,h=5,c){return"data:"!==e.substr(0,5)&&(e="data:"+e),new Ji(e,i,s,r,a,o,l,t,n,h,void 0,void 0,c)}}Ji.SerializeBuffers=!0,Ji.ForceSerializeBuffers=!1,Ji.OnTextureLoadErrorObservable=new s,Ji._SerializeInternalTextureUniqueId=!1,Ji._CubeTextureParser=(e,t,i)=>{throw _("CubeTexture")},Ji._CreateMirror=(e,t,i,n)=>{throw _("MirrorTexture")},Ji._CreateRenderTargetTexture=(e,t,i,n,s)=>{throw _("RenderTargetTexture")},Ji.NEAREST_SAMPLINGMODE=1,Ji.NEAREST_NEAREST_MIPLINEAR=8,Ji.BILINEAR_SAMPLINGMODE=2,Ji.LINEAR_LINEAR_MIPNEAREST=11,Ji.TRILINEAR_SAMPLINGMODE=3,Ji.LINEAR_LINEAR_MIPLINEAR=3,Ji.NEAREST_NEAREST_MIPNEAREST=4,Ji.NEAREST_LINEAR_MIPNEAREST=5,Ji.NEAREST_LINEAR_MIPLINEAR=6,Ji.NEAREST_LINEAR=7,Ji.NEAREST_NEAREST=1,Ji.LINEAR_NEAREST_MIPNEAREST=9,Ji.LINEAR_NEAREST_MIPLINEAR=10,Ji.LINEAR_LINEAR=2,Ji.LINEAR_NEAREST=12,Ji.EXPLICIT_MODE=0,Ji.SPHERICAL_MODE=1,Ji.PLANAR_MODE=2,Ji.CUBIC_MODE=3,Ji.PROJECTION_MODE=4,Ji.SKYBOX_MODE=5,Ji.INVCUBIC_MODE=6,Ji.EQUIRECTANGULAR_MODE=7,Ji.FIXED_EQUIRECTANGULAR_MODE=8,Ji.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Ji.CLAMP_ADDRESSMODE=0,Ji.WRAP_ADDRESSMODE=1,Ji.MIRROR_ADDRESSMODE=2,Ji.UseSerializedUrlIfAny=!1,Qe([ct()],Ji.prototype,"url",void 0),Qe([ct()],Ji.prototype,"uOffset",void 0),Qe([ct()],Ji.prototype,"vOffset",void 0),Qe([ct()],Ji.prototype,"uScale",void 0),Qe([ct()],Ji.prototype,"vScale",void 0),Qe([ct()],Ji.prototype,"uAng",void 0),Qe([ct()],Ji.prototype,"vAng",void 0),Qe([ct()],Ji.prototype,"wAng",void 0),Qe([ct()],Ji.prototype,"uRotationCenter",void 0),Qe([ct()],Ji.prototype,"vRotationCenter",void 0),Qe([ct()],Ji.prototype,"wRotationCenter",void 0),Qe([ct()],Ji.prototype,"homogeneousRotationInUVTransform",void 0),Qe([ct()],Ji.prototype,"isBlocking",null),Se("BABYLON.Texture",Ji),gt._TextureParser=Ji.Parse;class $i{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new en(e)}sampleFrame(e=f.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 en{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}}ie.prototype.setAlphaConstants=function(e,t,i,n){this._alphaState.setAlphaBlendConstants(e,t,i,n)},ie.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:case 14: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 2: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 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5: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 9: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 10: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 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13: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 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16: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 17: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=0===e),this._alphaMode=e}else if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}},ie.prototype.getAlphaMode=function(){return this._alphaMode},ie.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774)}this._alphaEquation=e}},ie.prototype.getAlphaEquation=function(){return this._alphaEquation},ie.prototype._readTexturePixelsSync=function(e,t,i,n=-1,s=0,r=null,a=!0,o=!1,l=0,h=0){var c,d;const u=this._gl;if(!u)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=u.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}u.bindFramebuffer(u.FRAMEBUFFER,this._dummyFramebuffer),n>-1?u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0,u.TEXTURE_CUBE_MAP_POSITIVE_X+n,null===(c=e._hardwareTexture)||void 0===c?void 0:c.underlyingResource,s):u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0,u.TEXTURE_2D,null===(d=e._hardwareTexture)||void 0===d?void 0:d.underlyingResource,s);let f=void 0!==e.type?this._getWebGLTextureType(e.type):u.UNSIGNED_BYTE;return o?r||(r=function(e,t,i=!1,n){switch(e){case 3:{const e=(ArrayBuffer,new Int8Array(t));return n&&e.set(new Int8Array(n)),e}case 0:{const e=(ArrayBuffer,new Uint8Array(t));return n&&e.set(new Uint8Array(n)),e}case 4:{const e=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return n&&e.set(new Int16Array(n)),e}case 5:case 8:case 9:case 10:case 2:{const e=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return n&&e.set(new Uint16Array(n)),e}case 6:{const e=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return n&&e.set(new Int32Array(n)),e}case 7:case 11:case 12:case 13:case 14:case 15:{const e=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return n&&e.set(new Uint32Array(n)),e}case 1:{const e=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return n&&e.set(new Float32Array(n)),e}}const s=(ArrayBuffer,new Uint8Array(t));return n&&s.set(new Uint8Array(n)),s}(e.type,4*t*i)):f===u.UNSIGNED_BYTE?(r||(r=new Uint8Array(4*t*i)),f=u.UNSIGNED_BYTE):(r||(r=new Float32Array(4*t*i)),f=u.FLOAT),a&&this.flushFramebuffer(),u.readPixels(l,h,t,i,u.RGBA,f,r),u.bindFramebuffer(u.FRAMEBUFFER,this._currentFramebuffer),r},ie.prototype._readTexturePixels=function(e,t,i,n=-1,s=0,r=null,a=!0,o=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,n,s,r,a,o,l,h))},ie.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let n;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),n=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,n,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},ie.prototype.updateDynamicVertexBuffer=function(e,t,i,n){this.bindArrayBuffer(e),void 0===i&&(i=0);const s=t.byteLength||t.length;void 0===n||n>=s&&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+n)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,n):new Uint8Array(t.buffer,t.byteOffset+i,n),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()};class tn extends ie{static get NpmPackage(){return ie.NpmPackage}static get Version(){return ie.Version}static get Instances(){return m.Instances}static get LastCreatedEngine(){return m.LastCreatedEngine}static get LastCreatedScene(){return m.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise(((i,n)=>{const s=new Image;s.onload=()=>{s.decode().then((()=>{this.createImageBitmap(s,t).then((e=>{i(e)}))}))},s.onerror=()=>{n(`Error loading image ${s.src}`)},s.src=e}))}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){const n=this.createCanvas(t,i).getContext("2d");if(!n)throw new Error("Unable to get 2d context for resizeImageBitmap");return n.drawImage(e,0,0),n.getImageData(0,0,t,i).data}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this.onCanvasFocusObservable.notifyObservers(this)},this._onCanvasBlur=()=>{this.onCanvasBlurObservable.notifyObservers(this)},this._onCanvasContextMenu=e=>{this.disableContextMenu&&e.preventDefault()},e.addEventListener("focus",this._onCanvasFocus),e.addEventListener("blur",this._onCanvasBlur),e.addEventListener("contextmenu",this._onCanvasContextMenu),this._onBlur=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.disable(),this._windowIsBackground=!0},this._onFocus=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.enable(),this._windowIsBackground=!1},this._onCanvasPointerOut=t=>{document.elementFromPoint(t.clientX,t.clientY)!==e&&this.onCanvasPointerOutObservable.notifyObservers(t)};const t=this.getHostWindow();t&&"function"==typeof t.addEventListener&&(t.addEventListener("blur",this._onBlur),t.addEventListener("focus",this._onFocus)),e.addEventListener("pointerout",this._onCanvasPointerOut),this._creationOptions.doNotHandleTouchAction||this._disableTouchAction(),!tn.audioEngine&&this._creationOptions.audioEngine&&tn.AudioEngineFactory&&(tn.audioEngine=tn.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),o()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&tn._RequestPointerlock(e)},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=()=>{this.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1)),this.enableOfflineSupport=void 0!==tn.OfflineProviderFactory,this._deterministicLockstep=!!this._creationOptions.deterministicLockstep,this._lockstepMaxSteps=this._creationOptions.lockstepMaxSteps||0,this._timeStep=this._creationOptions.timeStep||1/60}getAspectRatio(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)}getScreenAspectRatio(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)}getRenderingCanvasClientRect(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null}getInputElementClientRect(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}generateMipMapsForCubemap(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)}}getDepthWrite(){return this._depthCullingState.depthMask}setDepthWrite(e){this._depthCullingState.depthMask=e}getStencilBuffer(){return this._stencilState.stencilTest}setStencilBuffer(e){this._stencilState.stencilTest=e}getStencilMask(){return this._stencilState.stencilMask}setStencilMask(e){this._stencilState.stencilMask=e}getStencilFunction(){return this._stencilState.stencilFunc}getStencilFunctionReference(){return this._stencilState.stencilFuncRef}getStencilFunctionMask(){return this._stencilState.stencilFuncMask}setStencilFunction(e){this._stencilState.stencilFunc=e}setStencilFunctionReference(e){this._stencilState.stencilFuncRef=e}setStencilFunctionMask(e){this._stencilState.stencilFuncMask=e}getStencilOperationFail(){return this._stencilState.stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilState.stencilOpDepthFail}getStencilOperationPass(){return this._stencilState.stencilOpStencilDepthPass}setStencilOperationFail(e){this._stencilState.stencilOpStencilFail=e}setStencilOperationDepthFail(e){this._stencilState.stencilOpDepthFail=e}setStencilOperationPass(e){this._stencilState.stencilOpStencilDepthPass=e}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)}getDepthFunction(){return this._depthCullingState.depthFunc}setDepthFunction(e){this._depthCullingState.depthFunc=e}setDepthFunctionToGreater(){this.setDepthFunction(516)}setDepthFunctionToGreaterOrEqual(){this.setDepthFunction(518)}setDepthFunctionToLess(){this.setDepthFunction(513)}setDepthFunctionToLessOrEqual(){this.setDepthFunction(515)}cacheStencilState(){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()}restoreStencilState(){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)}setDirectViewport(e,t,i,n){const s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,n),s}scissorClear(e,t,i,n,s){this.enableScissor(e,t,i,n),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,n){const s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,n)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}initWebVR(){throw _("WebVRCamera")}_prepareVRComponent(){}_connectVREvents(e,t){}_submitVRFrame(){}disableVR(){}isVRPresenting(){return!1}_requestVRFrame(){}_loadFileAsync(e,t,i){return new Promise(((n,s)=>{this._loadFile(e,(e=>{n(e)}),void 0,t,i,((e,t)=>{s(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}setDepthStencilTexture(e,t,i,n){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,n):this._setTexture(e,null,void 0,void 0,n))}setTextureFromPostProcess(e,t,i){var n;let s=null;t&&(t._textures.data[t._currentRenderTextureInd]?s=t._textures.data[t._currentRenderTextureInd]:t._forcedOutputTexture&&(s=t._forcedOutputTexture)),this._bindTexture(e,null!==(n=null==s?void 0:s.texture)&&void 0!==n?n:null,i)}setTextureFromPostProcessOutput(e,t,i){var n,s;this._bindTexture(e,null!==(s=null===(n=null==t?void 0:t._outputTexture)||void 0===n?void 0:n.texture)&&void 0!==s?s:null,i)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();super._rebuildBuffers()}_renderFrame(){for(let e=0;e0?this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this.isVRPresenting()?this._requestVRFrame():this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&tn._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&tn._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&tn._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){tn._ExitPointerlock()}beginFrame(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),super.beginFrame()}endFrame(){super.endFrame(),this._submitVRFrame(),this.onEndFrameObservable.notifyObservers(this)}resize(e=!1){this.isVRPresenting()||super.resize(e)}setSize(e,t,i=!1){if(!this._renderingCanvas)return!1;if(!super.setSize(e,t,i))return!1;if(this.scenes){for(let e=0;e1&&s){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(r,s),e.transformFeedback=t}return n.linkProgram(r),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=n,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)}))}))}))}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){const t=++tn._RenderPassIdCounter;return this._renderPassNames[t]=null!=e?e:"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t{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,n,0,0,t.width,t.height,0),this.unBindFramebuffer(r),r.dispose(),s&&s()})))}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}wrapWebGLTexture(e,t=!1,i=3){const n=new J(e,this._gl),s=new W(this,H.Unknown,!0);return s._hardwareTexture=n,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}_uploadImageToTexture(e,t,i=0,n=0){const s=this._gl,r=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,a),l=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=s.TEXTURE_2D;e.isCube&&(h=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(h,n,o,a,r,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void c.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,515),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,515),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 j(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 n=this._gl;return new Promise(((s,r)=>{const a=()=>{const o=n.clientWaitSync(e,t,0);o!=n.WAIT_FAILED?o!=n.TIMEOUT_EXPIRED?s():setTimeout(a,i):r()};a()}))}_readPixelsAsync(e,t,i,n,s,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,n,s,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(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();1===m.Instances.length&&tn.audioEngine&&(tn.audioEngine.dispose(),tn.audioEngine=null),this.disableVR();const e=this.getHostWindow();e&&"function"==typeof e.removeEventListener&&(e.removeEventListener("blur",this._onBlur),e.removeEventListener("focus",this._onFocus)),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._renderingCanvas.removeEventListener("contextmenu",this._onCanvasContextMenu)),o()&&(document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)),super.dispose();const t=m.Instances.indexOf(this);t>=0&&m.Instances.splice(t,1),tn.Instances.length||(m.OnEnginesDisposedObservable.notifyObservers(this),m.OnEnginesDisposedObservable.clear()),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}_disableTouchAction(){this._renderingCanvas&&this._renderingCanvas.setAttribute&&(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.webkitTapHighlightColor="transparent")}displayLoadingUI(){if(!r())return;const e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!r())return;const e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=tn.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen}set loadingScreen(e){this._loadingScreen=e}set loadingUIText(e){this.loadingScreen.loadingUIText=e}set loadingUIBackgroundColor(e){this.loadingScreen.loadingUIBackgroundColor=e}createVideoElement(e){return document.createElement("video")}static _RequestPointerlock(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}static _ExitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}static _RequestFullscreen(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}static _ExitFullscreen(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}getFontOffset(e){const t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style",`font: ${e} !important`);const i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";const n=document.createElement("div");n.style.whiteSpace="nowrap",n.appendChild(t),n.appendChild(i),document.body.appendChild(n);let s=0,r=0;try{r=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",s=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(n)}return{ascent:s,height:r,descent:r-s}}}tn.ALPHA_DISABLE=0,tn.ALPHA_ADD=1,tn.ALPHA_COMBINE=2,tn.ALPHA_SUBTRACT=3,tn.ALPHA_MULTIPLY=4,tn.ALPHA_MAXIMIZED=5,tn.ALPHA_ONEONE=6,tn.ALPHA_PREMULTIPLIED=7,tn.ALPHA_PREMULTIPLIED_PORTERDUFF=8,tn.ALPHA_INTERPOLATE=9,tn.ALPHA_SCREENMODE=10,tn.DELAYLOADSTATE_NONE=0,tn.DELAYLOADSTATE_LOADED=1,tn.DELAYLOADSTATE_LOADING=2,tn.DELAYLOADSTATE_NOTLOADED=4,tn.NEVER=512,tn.ALWAYS=519,tn.LESS=513,tn.EQUAL=514,tn.LEQUAL=515,tn.GREATER=516,tn.GEQUAL=518,tn.NOTEQUAL=517,tn.KEEP=7680,tn.REPLACE=7681,tn.INCR=7682,tn.DECR=7683,tn.INVERT=5386,tn.INCR_WRAP=34055,tn.DECR_WRAP=34056,tn.TEXTURE_CLAMP_ADDRESSMODE=0,tn.TEXTURE_WRAP_ADDRESSMODE=1,tn.TEXTURE_MIRROR_ADDRESSMODE=2,tn.TEXTUREFORMAT_ALPHA=0,tn.TEXTUREFORMAT_LUMINANCE=1,tn.TEXTUREFORMAT_LUMINANCE_ALPHA=2,tn.TEXTUREFORMAT_RGB=4,tn.TEXTUREFORMAT_RGBA=5,tn.TEXTUREFORMAT_RED=6,tn.TEXTUREFORMAT_R=6,tn.TEXTUREFORMAT_RG=7,tn.TEXTUREFORMAT_RED_INTEGER=8,tn.TEXTUREFORMAT_R_INTEGER=8,tn.TEXTUREFORMAT_RG_INTEGER=9,tn.TEXTUREFORMAT_RGB_INTEGER=10,tn.TEXTUREFORMAT_RGBA_INTEGER=11,tn.TEXTURETYPE_UNSIGNED_BYTE=0,tn.TEXTURETYPE_UNSIGNED_INT=0,tn.TEXTURETYPE_FLOAT=1,tn.TEXTURETYPE_HALF_FLOAT=2,tn.TEXTURETYPE_BYTE=3,tn.TEXTURETYPE_SHORT=4,tn.TEXTURETYPE_UNSIGNED_SHORT=5,tn.TEXTURETYPE_INT=6,tn.TEXTURETYPE_UNSIGNED_INTEGER=7,tn.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,tn.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,tn.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,tn.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,tn.TEXTURETYPE_UNSIGNED_INT_24_8=12,tn.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,tn.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,tn.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,tn.TEXTURE_NEAREST_SAMPLINGMODE=1,tn.TEXTURE_BILINEAR_SAMPLINGMODE=2,tn.TEXTURE_TRILINEAR_SAMPLINGMODE=3,tn.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,tn.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,tn.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,tn.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,tn.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,tn.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,tn.TEXTURE_NEAREST_LINEAR=7,tn.TEXTURE_NEAREST_NEAREST=1,tn.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,tn.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,tn.TEXTURE_LINEAR_LINEAR=2,tn.TEXTURE_LINEAR_NEAREST=12,tn.TEXTURE_EXPLICIT_MODE=0,tn.TEXTURE_SPHERICAL_MODE=1,tn.TEXTURE_PLANAR_MODE=2,tn.TEXTURE_CUBIC_MODE=3,tn.TEXTURE_PROJECTION_MODE=4,tn.TEXTURE_SKYBOX_MODE=5,tn.TEXTURE_INVCUBIC_MODE=6,tn.TEXTURE_EQUIRECTANGULAR_MODE=7,tn.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,tn.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,tn.SCALEMODE_FLOOR=1,tn.SCALEMODE_NEAREST=2,tn.SCALEMODE_CEILING=3,tn._RescalePostProcessFactory=null,tn._RenderPassIdCounter=0;class nn{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,tn.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,tn.MarkAllMaterialsAsDirty(1))}}nn._DiffuseTextureEnabled=!0,nn._DetailTextureEnabled=!0,nn._DecalMapEnabled=!0,nn._AmbientTextureEnabled=!0,nn._OpacityTextureEnabled=!0,nn._ReflectionTextureEnabled=!0,nn._EmissiveTextureEnabled=!0,nn._SpecularTextureEnabled=!0,nn._BumpTextureEnabled=!0,nn._LightmapTextureEnabled=!0,nn._RefractionTextureEnabled=!0,nn._ColorGradingTextureEnabled=!0,nn._FresnelEnabled=!0,nn._ClearCoatTextureEnabled=!0,nn._ClearCoatBumpTextureEnabled=!0,nn._ClearCoatTintTextureEnabled=!0,nn._SheenTextureEnabled=!0,nn._AnisotropicTextureEnabled=!0,nn._ThicknessTextureEnabled=!0,nn._RefractionIntensityTextureEnabled=!0,nn._TranslucencyIntensityTextureEnabled=!0,nn._IridescenceTextureEnabled=!0;B.IncludesShadersStore.decalFragmentDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;\n#endif\n";B.IncludesShadersStore.defaultFragmentDeclaration="uniform vec4 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\nuniform vec3 vAmbientColor;\nuniform float visibility;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\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 BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)\nuniform vec3 vRefractionPosition;\nuniform vec3 vRefractionSize; \n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\n#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";B.IncludesShadersStore.sceneUboDeclaration="layout(std140,column_major) uniform;\nuniform Scene {\nmat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nmat4 view;\nmat4 projection;\nvec4 vEyePosition;\n};\n";B.IncludesShadersStore.meshUboDeclaration="#ifdef WEBGL2\nuniform mat4 world;\nuniform float visibility;\n#else\nlayout(std140,column_major) uniform;\nuniform Mesh\n{\nmat4 world;\nfloat visibility;\n};\n#endif\n#define WORLD_UBO\n";B.IncludesShadersStore.defaultUboDeclaration="layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor;\nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix;\nvec2 vTangentSpaceParams;\nfloat pointSize;\nfloat alphaCutOff;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec3 vRefractionPosition;\nvec3 vRefractionSize;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nvec3 vAmbientColor;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";B.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";B.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;\nlayout(location=2) out vec4 backColor;\n#define MAX_DEPTH 99999.0\nhighp vec4 gl_FragColor;\nuniform sampler2D oitDepthSampler;\nuniform sampler2D oitFrontColorSampler;\n#endif\n";B.IncludesShadersStore.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n";B.IncludesShadersStore.helperFunctions="const float PI=3.1415926535897932384626433832795;\nconst float HALF_MIN=5.96046448e-08; \nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nconst 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) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn 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}\n#if USE_EXACT_SRGB_CONVERSIONS\nvec3 toLinearSpaceExact(vec3 color)\n{\nvec3 nearZeroSection=0.0773993808*color;\nvec3 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{\nvec3 nearZeroSection=12.92*color;\nvec3 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;\nfloat remainingSection=pow(0.947867299*(color+0.055),2.4);\nreturn 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;\nfloat remainingSection=1.055*pow(color,0.41666)-0.055;\nreturn 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{\nreturn value*value;\n}\nvec3 square(vec3 value)\n{\nreturn value*value;\n}\nfloat pow5(float value) {\nfloat sq=value*value;\nreturn sq*sq*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat normVariance=varianceAmount/255.0;\nfloat dither=mix(-normVariance,normVariance,rand);\nreturn dither;\n}\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=maxEps(max(color.r,max(color.g,color.b)));\nfloat D =max(rgbdMaxRange/maxRGB,1.);\nD =clamp(floor(D)/255.0,0.,1.);\nvec3 rgb=color.rgb*D;\nrgb=toGammaSpace(rgb);\nreturn vec4(clamp(rgb,0.,1.),D); \n}\nvec3 fromRGBD(vec4 rgbd) {\nrgbd.rgb=toLinearSpace(rgbd.rgb);\nreturn rgbd.rgb/rgbd.a;\n}\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\nvec3 intersectPositionWS=vertexPos+origVec*distance;\nreturn intersectPositionWS-cubePos;\n}\n";B.IncludesShadersStore.lightFragmentDeclaration="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform 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}];\nuniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float cascadeBlendFactor{X};\nvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\nuniform highp sampler2DArray depthSampler{X};\nuniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\n#else\nuniform highp sampler2DArray shadowSampler{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);\nvec3 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 shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform 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};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif\n";B.IncludesShadersStore.lightUboDeclaration="#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float cascadeBlendFactor{X};\nvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\nvarying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\nuniform highp sampler2DArray depthSampler{X};\nuniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\nuniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\n#else\nuniform highp sampler2DArray shadowSampler{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);\nvec3 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 shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";B.IncludesShadersStore.lightsFragmentFunctions="struct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w==0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}";B.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{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\n#define inline\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.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}\n#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;\n}\n#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nelse\n{\nfloat 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}\n}\n#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nelse\n{\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nelse\n{\nfloat 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);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n}\n#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nelse\n{\nfloat 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.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n}\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 inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\nvec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);\nfloat shadow=texture2D(shadowSampler,uvDepthLayer);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\nvec2 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;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\nvec2 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;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nelse\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=ZINCLIP;\nfloat shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n}\n#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nelse\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=ZINCLIP;\nvec2 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;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);\nshadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n}\n#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nelse\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=ZINCLIP;\nvec2 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;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);\nshadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);\nshadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);\nshadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);\nshadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);\nshadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);\nshadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n}\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.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst 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{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\nvec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nelse\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nuvDepth.z=ZINCLIP;\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; ithis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._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;e0&&(n.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;ie.priority-t.priority)),this._codeInjectionPoints={};const i={};i[an._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"));this._defineNamesFromPlugins=i}_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;t0&&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.customCode);break}case Wi.PrepareUniformBuffer:{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)e.ubo.addUniform(t.name,t.size),this._uboDeclaration+=`${t.type} ${t.name};\r\n`,this._uniformList.push(t.name);i.vertex&&(this._vertexDeclaration+=i.vertex+"\r\n"),i.fragment&&(this._fragmentDeclaration+=i.fragment+"\r\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){return(t,i)=>{var n;e&&(i=e(t,i)),this._uboDeclaration&&(i=i.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(i=i.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(i=i.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const s=null===(n=this._codeInjectionPoints)||void 0===n?void 0:n[t];if(!s)return i;for(let e in s){let n="";for(const i of this._activePlugins){const s=i.getCustomCode(t);(null==s?void 0:s[e])&&(n+=s[e]+"\r\n")}if(n.length>0)if("!"===e.charAt(0)){e=e.substring(1);let t="g";if("!"===e.charAt(0))t="",e=e.substring(1);else{const i=rn.exec(e);i&&i.length>=2&&(t=i[1],e=e.substring(t.length+1))}t.indexOf("g")<0&&(t+="g");const s=i,r=new RegExp(e,t);let a=r.exec(s);for(;null!==a;){let e=n;for(let t=0;t{e.pluginManager=void 0}))),this._pluginDefineNames=n,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),r&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,n){return!0}hardBindForSubMesh(e,t,i,n){}bindForSubMesh(e,t,i,n){}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){gt.Clone((()=>e),this)}serialize(){return gt.Serialize(this)}parse(e,t,i){gt.Parse((()=>this),e,t,i)}}Qe([ct()],on.prototype,"name",void 0),Qe([ct()],on.prototype,"priority",void 0),Qe([ct()],on.prototype,"registerForExtraEvents",void 0);class ln extends Tt{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class hn extends on{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new ln,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Yi.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&nn.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&&nn.DetailTextureEnabled&&this._isEnabled?(zi.PrepareDefinesForMergedUV(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&&nn.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),zi.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&nn.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){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}Qe([dt("detailTexture"),ht("_markAllSubMeshesAsTexturesDirty")],hn.prototype,"texture",void 0),Qe([ct()],hn.prototype,"diffuseBlendLevel",void 0),Qe([ct()],hn.prototype,"roughnessBlendLevel",void 0),Qe([ct()],hn.prototype,"bumpLevel",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],hn.prototype,"normalBlendMethod",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],hn.prototype,"isEnabled",void 0);const cn={effect:null,subMesh:null};class dn extends Tt{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_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.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!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.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,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_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.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,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.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class un extends Ki{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_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()}))))}get isPrePassCapable(){return!this.disableDepthWrite}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}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new tt(0,0,0),this.diffuseColor=new tt(1,1,1),this.specularColor=new tt(1,1,1),this.emissiveColor=new tt(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._renderTargets=new be(16),this._worldViewProjectionMatrix=Xe.Zero(),this._globalAmbientColor=new tt(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new hn(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new Ci,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),un.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),un.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return!!(un.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(un.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Yi.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Yi.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Wi.GetDefineNames,this._eventInfo),t.materialDefines=new dn(this._eventInfo.defineNames));const n=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=n.getEngine();s._needNormals=zi.PrepareDefinesForLights(n,e,s,!0,this._maxSimultaneousLights,this._disableLighting),zi.PrepareDefinesForMultiview(n,s);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(zi.PrepareDefinesForPrePass(n,s,this.canRenderToMRT&&!a),zi.PrepareDefinesForOIT(n,s,a),s._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,s._needUVs=!1;for(let e=1;e<=6;++e)s["MAINUV"+e]=!1;if(n.texturesEnabled){if(s.DIFFUSEDIRECTUV=0,s.BUMPDIRECTUV=0,s.AMBIENTDIRECTUV=0,s.OPACITYDIRECTUV=0,s.EMISSIVEDIRECTUV=0,s.SPECULARDIRECTUV=0,s.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&un.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;zi.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE")}else s.DIFFUSE=!1;if(this._ambientTexture&&un.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;zi.PrepareDefinesForMergedUV(this._ambientTexture,s,"AMBIENT")}else s.AMBIENT=!1;if(this._opacityTexture&&un.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;zi.PrepareDefinesForMergedUV(this._opacityTexture,s,"OPACITY"),s.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else s.OPACITY=!1;if(this._reflectionTexture&&un.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(s._needNormals=!0,s.REFLECTION=!0,s.ROUGHNESS=this._roughness>0,s.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,s.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===Ji.INVCUBIC_MODE,s.REFLECTIONMAP_3D=this._reflectionTexture.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,s.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case Ji.EXPLICIT_MODE:s.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case Ji.PLANAR_MODE:s.setReflectionMode("REFLECTIONMAP_PLANAR");break;case Ji.PROJECTION_MODE:s.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case Ji.SKYBOX_MODE:s.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case Ji.SPHERICAL_MODE:s.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case Ji.EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case Ji.FIXED_EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case Ji.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case Ji.CUBIC_MODE:case Ji.INVCUBIC_MODE:default:s.setReflectionMode("REFLECTIONMAP_CUBIC")}s.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else s.REFLECTION=!1,s.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&un.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;zi.PrepareDefinesForMergedUV(this._emissiveTexture,s,"EMISSIVE")}else s.EMISSIVE=!1;if(this._lightmapTexture&&un.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;zi.PrepareDefinesForMergedUV(this._lightmapTexture,s,"LIGHTMAP"),s.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,s.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else s.LIGHTMAP=!1;if(this._specularTexture&&un.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;zi.PrepareDefinesForMergedUV(this._specularTexture,s,"SPECULAR"),s.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else s.SPECULAR=!1;if(n.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&un.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;zi.PrepareDefinesForMergedUV(this._bumpTexture,s,"BUMP"),s.PARALLAX=this._useParallax,s.PARALLAXOCCLUSION=this._useParallaxOcclusion,s.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else s.BUMP=!1,s.PARALLAX=!1,s.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&un.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.REFRACTION=!0,s.REFRACTIONMAP_3D=this._refractionTexture.isCube,s.RGBDREFRACTION=this._refractionTexture.isRGBD,s.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else s.REFRACTION=!1;s.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else s.DIFFUSE=!1,s.AMBIENT=!1,s.OPACITY=!1,s.REFLECTION=!1,s.EMISSIVE=!1,s.LIGHTMAP=!1,s.BUMP=!1,s.REFRACTION=!1;s.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),s.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,s.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,s.SPECULAROVERALPHA=this._useSpecularOverAlpha,s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,s.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s),s.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,s.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}s._areFresnelDirty&&(un.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(s.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,s.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,s.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,s.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,s.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,s.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,s._needNormals=!0,s.FRESNEL=!0):s.FRESNEL=!1),zi.PrepareDefinesForMisc(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,s),zi.PrepareDefinesForFrameBoundValues(n,r,this,s,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=s,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),zi.PrepareDefinesForAttributes(e,s,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let o=!1;if(s.isDirty){const i=s._areLightsDisposed;s.markAsProcessed();const a=new sn;s.REFLECTION&&a.addFallback(0,"REFLECTION"),s.SPECULAR&&a.addFallback(0,"SPECULAR"),s.BUMP&&a.addFallback(0,"BUMP"),s.PARALLAX&&a.addFallback(1,"PARALLAX"),s.PARALLAXOCCLUSION&&a.addFallback(0,"PARALLAXOCCLUSION"),s.SPECULAROVERALPHA&&a.addFallback(0,"SPECULAROVERALPHA"),s.FOG&&a.addFallback(1,"FOG"),s.POINTSIZE&&a.addFallback(0,"POINTSIZE"),s.LOGARITHMICDEPTH&&a.addFallback(0,"LOGARITHMICDEPTH"),zi.HandleFallbacksForShadows(s,a,this._maxSimultaneousLights),s.SPECULARTERM&&a.addFallback(0,"SPECULARTERM"),s.DIFFUSEFRESNEL&&a.addFallback(1,"DIFFUSEFRESNEL"),s.OPACITYFRESNEL&&a.addFallback(2,"OPACITYFRESNEL"),s.REFLECTIONFRESNEL&&a.addFallback(3,"REFLECTIONFRESNEL"),s.EMISSIVEFRESNEL&&a.addFallback(4,"EMISSIVEFRESNEL"),s.FRESNEL&&a.addFallback(4,"FRESNEL"),s.MULTIVIEW&&a.addFallback(0,"MULTIVIEW");const l=[Lt.PositionKind];s.NORMAL&&l.push(Lt.NormalKind),s.TANGENT&&l.push(Lt.TangentKind);for(let e=1;e<=6;++e)s["UV"+e]&&l.push(`uv${1===e?"":e}`);s.VERTEXCOLOR&&l.push(Lt.ColorKind),zi.PrepareAttributesForBones(l,e,s,a),zi.PrepareAttributesForInstances(l,s),zi.PrepareAttributesForMorphTargets(l,e,s),zi.PrepareAttributesForBakedVertexAnimation(l,e,s);let h="default";const c=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],d=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],u=["Material","Scene","Mesh"];this._eventInfo.fallbacks=a,this._eventInfo.fallbackRank=0,this._eventInfo.defines=s,this._eventInfo.uniforms=c,this._eventInfo.attributes=l,this._eventInfo.samplers=d,this._eventInfo.uniformBuffersNames=u,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._callbackPluginEventGeneric(Wi.PrepareEffect,this._eventInfo),Ci.AddUniforms(c),Ci.AddSamplers(d),St&&(St.PrepareUniforms(c,s),St.PrepareSamplers(d,s)),zi.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:s,maxSimultaneousLights:this._maxSimultaneousLights}),Bi(c);const f={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,c,u,d,s,l,f));const _=s.toString(),p=t.effect;let m=n.getEngine().createEffect(h,{attributes:l,uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:_,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS},processFinalCode:f.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:s.PREPASS},r);if(this._eventInfo.customCode=void 0,m)if(this._onEffectCreatedObservable&&(cn.effect=m,cn.subMesh=t,this._onEffectCreatedObservable.notifyObservers(cn)),this.allowShaderHotSwapping&&p&&!m.isReady()){if(m=p,s.markAsUnprocessed(),o=this.isFrozen,i)return s._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(m,s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!o,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var n;const s=this.getScene(),r=i.materialDefines;if(!r)return;const a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=a._forceRebindOnNextCall||this._mustRebind(s,a,t.visibility);zi.BindBonesParameters(t,a);const l=this._uniformBuffer;if(o){if(this.bindViewProjection(a),!l.useUbo||!this.isFrozen||!l.isSync||a._forceRebindOnNextCall){if(un.FresnelEnabled&&r.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(l.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),l.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&l.updateColor4("opacityParts",new tt(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(l.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),l.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(l.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),l.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(l.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),l.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&un.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),zi.BindTextureMatrix(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&un.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),zi.BindTextureMatrix(this._ambientTexture,l,"ambient")),this._opacityTexture&&un.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),zi.BindTextureMatrix(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&un.ReflectionTextureEnabled&&(l.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),l.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const e=this._reflectionTexture;l.updateVector3("vReflectionPosition",e.boundingBoxPosition),l.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&un.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),zi.BindTextureMatrix(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&un.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),zi.BindTextureMatrix(this._lightmapTexture,l,"lightmap")),this._specularTexture&&un.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),zi.BindTextureMatrix(this._specularTexture,l,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&un.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),zi.BindTextureMatrix(this._bumpTexture,l,"bump"),s._mirroredCameraPosition?l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&un.RefractionTextureEnabled){let e=1;if(this._refractionTexture.isCube||(l.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),l.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const e=this._refractionTexture;l.updateVector3("vRefractionPosition",e.boundingBoxPosition),l.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),r.SPECULARTERM&&l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",un.EmissiveTextureEnabled?this.emissiveColor:tt.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&un.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&un.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&un.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&un.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&un.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&un.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&un.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&un.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&un.RefractionTextureEnabled&&(this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),ki(a,this,s),this.bindEyePosition(a)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!o&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&zi.BindLights(s,t,a,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==pi.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(a),zi.BindFogParameters(s,t,a),r.NUM_MORPH_INFLUENCERS&&zi.BindMorphTargetParameters(t,a),r.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(n=t.bakedVertexAnimationManager)||void 0===n||n.bind(a,r.INSTANCES)),this.useLogarithmicDepth&&zi.BindLogDepth(r,a,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),l.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),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._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),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._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),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._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e}dispose(e,t){var i,n,s,r,a,o,l,h,c;t&&(null===(i=this._diffuseTexture)||void 0===i||i.dispose(),null===(n=this._ambientTexture)||void 0===n||n.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(r=this._reflectionTexture)||void 0===r||r.dispose(),null===(a=this._emissiveTexture)||void 0===a||a.dispose(),null===(o=this._specularTexture)||void 0===o||o.dispose(),null===(l=this._bumpTexture)||void 0===l||l.dispose(),null===(h=this._lightmapTexture)||void 0===h||h.dispose(),null===(c=this._refractionTexture)||void 0===c||c.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e){const t=gt.Clone((()=>new un(e,this.getScene())),this);return t.name=e,t.id=e,this.stencil.copyTo(t.stencil),t}static Parse(e,t,i){const n=gt.Parse((()=>new un(e.name,t)),e,t,i);return e.stencil&&n.stencil.parse(e.stencil,t,i),n}static get DiffuseTextureEnabled(){return nn.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){nn.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return nn.DetailTextureEnabled}static set DetailTextureEnabled(e){nn.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return nn.AmbientTextureEnabled}static set AmbientTextureEnabled(e){nn.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return nn.OpacityTextureEnabled}static set OpacityTextureEnabled(e){nn.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return nn.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){nn.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return nn.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){nn.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return nn.SpecularTextureEnabled}static set SpecularTextureEnabled(e){nn.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return nn.BumpTextureEnabled}static set BumpTextureEnabled(e){nn.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return nn.LightmapTextureEnabled}static set LightmapTextureEnabled(e){nn.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return nn.RefractionTextureEnabled}static set RefractionTextureEnabled(e){nn.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return nn.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){nn.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return nn.FresnelEnabled}static set FresnelEnabled(e){nn.FresnelEnabled=e}}Qe([dt("diffuseTexture")],un.prototype,"_diffuseTexture",void 0),Qe([ht("_markAllSubMeshesAsTexturesAndMiscDirty")],un.prototype,"diffuseTexture",void 0),Qe([dt("ambientTexture")],un.prototype,"_ambientTexture",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"ambientTexture",void 0),Qe([dt("opacityTexture")],un.prototype,"_opacityTexture",void 0),Qe([ht("_markAllSubMeshesAsTexturesAndMiscDirty")],un.prototype,"opacityTexture",void 0),Qe([dt("reflectionTexture")],un.prototype,"_reflectionTexture",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"reflectionTexture",void 0),Qe([dt("emissiveTexture")],un.prototype,"_emissiveTexture",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"emissiveTexture",void 0),Qe([dt("specularTexture")],un.prototype,"_specularTexture",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"specularTexture",void 0),Qe([dt("bumpTexture")],un.prototype,"_bumpTexture",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"bumpTexture",void 0),Qe([dt("lightmapTexture")],un.prototype,"_lightmapTexture",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"lightmapTexture",void 0),Qe([dt("refractionTexture")],un.prototype,"_refractionTexture",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"refractionTexture",void 0),Qe([ut("ambient")],un.prototype,"ambientColor",void 0),Qe([ut("diffuse")],un.prototype,"diffuseColor",void 0),Qe([ut("specular")],un.prototype,"specularColor",void 0),Qe([ut("emissive")],un.prototype,"emissiveColor",void 0),Qe([ct()],un.prototype,"specularPower",void 0),Qe([ct("useAlphaFromDiffuseTexture")],un.prototype,"_useAlphaFromDiffuseTexture",void 0),Qe([ht("_markAllSubMeshesAsTexturesAndMiscDirty")],un.prototype,"useAlphaFromDiffuseTexture",void 0),Qe([ct("useEmissiveAsIllumination")],un.prototype,"_useEmissiveAsIllumination",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"useEmissiveAsIllumination",void 0),Qe([ct("linkEmissiveWithDiffuse")],un.prototype,"_linkEmissiveWithDiffuse",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"linkEmissiveWithDiffuse",void 0),Qe([ct("useSpecularOverAlpha")],un.prototype,"_useSpecularOverAlpha",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"useSpecularOverAlpha",void 0),Qe([ct("useReflectionOverAlpha")],un.prototype,"_useReflectionOverAlpha",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"useReflectionOverAlpha",void 0),Qe([ct("disableLighting")],un.prototype,"_disableLighting",void 0),Qe([ht("_markAllSubMeshesAsLightsDirty")],un.prototype,"disableLighting",void 0),Qe([ct("useObjectSpaceNormalMap")],un.prototype,"_useObjectSpaceNormalMap",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"useObjectSpaceNormalMap",void 0),Qe([ct("useParallax")],un.prototype,"_useParallax",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"useParallax",void 0),Qe([ct("useParallaxOcclusion")],un.prototype,"_useParallaxOcclusion",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"useParallaxOcclusion",void 0),Qe([ct()],un.prototype,"parallaxScaleBias",void 0),Qe([ct("roughness")],un.prototype,"_roughness",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"roughness",void 0),Qe([ct()],un.prototype,"indexOfRefraction",void 0),Qe([ct()],un.prototype,"invertRefractionY",void 0),Qe([ct()],un.prototype,"alphaCutOff",void 0),Qe([ct("useLightmapAsShadowmap")],un.prototype,"_useLightmapAsShadowmap",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"useLightmapAsShadowmap",void 0),Qe([ft("diffuseFresnelParameters")],un.prototype,"_diffuseFresnelParameters",void 0),Qe([ht("_markAllSubMeshesAsFresnelDirty")],un.prototype,"diffuseFresnelParameters",void 0),Qe([ft("opacityFresnelParameters")],un.prototype,"_opacityFresnelParameters",void 0),Qe([ht("_markAllSubMeshesAsFresnelAndMiscDirty")],un.prototype,"opacityFresnelParameters",void 0),Qe([ft("reflectionFresnelParameters")],un.prototype,"_reflectionFresnelParameters",void 0),Qe([ht("_markAllSubMeshesAsFresnelDirty")],un.prototype,"reflectionFresnelParameters",void 0),Qe([ft("refractionFresnelParameters")],un.prototype,"_refractionFresnelParameters",void 0),Qe([ht("_markAllSubMeshesAsFresnelDirty")],un.prototype,"refractionFresnelParameters",void 0),Qe([ft("emissiveFresnelParameters")],un.prototype,"_emissiveFresnelParameters",void 0),Qe([ht("_markAllSubMeshesAsFresnelDirty")],un.prototype,"emissiveFresnelParameters",void 0),Qe([ct("useReflectionFresnelFromSpecular")],un.prototype,"_useReflectionFresnelFromSpecular",void 0),Qe([ht("_markAllSubMeshesAsFresnelDirty")],un.prototype,"useReflectionFresnelFromSpecular",void 0),Qe([ct("useGlossinessFromSpecularMapAlpha")],un.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"useGlossinessFromSpecularMapAlpha",void 0),Qe([ct("maxSimultaneousLights")],un.prototype,"_maxSimultaneousLights",void 0),Qe([ht("_markAllSubMeshesAsLightsDirty")],un.prototype,"maxSimultaneousLights",void 0),Qe([ct("invertNormalMapX")],un.prototype,"_invertNormalMapX",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"invertNormalMapX",void 0),Qe([ct("invertNormalMapY")],un.prototype,"_invertNormalMapY",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"invertNormalMapY",void 0),Qe([ct("twoSidedLighting")],un.prototype,"_twoSidedLighting",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],un.prototype,"twoSidedLighting",void 0),Qe([ct()],un.prototype,"useLogarithmicDepth",null),Se("BABYLON.StandardMaterial",un),pi.DefaultMaterialFactory=e=>new un("default material",e);class fn{static get ForceFullSceneLoadingForIncremental(){return fn._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){fn._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return fn._ShowLoadingScreen}static set ShowLoadingScreen(e){fn._ShowLoadingScreen=e}static get loggingLevel(){return fn._LoggingLevel}static set loggingLevel(e){fn._LoggingLevel=e}static get CleanBoneMatrixWeights(){return fn._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){fn._CleanBoneMatrixWeights=e}}var _n;fn._ForceFullSceneLoadingForIncremental=!1,fn._ShowLoadingScreen=!0,fn._CleanBoneMatrixWeights=!1,fn._LoggingLevel=0,function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(_n||(_n={}));class pn{static get ForceFullSceneLoadingForIncremental(){return fn.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){fn.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return fn.ShowLoadingScreen}static set ShowLoadingScreen(e){fn.ShowLoadingScreen=e}static get loggingLevel(){return fn.loggingLevel}static set loggingLevel(e){fn.loggingLevel=e}static get CleanBoneMatrixWeights(){return fn.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){fn.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return pn._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){return pn._RegisteredPlugins[e]||(c.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("."),n=e.substring(i,e.length).toLowerCase();return pn._GetPluginForExtension(n)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let n="Unable to load from "+e.url;return t?n+=`: ${t}`:i&&(n+=`: ${i}`),n}static _LoadData(e,t,i,n,s,r,a){const o=pn._GetDirectLoad(e.url),l=a?pn._GetPluginForExtension(a):o?pn._GetPluginForDirectLoad(e.url):pn._GetPluginForFilename(e.url);let h;if(h=void 0!==l.plugin.createPlugin?l.plugin.createPlugin():l.plugin,!h)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(h),o&&(h.canDirectLoad&&h.canDirectLoad(e.url)||!me(e.url))){if(h.directLoad){const e=h.directLoad(t,o);e.then?e.then((e=>{i(h,e)})).catch((e=>{s("Error in directLoad of _loadData: "+e,e)})):i(h,e)}else i(h,o);return h}const c=l.isBinary,d=(e,n)=>{t.isDisposed?s("Scene has been disposed"):i(h,e,n)};let u=null,f=!1;const _=h.onDisposeObservable;_&&_.add((()=>{f=!0,u&&(u.abort(),u=null),r()}));const p=()=>{if(f)return;const i=(e,t)=>{s(null==e?void 0:e.statusText,t)},r=e.file||e.url;u=h.loadFile?h.loadFile(t,r,d,n,c,i):t._loadFile(r,d,n,!0,c,i)},m=t.getEngine();let g=m.enableOfflineSupport;if(g){let i=!1;for(const n of t.disableOfflineSupportExceptionRules)if(n.test(e.url)){i=!0;break}g=!i}return g&&tn.OfflineProviderFactory?t.offlineProvider=tn.OfflineProviderFactory(e.url,p,m.disableManifestCheck):p(),h}static _GetFileInfo(e,t){let i,n,s=null;if(t)if(t.name){const e=t;i=`file:${e.name}`,n=e.name,s=e}else if("string"==typeof t&&t.startsWith("data:"))i=t,n="";else{const s=t;if("/"===s.substr(0,1))return Me.Error("Wrong sceneFilename parameter"),null;i=e+s,n=s}else i=e,n=Me.GetFilename(e),e=Me.GetFolderPath(e);return{url:i,rootUrl:e,name:n,file:s}}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="",n=m.LastCreatedScene,s=null,r=null,a=null,o=null){if(!n)return c.Error("No scene available to import mesh to"),null;const l=pn._GetFileInfo(t,i);if(!l)return null;const h={};n.addPendingData(h);const d=()=>{n.removePendingData(h)},u=(e,t)=>{const i=pn._FormatErrorMessage(l,e,t);a?a(n,i,new A(i,T,t)):c.Error(i),d()},f=r?e=>{try{r(e)}catch(e){u("Error in onProgress callback: "+e,e)}}:void 0,_=(e,t,i,r,a,o,c)=>{if(n.importedMeshesFiles.push(l.url),s)try{s(e,t,i,r,a,o,c)}catch(e){u("Error in onSuccess callback: "+e,e)}n.removePendingData(h)};return pn._LoadData(l,n,((t,i,s)=>{if(t.rewriteRootURL&&(l.rootUrl=t.rewriteRootURL(l.rootUrl,s)),t.importMesh){const s=t,r=new Array,a=new Array,o=new Array;if(!s.importMesh(e,n,i,l.rootUrl,r,a,o,u))return;n.loadingPluginName=t.name,_(r,a,o,[],[],[],[])}else t.importMeshAsync(e,n,i,l.rootUrl,f,l.name).then((e=>{n.loadingPluginName=t.name,_(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights)})).catch((e=>{u(e.message,e)}))}),f,u,d,o)}static ImportMeshAsync(e,t,i="",n=m.LastCreatedScene,s=null,r=null){return new Promise(((a,o)=>{pn.ImportMesh(e,t,i,n,((e,t,i,n,s,r,o)=>{a({meshes:e,particleSystems:t,skeletons:i,animationGroups:n,transformNodes:s,geometries:r,lights:o})}),s,((e,t,i)=>{o(i||new Error(t))}),r)}))}static Load(e,t="",i=m.LastCreatedEngine,n=null,s=null,r=null,a=null){return i?pn.Append(e,t,new pi(i),n,s,r,a):(Me.Error("No engine available"),null)}static LoadAsync(e,t="",i=m.LastCreatedEngine,n=null,s=null){return new Promise(((r,a)=>{pn.Load(e,t,i,(e=>{r(e)}),n,((e,t,i)=>{a(i||new Error(t))}),s)}))}static Append(e,t="",i=m.LastCreatedScene,n=null,s=null,r=null,a=null){if(!i)return c.Error("No scene available to append to"),null;const o=pn._GetFileInfo(e,t);if(!o)return null;const l={};i.addPendingData(l);const h=()=>{i.removePendingData(l)};pn.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1})));const d=(e,t)=>{const n=pn._FormatErrorMessage(o,e,t);r?r(i,n,new A(n,T,t)):c.Error(n),h()},u=s?e=>{try{s(e)}catch(e){d("Error in onProgress callback",e)}}:void 0,f=()=>{if(n)try{n(i)}catch(e){d("Error in onSuccess callback",e)}i.removePendingData(l)};return pn._LoadData(o,i,((e,t)=>{if(e.load){if(!e.load(i,t,o.rootUrl,d))return;i.loadingPluginName=e.name,f()}else e.loadAsync(i,t,o.rootUrl,u,o.name).then((()=>{i.loadingPluginName=e.name,f()})).catch((e=>{d(e.message,e)}))}),u,d,h,a)}static AppendAsync(e,t="",i=m.LastCreatedScene,n=null,s=null){return new Promise(((r,a)=>{pn.Append(e,t,i,(e=>{r(e)}),n,((e,t,i)=>{a(i||new Error(t))}),s)}))}static LoadAssetContainer(e,t="",i=m.LastCreatedScene,n=null,s=null,r=null,a=null){if(!i)return c.Error("No scene available to load asset container to"),null;const o=pn._GetFileInfo(e,t);if(!o)return null;const l={};i.addPendingData(l);const h=()=>{i.removePendingData(l)},d=(e,t)=>{const n=pn._FormatErrorMessage(o,e,t);r?r(i,n,new A(n,T,t)):c.Error(n),h()},u=s?e=>{try{s(e)}catch(e){d("Error in onProgress callback",e)}}:void 0,f=e=>{if(n)try{n(e)}catch(e){d("Error in onSuccess callback",e)}i.removePendingData(l)};return pn._LoadData(o,i,((e,t)=>{if(e.loadAssetContainer){const n=e.loadAssetContainer(i,t,o.rootUrl,d);if(!n)return;i.loadingPluginName=e.name,f(n)}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,o.rootUrl,u,o.name).then((t=>{i.loadingPluginName=e.name,f(t)})).catch((e=>{d(e.message,e)})):d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),u,d,h,a)}static LoadAssetContainerAsync(e,t="",i=m.LastCreatedScene,n=null,s=null){return new Promise(((r,a)=>{pn.LoadAssetContainer(e,t,i,(e=>{r(e)}),n,((e,t,i)=>{a(i||new Error(t))}),s)}))}static ImportAnimations(e,t="",i=m.LastCreatedScene,n=!0,s=_n.Clean,r=null,a=null,o=null,l=null,h=null){if(!i)return void c.Error("No scene available to load animations to");if(n){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(s){case _n.Clean:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case _n.Stop:i.animationGroups.forEach((e=>{e.stop()}));break;case _n.Sync:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case _n.NoSync:break;default:return void c.Error("Unknown animation group loading mode value '"+s+"'")}const d=i.animatables.length;this.LoadAssetContainer(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(d),r),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),a&&a(i)}),o,l,h)}static ImportAnimationsAsync(e,t="",i=m.LastCreatedScene,n=!0,s=_n.Clean,r=null,a=null,o=null,l=null,h=null){return new Promise(((a,l)=>{pn.ImportAnimations(e,t,i,n,s,r,(e=>{a(e)}),o,((e,t,i)=>{l(i||new Error(t))}),h)}))}}pn.NO_LOGGING=0,pn.MINIMAL_LOGGING=1,pn.SUMMARY_LOGGING=2,pn.DETAILED_LOGGING=3,pn.OnPluginActivatedObservable=new s,pn._RegisteredPlugins={},pn._ShowingLoadingScreen=!1,ie.prototype._createDepthStencilCubeTexture=function(e,t,i){const n=new W(this,H.DepthStencil);if(n.isCube=!0,1===this.webGLVersion)return c.Error("Depth cube texture is not supported by WebGL 1."),n;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t},r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,n,!0),this._setupDepthStencilTexture(n,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction),i._depthStencilTexture=n,i._depthStencilTextureWithStencil=s.generateStencil;for(let t=0;t<6;t++)s.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH24_STENCIL8,e,e,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH_COMPONENT24,e,e,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(n),n},ie.prototype._partialLoadFile=function(e,t,i,n,s=null){this._loadFile(e,(e=>{i[t]=e,i._internalCount++,6===i._internalCount&&n(i)}),void 0,void 0,!0,((e,t)=>{s&&e&&s(e.status+" "+e.statusText,t)}))},ie.prototype._cascadeLoadFiles=function(e,t,i,n=null){const s=[];s._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,s,t,n)},ie.prototype._cascadeLoadImgs=function(e,t,i,n,s=null,r){const a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(n[o],o,a,e,t,i,s,r)},ie.prototype._partialLoadImg=function(e,t,i,n,s,r,a=null,o){const l=xe();de(e,(e=>{i[t]=e,i._internalCount++,n&&n.removePendingData(l),6===i._internalCount&&r&&r(s,i)}),((e,t)=>{n&&n.removePendingData(l),a&&a(e,t)}),n?n.offlineProvider:null,o),n&&n.addPendingData(l)},ie.prototype._setCubeMapTextureParams=function(e,t,i){const n=this._gl;n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MIN_FILTER,t?n.LINEAR_MIPMAP_LINEAR:n.LINEAR),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),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null)},ie.prototype.createCubeTextureBase=function(e,t,i,n,s=null,r=null,a,o=null,l=!1,h=0,d=0,u=null,f=null,_=null,p=!1){const m=u||new W(this,H.Cube);m.isCube=!0,m.url=e,m.generateMipMaps=!n,m._lodGenerationScale=h,m._lodGenerationOffset=d,m._useSRGBBuffer=!!p&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!n),this._doNotHandleContextLost||(m._extension=o,m._files=i);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 v=null;for(const e of ie._TextureLoaders)if(e.canLoad(A)){v=e;break}const S=(u,E)=>{e===g?r&&u&&r(u.status+" "+u.statusText,E):(c.Warn(`Failed to load ${e}, falling back to the ${g}`),this.createCubeTextureBase(g,t,i,!!n,s,r,a,o,l,h,d,m,f,_,p))};if(v){const n=e=>{f&&f(m,e),v.loadCubeData(e,m,l,s,r)};i&&6===i.length?v.supportCascades?this._cascadeLoadFiles(t,(e=>n(e.map((e=>new Uint8Array(e))))),i,r):r?r("Textures type does not support cascades."):c.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,S)}else{if(!i)throw new Error("Cannot load cubemap because files were not defined");this._cascadeLoadImgs(t,m,((e,t)=>{_&&_(e,t)}),i,r)}return this._internalTexturesCache.push(m),m},ie.prototype.createCubeTexture=function(e,t,i,n,s=null,r=null,a,o=null,l=!1,h=0,d=0,u=null,f,_=!1){const p=this._gl;return this.createCubeTextureBase(e,t,i,!!n,s,r,a,o,l,h,d,u,(e=>this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?ie.GetExponentOfTwo(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,r=i,o=[p.TEXTURE_CUBE_MAP_POSITIVE_X,p.TEXTURE_CUBE_MAP_POSITIVE_Y,p.TEXTURE_CUBE_MAP_POSITIVE_Z,p.TEXTURE_CUBE_MAP_NEGATIVE_X,p.TEXTURE_CUBE_MAP_NEGATIVE_Y,p.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const l=a?this._getInternalFormat(a,e._useSRGBBuffer):e._useSRGBBuffer?p.SRGB8_ALPHA8:p.RGBA;let h=a?this._getInternalFormat(a):p.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(h=l);for(let e=0;en+=e)),new mn(n,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,n=!0){const s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const r=new mn(e,t,null,!1,null,null,null,void 0,!0,i,n);return t.useDelayedTextureLoading=s,r}constructor(e,t,i=null,n=!1,r=null,a=null,o=null,l=5,h=!1,c=null,d=!1,u=.8,f=0,_,p){var m;super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new s,this.boundingBoxPosition=ze.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this.name=e,this.url=e,this._noMipmap=n,this.hasAlpha=!1,this._format=l,this.isCube=!0,this._textureMatrix=Xe.Identity(),this._createPolynomials=d,this.coordinatesMode=Ji.CUBIC_MODE,this._extensions=i,this._files=r,this._forcedExtension=c,this._loaderOptions=_,this._useSRGBBuffer=p,this._lodScale=u,this._lodOffset=f,(e||r)&&this.updateURL(e,c,a,h,o,i,null===(m=this.getScene())||void 0===m?void 0:m.useDelayedTextureLoading,r)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,n=!1,s=null,r=null,a=!1,o=null){this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,t&&(this._forcedExtension=t);const l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),c=0===h.indexOf(".dds"),d=0===h.indexOf(".env"),u=0===h.indexOf(".basis");if(d?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=n,n&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),o)this._files=o;else if(u||d||c||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-1!==e.getActiveTextures().indexOf(this)))),this._textureMatrix=e)}_loadTexture(e=null,t=null){var i;const n=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const r=()=>{var t;this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1)),e&&e()},a=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),Ji.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Me.SetImmediate((()=>r())):this._texture.onLoadedObservable.add((()=>r())):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,n,this._lodScale,this._lodOffset,e,a,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,n,this._files,this._noMipmap,e,a,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),null===(i=this._texture)||void 0===i||i.onLoadedObservable.add((()=>this.onLoadObservable.notifyObservers(this))))}static Parse(e,t,i){const n=gt.Parse((()=>{let n=!1;return e.prefiltered&&(n=e.prefiltered),new mn(i+e.name,t,e.extensions,!1,e.files||null,null,null,void 0,n,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(n.boundingBoxPosition=ze.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(n.boundingBoxSize=ze.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t{const t=new mn(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}Qe([ct()],mn.prototype,"url",void 0),Qe([pt()],mn.prototype,"boundingBoxPosition",void 0),Qe([pt()],mn.prototype,"boundingBoxSize",null),Qe([ct("rotationY")],mn.prototype,"rotationY",null),Qe([ct("files")],mn.prototype,"_files",void 0),Qe([ct("forcedExtension")],mn.prototype,"_forcedExtension",void 0),Qe([ct("extensions")],mn.prototype,"_extensions",void 0),Qe([lt(12,"textureMatrix")],mn.prototype,"_textureMatrix",void 0),Ji._CubeTextureParser=mn.Parse,Se("BABYLON.CubeTexture",mn);class gn{static ConvertPanoramaToCubemap(e,t,i,n){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(n,this.FACE_FRONT,e,t,i),back:this.CreateCubemapTexture(n,this.FACE_BACK,e,t,i),left:this.CreateCubemapTexture(n,this.FACE_LEFT,e,t,i),right:this.CreateCubemapTexture(n,this.FACE_RIGHT,e,t,i),up:this.CreateCubemapTexture(n,this.FACE_UP,e,t,i),down:this.CreateCubemapTexture(n,this.FACE_DOWN,e,t,i),size:n,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,n,s){const r=new ArrayBuffer(e*e*4*3),a=new Float32Array(r),o=t[1].subtract(t[0]).scale(1/e),l=t[3].subtract(t[2]).scale(1/e),h=1/e;let c=0;for(let r=0;rMath.PI;)s-=2*Math.PI;let a=s/Math.PI;const o=r/Math.PI;a=.5*a+.5;let l=Math.round(a*i);l<0?l=0:l>=i&&(l=i-1);let h=Math.round(o*n);h<0?h=0:h>=n&&(h=n-1);const c=n-h-1;return{r:t[c*i*3+3*l+0],g:t[c*i*3+3*l+1],b:t[c*i*3+3*l+2]}}}gn.FACE_LEFT=[new ze(-1,-1,-1),new ze(1,-1,-1),new ze(-1,1,-1),new ze(1,1,-1)],gn.FACE_RIGHT=[new ze(1,-1,1),new ze(-1,-1,1),new ze(1,1,1),new ze(-1,1,1)],gn.FACE_FRONT=[new ze(1,-1,-1),new ze(1,-1,1),new ze(1,1,-1),new ze(1,1,1)],gn.FACE_BACK=[new ze(-1,-1,1),new ze(-1,-1,-1),new ze(-1,1,1),new ze(-1,1,-1)],gn.FACE_DOWN=[new ze(1,1,-1),new ze(1,1,1),new ze(-1,1,-1),new ze(-1,1,1)],gn.FACE_UP=[new ze(-1,-1,-1),new ze(-1,-1,1),new ze(1,-1,-1),new ze(1,-1,1)];class En{static _Ldexp(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,n,s,r){s>0?(s=this._Ldexp(1,s-136),e[r+0]=t*s,e[r+1]=i*s,e[r+2]=n*s):(e[r+0]=0,e[r+1]=0,e[r+2]=0)}static _ReadStringLine(e,t){let i="",n="";for(let s=t;s32767)throw"HDR Bad header format, unsupported size";return a+=n.length+1,{height:t,width:i,dataPosition:a}}static GetCubeMapTextureData(e,t){const i=new Uint8Array(e),n=this.RGBE_ReadHeader(i),s=this.RGBE_ReadPixels(i,n);return gn.ConvertPanoramaToCubemap(s,n.width,n.height,t)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i=t.height;const n=t.width;let s,r,a,o,l,h=t.dataPosition,c=0,d=0,u=0;const f=new ArrayBuffer(4*n),_=new Uint8Array(f),p=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(p);for(;i>0;){if(s=e[h++],r=e[h++],a=e[h++],o=e[h++],2!=s||2!=r||128&a||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((a<<8|o)!=n)throw"HDR Bad header format, wrong scan line width";for(c=0,u=0;u<4;u++)for(d=(u+1)*n;c128){if(l=s-128,0==l||l>d-c)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)_[c++]=r}else{if(l=s,0==l||l>d-c)throw"HDR Bad Format, bad scanline data (non-run)";if(_[c++]=r,--l>0)for(let t=0;t0;){for(l=0;l1,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],vn=(e,t)=>Tn[e]*An[e](t),Sn=[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 Rn{constructor(){this.preScaled=!1,this.l00=ze.Zero(),this.l1_1=ze.Zero(),this.l10=ze.Zero(),this.l11=ze.Zero(),this.l2_2=ze.Zero(),this.l2_1=ze.Zero(),this.l20=ze.Zero(),this.l21=ze.Zero(),this.l22=ze.Zero()}addLight(e,t,i){Ke.Vector3[0].set(t.r,t.g,t.b);const n=Ke.Vector3[0],s=Ke.Vector3[1];n.scaleToRef(i,s),s.scaleToRef(vn(0,e),Ke.Vector3[2]),this.l00.addInPlace(Ke.Vector3[2]),s.scaleToRef(vn(1,e),Ke.Vector3[2]),this.l1_1.addInPlace(Ke.Vector3[2]),s.scaleToRef(vn(2,e),Ke.Vector3[2]),this.l10.addInPlace(Ke.Vector3[2]),s.scaleToRef(vn(3,e),Ke.Vector3[2]),this.l11.addInPlace(Ke.Vector3[2]),s.scaleToRef(vn(4,e),Ke.Vector3[2]),this.l2_2.addInPlace(Ke.Vector3[2]),s.scaleToRef(vn(5,e),Ke.Vector3[2]),this.l2_1.addInPlace(Ke.Vector3[2]),s.scaleToRef(vn(6,e),Ke.Vector3[2]),this.l20.addInPlace(Ke.Vector3[2]),s.scaleToRef(vn(7,e),Ke.Vector3[2]),this.l21.addInPlace(Ke.Vector3[2]),s.scaleToRef(vn(8,e),Ke.Vector3[2]),this.l22.addInPlace(Ke.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(Sn[0]),this.l1_1.scaleInPlace(Sn[1]),this.l10.scaleInPlace(Sn[2]),this.l11.scaleInPlace(Sn[3]),this.l2_2.scaleInPlace(Sn[4]),this.l2_1.scaleInPlace(Sn[5]),this.l20.scaleInPlace(Sn[6]),this.l21.scaleInPlace(Sn[7]),this.l22.scaleInPlace(Sn[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(Tn[0]),this.l1_1.scaleInPlace(Tn[1]),this.l10.scaleInPlace(Tn[2]),this.l11.scaleInPlace(Tn[3]),this.l2_2.scaleInPlace(Tn[4]),this.l2_1.scaleInPlace(Tn[5]),this.l20.scaleInPlace(Tn[6]),this.l21.scaleInPlace(Tn[7]),this.l22.scaleInPlace(Tn[8])}updateFromArray(e){return ze.FromArrayToRef(e[0],0,this.l00),ze.FromArrayToRef(e[1],0,this.l1_1),ze.FromArrayToRef(e[2],0,this.l10),ze.FromArrayToRef(e[3],0,this.l11),ze.FromArrayToRef(e[4],0,this.l2_2),ze.FromArrayToRef(e[5],0,this.l2_1),ze.FromArrayToRef(e[6],0,this.l20),ze.FromArrayToRef(e[7],0,this.l21),ze.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return ze.FromFloatsToRef(e[0],e[1],e[2],this.l00),ze.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),ze.FromFloatsToRef(e[6],e[7],e[8],this.l10),ze.FromFloatsToRef(e[9],e[10],e[11],this.l11),ze.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),ze.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),ze.FromFloatsToRef(e[18],e[19],e[20],this.l20),ze.FromFloatsToRef(e[21],e[22],e[23],this.l21),ze.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new Rn).updateFromArray(e)}static FromPolynomial(e){const t=new Rn;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 Cn{constructor(){this.x=ze.Zero(),this.y=ze.Zero(),this.z=ze.Zero(),this.xx=ze.Zero(),this.yy=ze.Zero(),this.zz=ze.Zero(),this.xy=ze.Zero(),this.yz=ze.Zero(),this.zx=ze.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=Rn.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){Ke.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=Ke.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),Ke.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),Ke.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(Ke.Vector3[0]).addInPlace(Ke.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(Ke.Vector3[0]).subtractInPlace(Ke.Vector3[1]),this.zz.copyFrom(e.l00),Ke.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(Ke.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 Cn).updateFromHarmonics(e)}static FromArray(e){const t=new Cn;return ze.FromArrayToRef(e[0],0,t.x),ze.FromArrayToRef(e[1],0,t.y),ze.FromArrayToRef(e[2],0,t.z),ze.FromArrayToRef(e[3],0,t.xx),ze.FromArrayToRef(e[4],0,t.yy),ze.FromArrayToRef(e[5],0,t.zz),ze.FromArrayToRef(e[6],0,t.yz),ze.FromArrayToRef(e[7],0,t.zx),ze.FromArrayToRef(e[8],0,t.xy),t}}class xn{constructor(e,t,i,n){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=n}}class Mn{static ConvertCubeMapTextureToSphericalPolynomial(e){var t;if(!e.isCube)return null;null===(t=e.getScene())||void 0===t||t.getEngine().flushFramebuffer();const i=e.getSize().width,n=e.readPixels(0,void 0,void 0,!1),s=e.readPixels(1,void 0,void 0,!1);let r,a;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),a=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),a=e.readPixels(3,void 0,void 0,!1));const o=e.readPixels(4,void 0,void 0,!1),l=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace;let c=0;return 1!=e.textureType&&2!=e.textureType||(c=1),new Promise((e=>{Promise.all([s,n,r,a,o,l]).then((([t,n,s,r,a,o])=>{const l={size:i,right:n,left:t,up:s,down:r,front:a,back:o,format:5,type:c,gammaSpace:h};e(this.ConvertCubeMapToSphericalPolynomial(l))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new Rn;let i=0;const n=2/e.size,s=n,r=.5*n,a=r-1;for(let o=0;o<6;o++){const l=this._FileFaces[o],h=e[l.name];let c=a;const d=5===e.format?4:3;for(let o=0;o{this._indexBuffer=e.createIndexBuffer(r);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({})}restoreStates(){this.engine.depthCullingState.depthTest=!0,this.engine.stencilState.stencilTest=!0}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;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[Lt.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[Lt.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class yn{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new s;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 n=e.defines?e.defines.join("\n"):"";this._drawWrapper=new $(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,n,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new U(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,n,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add((()=>{this.effect._pipelineContext=null,this.effect._wasPreviouslyReady=!1,this.effect._prepareEffect()})))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}B.ShadersStore.hdrFilteringVertexShader="attribute vec2 position;\nvarying vec3 direction;\nuniform vec3 up;\nuniform vec3 right;\nuniform vec3 front;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nmat3 view=mat3(up,right,front);\ndirection=view*vec3(position,1.0);\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";B.IncludesShadersStore.importanceSampling="vec3 hemisphereCosSample(vec2 u) {\nfloat phi=2.*PI*u.x;\nfloat cosTheta2=1.-u.y;\nfloat cosTheta=sqrt(cosTheta2);\nfloat sinTheta=sqrt(1.-cosTheta2);\nreturn vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);\n}\nvec3 hemisphereImportanceSampleDggx(vec2 u,float a) {\nfloat phi=2.*PI*u.x;\nfloat cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));\nfloat cosTheta=sqrt(cosTheta2);\nfloat sinTheta=sqrt(1.-cosTheta2);\nreturn vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);\n}\nvec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { \nfloat phi=2.*PI*u.x;\nfloat sinTheta=pow(u.y,a/(2.*a+1.));\nfloat cosTheta=sqrt(1.-sinTheta*sinTheta);\nreturn vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);\n}";B.IncludesShadersStore.pbrBRDFFunctions="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\nreturn 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);\n}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {\nvec2 UV=vec2(NdotV,perceptualRoughness);\nvec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;\n}\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;\n}\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}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfloat getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)\n{\nfloat c=1.0-NdotV;\nfloat c3=c*c*c;\nreturn 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));\n}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));\n}\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) {\nvec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;\nreturn sheenEnvironmentReflectance;\n}\n#endif\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);\n}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);\n}\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);\nvec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);\nreturn 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);\nvec3 getIORTfromAirToSurfaceR0(vec3 f0) {\nvec3 sqrtF0=sqrt(f0);\nreturn (1.+sqrtF0)/(1.-sqrtF0);\n}\nvec3 getR0fromIORs(vec3 iorT,float iorI) {\nreturn square((iorT-vec3(iorI))/(iorT+vec3(iorI)));\n}\nfloat getR0fromIORs(float iorT,float iorI) {\nreturn square((iorT-iorI)/(iorT+iorI));\n}\nvec3 evalSensitivity(float opd,vec3 shift) {\nfloat phase=2.0*PI*opd*1.0e-9;\nconst vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);\nconst vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);\nconst vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);\nvec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);\nxyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));\nxyz/=1.0685e-7;\nvec3 srgb=XYZ_TO_REC709*xyz;\nreturn srgb;\n}\nvec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {\nvec3 I=vec3(1.0);\nfloat iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));\nfloat sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));\nfloat cosTheta2Sq=1.0-sinTheta2Sq;\nif (cosTheta2Sq<0.0) {\nreturn I;\n}\nfloat cosTheta2=sqrt(cosTheta2Sq);\nfloat R0=getR0fromIORs(iridescenceIOR,outsideIOR);\nfloat R12=fresnelSchlickGGX(cosTheta1,R0,1.);\nfloat R21=R12;\nfloat T121=1.0-R12;\nfloat phi12=0.0;\nif (iridescenceIOR{this._effectRenderer=new bn(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled((()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()}))})):(c.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}}class Dn{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 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 texture(){var e,t;return null!==(t=null===(e=this._textures)||void 0===e?void 0:e[0])&&void 0!==t?t:null}get textures(){return this._textures}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const n=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,n}constructor(e,t,i,n){this._textures=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=n,this._depthStencilTexture=null}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]&&i&&this._textures[t].dispose(),this._textures[t]=e}createDepthStencilTexture(e=0,t=!0,i=!1,n=1,s=14){var r;return null===(r=this._depthStencilTexture)||void 0===r||r.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:n,depthTextureFormat:s},this),this._depthStencilTexture}_shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var e,t,i,n,s,r;let a=null;if(this._isMulti){const e=this.textures;if(e&&e.length>0){let t=!1,i=e.length;const n=e[e.length-1]._source;n!==H.Depth&&n!==H.DepthStencil||(t=!0,i--);const s=[],r=[];for(let t=0;t1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e,t;if(this._textures)for(let i=0;null!==(t=i<(null===(e=this._textures)||void 0===e?void 0:e.length))&&void 0!==t&&t;++i)this._textures[i].dispose();this._textures=null}dispose(e=!1){var t;e||(null===(t=this._depthStencilTexture)||void 0===t||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class On extends Dn{constructor(e,t,i,n,s){super(e,t,i,n),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._context=s}_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}_shareDepth(e){super._shareDepth(e);const t=this._context,i=this._depthStencilBuffer,n=e._MSAAFramebuffer||e._framebuffer;e._depthStencilBuffer&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=this._depthStencilBuffer,this._engine._bindUnboundFramebuffer(n),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i=-1,n=0){if(!e._hardwareTexture)return;const s=this._context,r=this._framebuffer,a=this._engine._currentFramebuffer;this._engine._bindUnboundFramebuffer(r);const o=s[this._engine.webGLVersion>1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],l=-1!==i?s.TEXTURE_CUBE_MAP_POSITIVE_X+i:s.TEXTURE_2D;s.framebufferTexture2D(s.FRAMEBUFFER,o,l,e._hardwareTexture.underlyingResource,n),this._engine._bindUnboundFramebuffer(a)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}dispose(e=!1){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)}}ie.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const n=new On(e,t,i,this,this._gl);return this._renderTargetWrapperCache.push(n),n},ie.prototype.createRenderTargetTexture=function(e,t){var i,n;const s=this._createHardwareRenderTargetWrapper(!1,!1,e);let r,a=!0,o=!1,l=!1,h=1;void 0!==t&&"object"==typeof t&&(a=null===(i=t.generateDepthBuffer)||void 0===i||i,o=!!t.generateStencilBuffer,l=!!t.noColorAttachment,r=t.colorAttachment,h=null!==(n=t.samples)&&void 0!==n?n:1);const c=r||(l?null:this._createInternalTexture(e,t,!0,H.RenderTarget)),d=e.width||e,u=e.height||e,f=this._currentFramebuffer,_=this._gl,p=_.createFramebuffer();return this._bindUnboundFramebuffer(p),s._depthStencilBuffer=this._setupFramebufferDepthAttachments(o,a,d,u),c&&!c.is2DArray&&_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_2D,c._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(f),s._framebuffer=p,s._generateDepthBuffer=a,s._generateStencilBuffer=o,s.setTextures(c),this.updateRenderTargetTextureSampleCount(s,h),s},ie.prototype.createDepthStencilTexture=function(e,t,i){if(t.isCube){const n=e.width||e;return this._createDepthStencilCubeTexture(n,t,i)}return this._createDepthStencilTexture(e,t,i)},ie.prototype._createDepthStencilTexture=function(e,t,i){const n=this._gl,s=e.layers||0,r=0!==s?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D,a=new W(this,H.DepthStencil);if(!this._caps.depthTextureExtension)return c.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(15!==o.depthTextureFormat&&16!==o.depthTextureFormat&&17!==o.depthTextureFormat&&13!==o.depthTextureFormat&&14!==o.depthTextureFormat&&18!==o.depthTextureFormat)return c.Error("Depth texture format is not supported."),a;a.format=o.depthTextureFormat}else a.format=o.generateStencil?13:16;const l=17===a.format||13===a.format||18===a.format;i._depthStencilTexture=a,i._depthStencilTextureWithStencil=l;let h=n.UNSIGNED_INT;15===a.format?h=n.UNSIGNED_SHORT:17===a.format||13===a.format?h=n.UNSIGNED_INT_24_8:14===a.format?h=n.FLOAT:18===a.format&&(h=n.FLOAT_32_UNSIGNED_INT_24_8_REV);const d=l?n.DEPTH_STENCIL:n.DEPTH_COMPONENT;let u=d;this.webGLVersion>1&&(15===a.format?u=n.DEPTH_COMPONENT16:16===a.format?u=n.DEPTH_COMPONENT24:17===a.format||13===a.format?u=n.DEPTH24_STENCIL8:14===a.format?u=n.DEPTH_COMPONENT32F:18===a.format&&(u=n.DEPTH32F_STENCIL8)),a.is2DArray?n.texImage3D(r,0,u,a.width,a.height,s,0,d,h,null):n.texImage2D(r,0,u,a.width,a.height,0,d,h,null),this._bindTextureDirectly(r,null),this._internalTexturesCache.push(a);const f=i;if(f._depthStencilBuffer){const e=this._currentFramebuffer;this._bindUnboundFramebuffer(f._framebuffer),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,null),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,null),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.STENCIL_ATTACHMENT,n.RENDERBUFFER,null),this._bindUnboundFramebuffer(e),n.deleteRenderbuffer(f._depthStencilBuffer),f._depthStencilBuffer=null}return a},ie.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 n=e.texture._hardwareTexture;if(n._MSAARenderBuffer&&(i.deleteRenderbuffer(n._MSAARenderBuffer),n._MSAARenderBuffer=null),t>1&&"function"==typeof i.renderbufferStorageMultisample){const s=i.createFramebuffer();if(!s)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=s,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const r=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBAMultiSampleBufferFormat(e.texture.type),i.COLOR_ATTACHMENT0,!1);if(!r)throw new Error("Unable to create multi sampled framebuffer");n._MSAARenderBuffer=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},ie.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),n={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};n.generateStencilBuffer=n.generateDepthBuffer&&n.generateStencilBuffer,(1!==n.type||this._caps.textureFloatLinearFiltering)&&(2!==n.type||this._caps.textureHalfFloatLinearFiltering)||(n.samplingMode=1);const s=this._gl,r=new W(this,H.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,r,!0);const a=this._getSamplingParameters(n.samplingMode,n.generateMipMaps);1!==n.type||this._caps.textureFloat||(n.type=0,c.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,a.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,a.min),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);for(let t=0;t<6;t++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(n.type,n.format),e,e,0,this._getInternalFormat(n.format),this._getWebGLTextureType(n.type),null);const o=s.createFramebuffer();return this._bindUnboundFramebuffer(o),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(n.generateStencilBuffer,n.generateDepthBuffer,e,e),n.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=o,i._generateDepthBuffer=n.generateDepthBuffer,i._generateStencilBuffer=n.generateStencilBuffer,r.width=e,r.height=e,r.isReady=!0,r.isCube=!0,r.samples=1,r.generateMipMaps=n.generateMipMaps,r.samplingMode=n.samplingMode,r.type=n.type,r.format=n.format,this._internalTexturesCache.push(r),i.setTextures(r),i};const Ln="passPixelShader",Nn="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}";B.ShadersStore[Ln]=Nn;const Fn=Ln,wn=Nn;class Bn{static _CreateDumpRenderer(){if(!Bn._DumpToolsEngine){const e=document.createElement("canvas"),t=new ie(e,!1,{preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1});t.getCaps().parallelShaderCompile=void 0;const i=new bn(t),n=new yn({engine:t,name:Fn,fragmentShader:wn,samplerNames:["textureSampler"]});Bn._DumpToolsEngine={canvas:e,engine:t,renderer:i,wrapper:n}}return Bn._DumpToolsEngine}static async DumpFramebuffer(e,t,i,n,s="image/png",r){const a=await i.readPixels(0,0,e,t),o=new Uint8Array(a.buffer);Bn.DumpData(e,t,o,n,s,r,!0)}static DumpDataAsync(e,t,i,n="image/png",s,r=!1,a=!1,o){return new Promise((l=>{Bn.DumpData(e,t,i,(e=>l(e)),n,s,r,a,o)}))}static DumpData(e,t,i,n,s="image/png",r,a=!1,o=!1,l){const h=Bn._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){const e=new Uint8Array(i.length);let t=i.length;for(;t--;){const n=i[t];e[t]=n<0?0:n>1?1:Math.round(255*n)}i=e}const c=h.engine.createRawTexture(i,e,t,5,!1,!a,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",c),h.renderer.draw(),o?Me.ToBlob(h.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;n&&n(t)},t.readAsArrayBuffer(e)}),s,l):Me.EncodeScreenshotCanvasData(h.canvas,n,s,r,l),c.dispose()}static Dispose(){Bn._DumpToolsEngine&&(Bn._DumpToolsEngine.wrapper.dispose(),Bn._DumpToolsEngine.renderer.dispose(),Bn._DumpToolsEngine.engine.dispose()),Bn._DumpToolsEngine=null}}Me.DumpData=Bn.DumpData,Me.DumpDataAsync=Bn.DumpDataAsync,Me.DumpFramebuffer=Bn.DumpFramebuffer;class Un extends Ji{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=ke(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{var i;const n=this._renderList?this._renderList.length:0;(0===t&&n>0||0===n)&&(null===(i=this.getScene())||void 0===i||i.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()})))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new s,this.onAfterUnbindObservable=new s,this.onBeforeRenderObservable=new s,this.onAfterRenderObservable=new s,this.onClearObservable=new s,this.onResizeObservable=new s,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=ze.Zero(),!(i=this.getScene()))return;const x=this.getScene().getEngine();this._coordinatesMode=Ji.PROJECTION_MODE,this.renderList=new Array,this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=o,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=x.onResizeObservable.add((()=>{})),this._generateMipMaps=!!n,this._doNotChangeAspectRatio=r,this._renderingManager=new kt(i),this._renderingManager._useSceneAutoClearSetup=!0,d||(this._renderTargetOptions={generateMipMaps:n,type:a,format:null!==(R=this._format)&&void 0!==R?R:void 0,samplingMode:this.samplingMode,generateDepthBuffer:h,generateStencilBuffer:c,samples:_,creationFlags:p,noColorAttachment:m,useSRGBBuffer:g,colorAttachment:C},this.samplingMode===Ji.NEAREST_SAMPLINGMODE&&(this.wrapU=Ji.CLAMP_ADDRESSMODE,this.wrapV=Ji.CLAMP_ADDRESSMODE),f||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=Ji.INVCUBIC_MODE,this._textureMatrix=Xe.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,n=1,s=14){var r;null===(r=this._renderTarget)||void 0===r||r.createDepthStencilTexture(e,t,i,n,s)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(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(){return this._size.layers||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){var t;const i=this.isCube;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null;const n=this.getScene();n&&(this._processSizeParameter(e),this._renderTarget=i?n.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):n.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){var n;const s=this.getScene();if(!s)return i;const r=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(let e=0;e1||this.activeCamera&&this.activeCamera!==s.activeCamera)&&s.setTransformMatrix(s.activeCamera.getViewMatrix(),s.activeCamera.getProjectionMatrix(!0)),r.setViewport(s.activeCamera.viewport)),s.resetCachedMaterial(),h}_bestReflectionRenderTargetDimension(e,t){const i=e*t,n=tn.NearestPOT(i+16384/(128+i));return Math.min(tn.FloorPOT(e),n)}_prepareRenderingManager(e,t,i,n){const s=this.getScene();if(!s)return;this._renderingManager.reset();const r=s.getRenderId();for(let a=0;a{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,n){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):n&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,n=0,s=null){var r,a,o,l,h,c;const d=this.getScene();if(!d)return;const u=d.getEngine();if(null===(r=u._debugPushGroup)||void 0===r||r.call(u,`render to face #${e} layer #${n}`,1),this._prepareFrame(d,e,n,t),this.is2DArray?(u.currentRenderPassId=this._renderPassIds[n],this.onBeforeRenderObservable.notifyObservers(n)):(u.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),u.snapshotRendering&&1===u.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(u):this.skipInitialClear||u.clear(this.clearColor||d.clearColor,!0,!0,!0);else{let r=null;const c=this.renderList?this.renderList:d.getActiveMeshes().data,f=this.renderList?this.renderList.length:d.getActiveMeshes().length;this.getCustomRenderList&&(r=this.getCustomRenderList(this.is2DArray?n:e,c,f)),r?this._prepareRenderingManager(r,r.length,s,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(c,f,s,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),r=c);for(const t of d._beforeRenderTargetClearStage)t.action(this,e,n);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(u):this.skipInitialClear||u.clear(this.clearColor||d.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0);for(const t of d._beforeRenderTargetDrawStage)t.action(this,e,n);this._renderingManager.render(this.customRenderFunction,r,this.renderParticles,this.renderSprites);for(const t of d._afterRenderTargetDrawStage)t.action(this,e,n);const _=null!==(o=null===(a=this._texture)||void 0===a?void 0:a.generateMipMaps)&&void 0!==o&&o;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,null!==(l=this._renderTarget)&&void 0!==l?l:void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&d.postProcessManager._finalizeFrame(!1,null!==(h=this._renderTarget)&&void 0!==h?h:void 0,e);for(const t of d._afterRenderTargetPostProcessStage)t.action(this,e,n);this._texture&&(this._texture.generateMipMaps=_),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0),i&&Bn.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),u)}this._unbindFrameBuffer(u,e),this._texture&&this.isCube&&5===e&&u.generateMipMapsForCubemap(this._texture),null===(c=u._debugPopGroup)||void 0===c||c.call(u,1)}setRenderingOrder(e,t=null,i=null,n=null){this._renderingManager.setRenderingOrder(e,t,i,n)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new Un(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=0&&t.customRenderTargets.splice(i,1);for(const e of t.cameras)i=e.customRenderTargets.indexOf(this),i>=0&&e.customRenderTargets.splice(i,1);null===(e=this._renderTarget)||void 0===e||e.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===Un.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=Un.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}Un.REFRESHRATE_RENDER_ONCE=0,Un.REFRESHRATE_RENDER_ONEVERYFRAME=1,Un.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,Ji._CreateRenderTargetTexture=(e,t,i,n,s)=>new Un(e,t,i,n);class kn{static RegisterShaderCodeProcessing(e,t){t?kn._CustomShaderCodeProcessing[null!=e?e:""]=t:delete kn._CustomShaderCodeProcessing[null!=e?e:""]}static _GetShaderCodeProcessing(e){var t;return null!==(t=kn._CustomShaderCodeProcessing[e])&&void 0!==t?t: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,n,r,a,o=1,l,h,c=null,d=0,u="postprocess",f,_=!1,p=5,m=O.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.alphaMode=0,this.animations=new Array,this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new be(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new Ve(1,1),this._texelSize=Ve.Zero(),this.onActivateObservable=new s,this.onSizeChangedObservable=new s,this.onApplyObservable=new s,this.onBeforeRenderObservable=new s,this.onAfterRenderObservable=new s,this.name=e,null!=a?(this._camera=a,this._scene=a.getScene(),a.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):l&&(this._engine=l,this._engine.postProcesses.push(this)),this._options=r,this.renderTargetSamplingMode=o||1,this._reusable=h||!1,this._textureType=d,this._textureFormat=p,this._shaderLanguage=m,this._samplers=n||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=u,this._parameters=i||[],this._parameters.push("scale"),this._indexParameters=f,this._drawWrapper=new $(this._engine),_||this.updateEffect(c)}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 be(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,n,s,r,a,o){var l,h;const c=kn._GetShaderCodeProcessing(this.name);if(null==c?void 0:c.defineCustomBindings){const n=null!==(l=null==t?void 0:t.slice())&&void 0!==l?l:[];n.push(...this._parameters);const s=null!==(h=null==i?void 0:i.slice())&&void 0!==h?h:[];s.push(...this._samplers),e=c.defineCustomBindings(this.name,e,n,s),t=n,i=s}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:null!=a?a:this._vertexUrl,fragment:null!=o?o:this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:[],samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:null!=s?s:null,onError:null!=r?r:null,indexParameters:n||this._indexParameters,processCodeAfterIncludes:(null==c?void 0:c.processCodeAfterIncludes)?(e,t)=>c.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:(null==c?void 0:c.processFinalCode)?(e,t)=>c.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 n=0;n=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let r=null;for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}let _;if(this._shareOutputWithPostProcess)_=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)_=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{let e;_=this.inputTexture;for(let t=0;t=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=gt.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 n=Re(e.customType);if(!n||!n._Parse)return null;const s=t?t.getCameraById(e.cameraId):null;return n._Parse(e,s,t,i)}static _Parse(e,t,i,n){return gt.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,n)}}kn._CustomShaderCodeProcessing={},Qe([ct()],kn.prototype,"uniqueId",void 0),Qe([ct()],kn.prototype,"name",void 0),Qe([ct()],kn.prototype,"width",void 0),Qe([ct()],kn.prototype,"height",void 0),Qe([ct()],kn.prototype,"renderTargetSamplingMode",void 0),Qe([mt()],kn.prototype,"clearColor",void 0),Qe([ct()],kn.prototype,"autoClear",void 0),Qe([ct()],kn.prototype,"alphaMode",void 0),Qe([ct()],kn.prototype,"alphaConstants",void 0),Qe([ct()],kn.prototype,"enablePixelPerfectMode",void 0),Qe([ct()],kn.prototype,"forceFullscreenViewport",void 0),Qe([ct()],kn.prototype,"scaleMode",void 0),Qe([ct()],kn.prototype,"alwaysForcePOT",void 0),Qe([ct("samples")],kn.prototype,"_samples",void 0),Qe([ct()],kn.prototype,"adaptScaleToCurrentViewport",void 0),Se("BABYLON.PostProcess",kn);B.ShadersStore.passCubePixelShader="varying vec2 vUV;\nuniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec2 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 Gn extends kn{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,n,s,r,a=0,o=!1){super(e,"pass",null,null,t,i,n,s,r,void 0,a,void 0,null,o)}static _Parse(e,t,i,n){return gt.Parse((()=>new Gn(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,n)}}let Vn,zn;function Hn(e){Vn||(Vn=new Float32Array(1),zn=new Int32Array(Vn.buffer)),Vn[0]=e;const t=zn[0];let i=t>>16&32768,n=t>>12&2047;const s=t>>23&255;return s<103?i:s>142?(i|=31744,i|=(255==s?0:1)&&8388607&t,i):s<113?(n|=2048,i|=(n>>114-s)+(n>>113-s&1),i):(i|=s-112<<10|n>>1,i+=1&n,i)}function Wn(e){const t=(32768&e)>>15,i=(31744&e)>>10,n=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(n/Math.pow(2,10)):31==i?n?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+n/Math.pow(2,10))}function Xn(e,t,i,n){let s,r=1;1===n?s=new Float32Array(t*i*4):2===n?(s=new Uint16Array(t*i*4),r=15360):s=7===n?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let n=0;nnew Gn("rescale",1,null,2,e,!1,0),ie.prototype.updateRawTexture=function(e,t,i,n,s=null,r=0,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===n||!!n),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=r,e.invertY=n,e._compression=s),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[s],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},ie.prototype.createRawTexture=function(e,t,i,n,s,r,a,o=null,l=0,h=0,c=!1){const d=new W(this,H.Raw);d.baseWidth=t,d.baseHeight=i,d.width=t,d.height=i,d.format=n,d.generateMipMaps=s,d.samplingMode=a,d.invertY=r,d._compression=o,d.type=l,d._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this._doNotHandleContextLost||(d._bufferView=e),this.updateRawTexture(d,e,n,r,o,l,d._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,d,!0);const u=this._getSamplingParameters(a,s);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,u.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,u.min),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(d),d},ie.prototype.createRawCubeTexture=function(e,t,i,n,s,r,a,o=null){const l=this._gl,h=new W(this,H.CubeRaw);h.isCube=!0,h.format=i,h.type=n,this._doNotHandleContextLost||(h._bufferViewArray=e);const d=this._getWebGLTextureType(n);let u=this._getInternalFormat(i);u===l.RGB&&(u=l.RGBA),d!==l.FLOAT||this._caps.textureFloatLinearFiltering?d!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?d!==l.FLOAT||this._caps.textureFloatRender?d!==l.HALF_FLOAT||this._caps.colorBufferFloat||(s=!1,c.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(s=!1,c.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(s=!1,a=1,c.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(s=!1,a=1,c.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."));const f=t,_=f;if(h.width=f,h.height=_,h.invertY=r,h._compression=o,!this.needPOTTextures||Me.IsExponentOfTwo(h.width)&&Me.IsExponentOfTwo(h.height)||(s=!1),e)this.updateRawCubeTexture(h,e,i,n,r,o);else{const e=this._getRGBABufferInternalSizedFormat(n),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,d,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),e&&s&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const p=this._getSamplingParameters(a,s);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,p.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,p.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=s,h.samplingMode=a,h.isReady=!0,h},ie.prototype.updateRawCubeTexture=function(e,t,i,n,s,r=null,a=0){e._bufferViewArray=t,e.format=i,e.type=n,e.invertY=s,e._compression=r;const o=this._gl,l=this._getWebGLTextureType(n);let h=this._getInternalFormat(i);const c=this._getRGBABufferInternalSizedFormat(n);let d=!1;h===o.RGB&&(h=o.RGBA,d=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===s||!!s),e.width%4!=0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let s=t[i];r?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,a,this.getCaps().s3tc[r],e.width,e.height,0,s):(d&&(s=Xn(s,e.width,e.height,n)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,a,c,e.width,e.height,0,h,l,s))}(!this.needPOTTextures||Me.IsExponentOfTwo(e.width)&&Me.IsExponentOfTwo(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},ie.prototype.createRawCubeTextureFromUrl=function(e,t,i,n,s,r,a,o,l=null,h=null,c=3,d=!1){const u=this._gl,f=this.createRawCubeTexture(null,i,n,s,!r,d,c,null);null==t||t.addPendingData(f),f.url=e,this._internalTexturesCache.push(f);const _=e=>{const i=f.width,r=a(e);if(r){if(o){const e=this._getWebGLTextureType(s);let t=this._getInternalFormat(n);const a=this._getRGBABufferInternalSizedFormat(s);let l=!1;t===u.RGB&&(t=u.RGBA,l=!0),this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const h=o(r);for(let n=0;n>n;for(let i=0;i<6;i++){let o=h[n][i];l&&(o=Xn(o,r,r,s)),u.texImage2D(i,n,a,r,r,0,t,e,o)}}this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(f,r,n,s,d);f.isReady=!0,null==t||t.removePendingData(f),f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,(e=>{_(e)}),void 0,null==t?void 0:t.offlineProvider,!0,((e,i)=>{null==t||t.removePendingData(f),h&&e&&h(e.status+" "+e.statusText,i)})),f},ie.prototype.createRawTexture2DArray=Yn(!1),ie.prototype.createRawTexture3D=Yn(!0),ie.prototype.updateRawTexture2DArray=Kn(!1),ie.prototype.updateRawTexture3D=Kn(!0),qi.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(qi.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=Mn.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});class jn extends qi{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(Xe.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,n=!1,r=!0,a=!1,o=!1,l=null,h=null){var c;super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=ze.Zero(),this.onLoadObservable=new s,e&&(this._coordinatesMode=Ji.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=Xe.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),l&&l()},this._onError=h,this.gammaSpace=a,this._noMipmap=n,this._size=i,this._generateHarmonics=r,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?Me.SetImmediate((()=>this._onLoad())):this._texture.onLoadedObservable.add(this._onLoad):(null===(c=this.getScene())||void 0===c?void 0:c.useDelayedTextureLoading)?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const t=this._onLoad,i=new Pn(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,(e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const t=En.GetCubeMapTextureData(e,this._size);if(this._generateHarmonics){const e=Mn.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}const n=[];let s=null,r=null;for(let e=0;e<6;e++){2===i?r=new Uint16Array(this._size*this._size*3):0===i&&(s=new Uint8Array(this._size*this._size*3));const a=t[jn._FacesMapping[e]];if(this.gammaSpace||r||s)for(let e=0;e255){const e=255/r;t*=e,i*=e,n*=e}s[3*e+0]=t,s[3*e+1]=i,s[3*e+2]=n}r?n.push(r):s?n.push(s):n.push(a)}return n}),null,this._onLoad,this._onError)}clone(){const e=new jn(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var t;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&(null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(this))))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let n=null;return e.name&&!e.isRenderTarget&&(n=new jn(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),n.name=e.name,n.hasAlpha=e.hasAlpha,n.level=e.level,n.coordinatesMode=e.coordinatesMode,n.isBlocking=e.isBlocking),n&&(e.boundingBoxPosition&&(n.boundingBoxPosition=ze.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(n.boundingBoxSize=ze.FromArray(e.boundingBoxSize)),e.rotationY&&(n.rotationY=e.rotationY)),n}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}jn._FacesMapping=["right","left","up","down","front","back"],Se("BABYLON.HDRCubeTexture",jn);class qn extends qi{constructor(e,t,i,n=!1,s=!0,r=null,a=null){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=Ji.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._noMipmap=n,this.gammaSpace=s,this._onLoad=r,this._onError=a,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?r&&(this._texture.isReady?Me.SetImmediate((()=>r())):this._texture.onLoadedObservable.add(r)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(this._loadTexture.bind(this),this._onError)}_loadImage(e,t){const i=document.createElement("canvas");de(this.url,(t=>{this._width=t.width,this._height=t.height,i.width=this._width,i.height=this._height;const n=i.getContext("2d");n.drawImage(t,0,0);const s=n.getImageData(0,0,t.width,t.height);this._buffer=s.data.buffer,i.remove(),e()}),((e,i)=>{t&&t(`${this.getClassName()} could not be loaded`,i)}),null)}_loadTexture(){const e=this.getScene();e&&(this._texture=e.getEngine().createRawCubeTextureFromUrl(this.url,e,this._size,4,e.getEngine().getCaps().textureFloat?1:7,this._noMipmap,(()=>{const e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=gn.ConvertPanoramaToCubemap(e,this._width,this._height,this._size),i=[];for(let e=0;e<6;e++){const n=t[qn._FacesMapping[e]];i.push(n)}return i}),null,this._onLoad,this._onError))}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(3*e.byteLength/4);let n=0;for(let s=0;s{this._onDoneCallback(t,i)}),((e,t)=>{this._onErrorCallback(i,e,t)}))}runTask(e,t,i){throw new Error("runTask is not implemented")}reset(){this._taskState=Qn.INIT}_onErrorCallback(e,t,i){this._taskState=Qn.ERROR,this._errorObject={message:t,exception:i},this.onError&&this.onError(this,t,i),e()}_onDoneCallback(e,t){try{this._taskState=Qn.DONE,this._isCompleted=!0,this.onSuccess&&this.onSuccess(this),e()}catch(e){this._onErrorCallback(t,"Task is done, error executing success callback(s)",e)}}}class $n{constructor(e,t,i){this.remainingCount=e,this.totalCount=t,this.task=i}}class es extends Jn{constructor(e,t,i,n,s){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=n,this.extension=s}runTask(e,t,i){pn.LoadAssetContainer(this.rootUrl,this.sceneFilename,e,(e=>{this.loadedContainer=e,this.loadedMeshes=e.meshes,this.loadedTransformNodes=e.transformNodes,this.loadedParticleSystems=e.particleSystems,this.loadedSkeletons=e.skeletons,this.loadedAnimationGroups=e.animationGroups,t()}),null,((e,t,n)=>{i(t,n)}),this.extension)}}class ts extends Jn{constructor(e,t,i,n,s){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=n,this.extension=s}runTask(e,t,i){pn.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,e,((e,i,n,s,r)=>{this.loadedMeshes=e,this.loadedTransformNodes=r,this.loadedParticleSystems=i,this.loadedSkeletons=n,this.loadedAnimationGroups=s,t()}),null,((e,t,n)=>{i(t,n)}),this.extension)}}class is extends Jn{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.text=e,t()}),void 0,!1,!1,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class ns extends Jn{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.data=e,t()}),void 0,!0,!0,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class ss extends Jn{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){const n=new Image;Me.SetCorsBehavior(this.url,n),n.onload=()=>{this.image=n,t()},n.onerror=e=>{i("Error loading image",e)},n.src=this.url}}class rs extends Jn{constructor(e,t,i,n=!0,s=Ji.TRILINEAR_SAMPLINGMODE){super(e),this.name=e,this.url=t,this.noMipmap=i,this.invertY=n,this.samplingMode=s}runTask(e,t,i){this.texture=new Ji(this.url,e,this.noMipmap,this.invertY,this.samplingMode,(()=>{t()}),((e,t)=>{i(e,t)}))}}class as extends Jn{constructor(e,t,i,n,s,r){super(e),this.name=e,this.url=t,this.extensions=i,this.noMipmap=n,this.files=s,this.prefiltered=r}runTask(e,t,i){this.texture=new mn(this.url,e,this.extensions,this.noMipmap,this.files,(()=>{t()}),((e,t)=>{i(e,t)}),void 0,this.prefiltered)}}class os extends Jn{constructor(e,t,i,n=!1,s=!0,r=!1,a=!1){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=n,this.generateHarmonics=s,this.gammaSpace=r,this.reserved=a}runTask(e,t,i){this.texture=new jn(this.url,e,this.size,this.noMipmap,this.generateHarmonics,this.gammaSpace,this.reserved,(()=>{t()}),((e,t)=>{i(e,t)}))}}class ls extends Jn{constructor(e,t,i,n=!1,s=!0){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=n,this.gammaSpace=s}runTask(e,t,i){this.texture=new qn(this.url,e,this.size,this.noMipmap,this.gammaSpace,(()=>{t()}),((e,t)=>{i(e,t)}))}}class hs{constructor(e){this._isLoading=!1,this._tasks=new Array,this._waitingTasksCount=0,this._totalTasksCount=0,this.onTaskSuccessObservable=new s,this.onTaskErrorObservable=new s,this.onTasksDoneObservable=new s,this.onProgressObservable=new s,this.useDefaultLoadingScreen=!0,this.autoHideLoadingUI=!0,this._scene=e||m.LastCreatedScene}addContainerTask(e,t,i,n,s){const r=new es(e,t,i,n,s);return this._tasks.push(r),r}addMeshTask(e,t,i,n,s){const r=new ts(e,t,i,n,s);return this._tasks.push(r),r}addTextFileTask(e,t){const i=new is(e,t);return this._tasks.push(i),i}addBinaryFileTask(e,t){const i=new ns(e,t);return this._tasks.push(i),i}addImageTask(e,t){const i=new ss(e,t);return this._tasks.push(i),i}addTextureTask(e,t,i,n,s=Ji.TRILINEAR_SAMPLINGMODE){const r=new rs(e,t,i,n,s);return this._tasks.push(r),r}addCubeTextureTask(e,t,i,n,s,r){const a=new as(e,t,i,n,s,r);return this._tasks.push(a),a}addHDRCubeTextureTask(e,t,i,n=!1,s=!0,r=!1,a=!1){const o=new os(e,t,i,n,s,r,a);return this._tasks.push(o),o}addEquiRectangularCubeTextureAssetTask(e,t,i,n=!1,s=!0){const r=new ls(e,t,i,n,s);return this._tasks.push(r),r}removeTask(e){const t=this._tasks.indexOf(e);t>-1&&this._tasks.splice(t,1)}_decreaseWaitingTasksCount(e){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,e),this.onProgressObservable.notifyObservers(new $n(this._waitingTasksCount,this._totalTasksCount,e))}catch(e){c.Error("Error running progress callbacks."),console.log(e)}if(0===this._waitingTasksCount){try{const e=this._tasks.slice();this.onFinish&&this.onFinish(e);for(const t of e)if(t.taskState===Qn.DONE){const e=this._tasks.indexOf(t);e>-1&&this._tasks.splice(e,1)}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(e){c.Error("Error running tasks-done callbacks."),console.log(e)}this._isLoading=!1,this.autoHideLoadingUI&&this._scene.getEngine().hideLoadingUI()}}_runTask(e){const t=(t,i)=>{e._setErrorObject(t,i),this.onTaskError?this.onTaskError(e):e.onError||c.Error(this._formatTaskErrorMessage(e)),this.onTaskErrorObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)};e.run(this._scene,(()=>{try{this.onTaskSuccess&&this.onTaskSuccess(e),this.onTaskSuccessObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)}catch(e){t("Error executing task success callbacks",e)}}),t)}_formatTaskErrorMessage(e){let t="Unable to complete task "+e.name;return e.errorObject.message&&(t+=`: ${e.errorObject.message}`),e.errorObject.exception&&(t+=`: ${e.errorObject.exception}`),t}reset(){return this._isLoading=!1,this._tasks=new Array,this}load(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(let e=0;e{this._isLoading?e():(this.onTasksDoneObservable.addOnce((i=>{i&&i.length?t(i):e()})),this.load())}))}}!function(e){e[e.cTFETC1=0]="cTFETC1",e[e.cTFETC2=1]="cTFETC2",e[e.cTFBC1=2]="cTFBC1",e[e.cTFBC3=3]="cTFBC3",e[e.cTFBC4=4]="cTFBC4",e[e.cTFBC5=5]="cTFBC5",e[e.cTFBC7=6]="cTFBC7",e[e.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",e[e.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",e[e.cTFASTC_4x4=10]="cTFASTC_4x4",e[e.cTFATC_RGB=11]="cTFATC_RGB",e[e.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",e[e.cTFRGBA32=13]="cTFRGBA32",e[e.cTFRGB565=14]="cTFRGB565",e[e.cTFBGR565=15]="cTFBGR565",e[e.cTFRGBA4444=16]="cTFRGBA4444",e[e.cTFFXT1_RGB=17]="cTFFXT1_RGB",e[e.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",e[e.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",e[e.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",e[e.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"}(Zn||(Zn={}));const cs={JSModuleURL:"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.js",WasmModuleURL:"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.wasm"};let ds=null,us=null,fs=0;const _s=(e,t)=>{var i,n;let s=null===(i=t._gl)||void 0===i?void 0:i.TEXTURE_2D;e.isCube&&(s=null===(n=t._gl)||void 0===n?void 0:n.TEXTURE_CUBE_MAP),t._bindTextureDirectly(s,e,!0)},ps={JSModuleURL:cs.JSModuleURL,WasmModuleURL:cs.WasmModuleURL,GetInternalFormatFromBasisFormat:(e,t)=>{let i;switch(e){case Zn.cTFETC1:i=36196;break;case Zn.cTFBC1:i=33776;break;case Zn.cTFBC4:i=33779;break;case Zn.cTFASTC_4x4:i=37808;break;case Zn.cTFETC2:i=37496;break;case Zn.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i},TranscodeAsync:(e,t)=>{const i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise(((e,n)=>{(ds||(ds=new Promise(((e,t)=>{us?e(us):Me.LoadFileAsync(cs.WasmModuleURL).then((i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");const n=URL.createObjectURL(new Blob([`(${ms})()`],{type:"application/javascript"}));us=new Worker(n);const s=i=>{"init"===i.data.action?(us.removeEventListener("message",s),e(us)):"error"===i.data.action&&t(i.data.error||"error initializing worker")};us.addEventListener("message",s),us.postMessage({action:"init",url:cs.JSModuleURL,wasmBinary:i})})).catch(t)}))),ds).then((()=>{const s=fs++,r=t=>{"transcode"===t.data.action&&t.data.id===s&&(us.removeEventListener("message",r),t.data.success?e(t.data):n("Transcode is not supported on this device"))};us.addEventListener("message",r);const a=new Uint8Array(i.byteLength);a.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),us.postMessage({action:"transcode",id:s,imageData:a,config:t,ignoreSupportedFormats:!1},[a.buffer])}),(e=>{n(e)}))}))},LoadTextureFromTranscodeResult:(e,t)=>{const i=e.getEngine();for(let n=0;n{i._releaseTexture(t),_s(e,i)}))}else{e.width=s.width,e.height=s.height,e.generateMipMaps=t.fileInfo.images[n].levels.length>1;const r=ps.GetInternalFormatFromBasisFormat(t.format,i);e.format=r,_s(e,i),t.fileInfo.images[n].levels.forEach(((t,s)=>{i._uploadCompressedDataToTextureDirectly(e,r,t.width,t.height,t.transcodedPixels,n,s)})),!i._features.basisNeedsPOT||Le.Log2(e.width)%1==0&&Le.Log2(e.height)%1==0||(Me.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),e._cachedWrapU=Ji.CLAMP_ADDRESSMODE,e._cachedWrapV=Ji.CLAMP_ADDRESSMODE)}}}};function ms(){const e=0,t=1,i=2,n=3,s=6,r=8,a=9,o=10,l=14;let h=null;function c(e,t,i,n,s){const r=e.getImageTranscodedSizeInBytes(t,i,n);let a=new Uint8Array(r);return e.transcodeImage(a,t,i,n,1,0)?(s&&(a=function(e,t,i,n){const s=new Uint16Array(4),r=new Uint16Array(i*n),a=i/4,o=n/4;for(let t=0;t>2&3],r[h++]=s[l>>4&3],r[h++]=s[l>>6&3]}}return r}(a,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)),a):null}onmessage=d=>{if("init"===d.data.action){if(!h){try{importScripts(d.data.url)}catch(e){postMessage({action:"error",error:e})}h=BASIS({wasmBinary:d.data.wasmBinary})}null!==h&&h.then((e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})}))}else if("transcode"===d.data.action){const h=d.data.config,u=d.data.imageData,f=new BASIS.BasisFile(u),_=function(e){const t=e.getHasAlpha(),i=e.getNumImages(),n=[];for(let t=0;t>8)}static _GetRGBArrayBuffer(e,t,i,n,s,r,a,o){const l=new Uint8Array(n),h=new Uint8Array(s,i);let c=0;for(let i=0;i>8&255,x>>16&255,x>>24&255)))}var x;const M=Cs._ExtractLongWordOrder(u[23]),I=Cs._ExtractLongWordOrder(u[24]),b=Cs._ExtractLongWordOrder(u[25]),y=Cs._ExtractLongWordOrder(u[26]);C&&(v=e._getRGBABufferInternalSizedFormat(n.textureType)),E=1,u[2]&gs&&!1!==s&&(E=Math.max(1,u[7]));const P=o||0,D=e.getCaps();for(let s=P;s0?n.sphericalPolynomial=Mn.ConvertCubeMapToSphericalPolynomial({size:u[4],right:h[0],left:h[1],up:h[2],down:h[3],front:h[4],back:h[5],format:5,type:1,gammaSpace:!1}):n.sphericalPolynomial=void 0}}Cs.StoreLODInAlphaChannel=!1,ie.prototype.createPrefilteredCubeTexture=function(e,t,i,n,s=null,r=null,a,o=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(s&&s(null));const r=e.texture;if(l?e.info.sphericalPolynomial&&(r._sphericalPolynomial=e.info.sphericalPolynomial):r._sphericalPolynomial=new Cn,r._source=H.CubePrefiltered,this.getCaps().textureLOD)return void(s&&s(r));const a=this._gl,o=e.width;if(!o)return;const h=[];for(let s=0;s<3;s++){const l=1-s/2,d=n,u=Le.Log2(o)*i+n,f=d+(u-d)*l,_=Math.round(Math.min(Math.max(f,0),u)),p=new W(this,H.Temp);if(p.type=r.type,p.format=r.format,p.width=Math.pow(2,Math.max(Le.Log2(o)-_,0)),p.height=p.width,p.isCube=!0,p._cachedWrapU=0,p._cachedWrapV=0,this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,p,!0),p.samplingMode=2,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),Cs.UploadDDSLevels(this,p,i,t,!0,6,_)}else c.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);const m=new qi(t);m._isCube=!0,m._texture=p,p.isReady=!0,h.push(m)}r._lodTextureHigh=h[2],r._lodTextureMid=h[1],r._lodTextureLow=h[0],s&&s(r)}),r,a,o,l,i,n)};class xs{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}}B.ShadersStore.rgbdDecodePixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}";class Ms{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),n=i.getCaps(),s=t.isReady;let r=!1;n.textureHalfFloatRender&&n.textureHalfFloatLinearFiltering?(r=!0,t.type=2):n.textureFloatRender&&n.textureFloatLinearFiltering&&(r=!0,t.type=1),r&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const a=()=>{if(r){const n=new kn("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);n.externalTextureSamplerBinding=!0;const s=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});n.getEffect().executeWhenCompiled((()=>{n.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([n],s,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),n&&n.dispose(),s._swapAndDie(t),t.isReady=!0}))}};s?a():e.onLoadObservable.addOnce(a)}static EncodeTextureToRGBD(e,t,i=0){return function(e,t,i,n,s,r){const a=t.getEngine();return t.isReady=!1,s=null!=s?s:t.samplingMode,n=null!=n?n:t.type,r=null!=r?r:t.format,-1===n&&(n=0),new Promise((o=>{const l=new kn("postprocess",e,null,null,1,null,s,a,!1,void 0,n,void 0,null,!1,r);l.externalTextureSamplerBinding=!0;const h=a.createRenderTargetTexture({width:t.width,height:t.height},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:n,format:r});l.getEffect().executeWhenCompiled((()=>{l.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([l],h,!0),a.restoreDefaultFramebuffer(),a._releaseTexture(t),l&&l.dispose(),h._swapAndDie(t),t.type=n,t.format=5,t.isReady=!0,o(t)}))}))}("rgbdEncode",e,t,i,1,5)}}B.ShadersStore.rgbdEncodePixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}";function Is(e,t,i,n,s,r,a,o,l,h,c){return new Promise(((d,u)=>{if(i){const i=t.createTexture(null,!0,!0,null,1,null,(e=>{u(e)}),e);n.getEffect().executeWhenCompiled((()=>{n.externalTextureSamplerBinding=!0,n.onApply=n=>{n._bindTexture("textureSampler",i),n.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([n],h,!0,r,a),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(s),d())}))}else{if(t._uploadImageToTexture(c,e,r,a),o){const i=l[a];i&&t._uploadImageToTexture(i._texture,e,r,0)}d()}}))}function bs(e,t,i="image/png"){if(!Me.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");const n=Le.ILog2(e.width)+1,s=e.getEngine();let r=!1,a=!1,o=null,l=null,h=null;const c=s.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,e),c.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering?(r=!0,e.type=2):c.textureFloatRender&&c.textureFloatLinearFiltering&&(r=!0,e.type=1):r=!1:(r=!1,a=!0,h={}),r)o=new kn("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,l=s.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,a){const t=3,i=e._lodGenerationScale,r=e._lodGenerationOffset;for(let a=0;aIs(t,s,r,o,_,c,n,a,h,l,e)));else{const t=new Image;t.src=_,p=new Promise(((i,d)=>{t.onload=()=>{Is(t,s,r,o,_,c,n,a,h,l,e).then((()=>i())).catch((e=>{d(e)}))},t.onerror=e=>{d(e)}}))}d.push(p)}if(t.length{l&&(s._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))}))}class ys{constructor(e,t){if(this.data=e,this.isInvalid=!1,!ys.IsValid(e))return this.isInvalid=!0,void c.Error("texture missing KTX identifier");const i=Uint32Array.BYTES_PER_ELEMENT,n=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),s=67305985===n.getUint32(0,!0);return this.glType=n.getUint32(1*i,s),this.glTypeSize=n.getUint32(2*i,s),this.glFormat=n.getUint32(3*i,s),this.glInternalFormat=n.getUint32(4*i,s),this.glBaseInternalFormat=n.getUint32(5*i,s),this.pixelWidth=n.getUint32(6*i,s),this.pixelHeight=n.getUint32(7*i,s),this.pixelDepth=n.getUint32(8*i,s),this.numberOfArrayElements=n.getUint32(9*i,s),this.numberOfFaces=n.getUint32(10*i,s),this.numberOfMipmapLevels=n.getUint32(11*i,s),this.bytesOfKeyValueData=n.getUint32(12*i,s),0!==this.glType?(c.Error("only compressed formats currently supported"),void(this.isInvalid=!0)):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?(c.Error("only 2D textures currently supported"),void(this.isInvalid=!0)):0!==this.numberOfArrayElements?(c.Error("texture arrays not currently supported"),void(this.isInvalid=!0)):this.numberOfFaces!==t?(c.Error("number of faces expected"+t+", but found "+this.numberOfFaces),void(this.isInvalid=!0)):void(this.loadType=ys.COMPRESSED_2D))}uploadLevels(e,t){switch(this.loadType){case ys.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case ys.TEX_2D:case ys.COMPRESSED_3D:case ys.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=ys.HEADER_LEN+this.bytesOfKeyValueData,n=this.pixelWidth,s=this.pixelHeight;const r=t?this.numberOfMipmapLevels:1;for(let t=0;t=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}function Ps(e,t,i){try{const n=e.next();n.done?t(n):n.value?n.value.then((()=>{n.value=void 0,t(n)}),i):t(n)}catch(e){i(e)}}function Ds(e,t,i,n,s){const r=()=>{let a;const o=e=>{e.done?i(e.value):void 0===a?a=!0:r()};do{a=void 0,s&&s.aborted?n(new Error("Aborted")):t(e,o,n),void 0===a&&(a=!1)}while(a)};r()}function Os(e,t){let i;return Ds(e,Ps,(e=>i=e),(e=>{throw e}),t),i}function Ls(e,t,i){return new Promise(((n,s)=>{Ds(e,t,n,s,i)}))}ys.HEADER_LEN=64,ys.COMPRESSED_2D=0,ys.COMPRESSED_3D=1,ys.TEX_2D=2,ys.TEX_3D=3,s.prototype.notifyObserversWithPromise=async function(e,t=-1,i,n,s){let r=Promise.resolve(e);if(!this.observers.length)return r;const a=this._eventState;return a.mask=t,a.target=i,a.currentTarget=n,a.skipNextObservers=!1,a.userInfo=s,this.observers.forEach((i=>{a.skipNextObservers||i._willBeUnregistered||i.mask&t&&(r=i.scope?r.then((t=>(a.lastReturnValue=t,i.callback.apply(i.scope,[e,a])))):r.then((t=>(a.lastReturnValue=t,i.callback(e,a)))),i.unregisterOnNextCall&&this._deferUnregister(i))})),await r,e};class Ns{constructor(){var e;this._applyTo=(e=this._applyToCoroutine.bind(this),(...t)=>Os(e(...t),undefined))}set(e,t){switch(e.length||c.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case Lt.PositionKind:this.positions=e;break;case Lt.NormalKind:this.normals=e;break;case Lt.TangentKind:this.tangents=e;break;case Lt.UVKind:this.uvs=e;break;case Lt.UV2Kind:this.uvs2=e;break;case Lt.UV3Kind:this.uvs3=e;break;case Lt.UV4Kind:this.uvs4=e;break;case Lt.UV5Kind:this.uvs5=e;break;case Lt.UV6Kind:this.uvs6=e;break;case Lt.ColorKind:this.colors=e;break;case Lt.MatricesIndicesKind:this.matricesIndices=e;break;case Lt.MatricesWeightsKind:this.matricesWeights=e;break;case Lt.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case Lt.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){return this.positions&&(e.setVerticesData(Lt.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(Lt.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(Lt.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(Lt.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(Lt.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(Lt.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(Lt.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(Lt.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(Lt.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(Lt.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(Lt.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(Lt.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(Lt.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(Lt.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),this}_update(e,t,i){return this.positions&&e.updateVerticesData(Lt.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(Lt.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(Lt.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(Lt.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(Lt.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(Lt.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(Lt.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(Lt.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(Lt.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(Lt.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(Lt.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(Lt.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(Lt.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(Lt.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,n=e.length){const s=Ke.Vector3[0],r=Ke.Vector3[1];for(let a=i;a({vertexData:e}))):[{vertexData:e}];return Os(this._mergeCoroutine(void 0,n,t,!1,i))}*_mergeCoroutine(e,t,i=!1,n,s){var r,a,o,l;this._validate();const h=t.map((e=>e.vertexData));for(const e of h)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");const c=h.reduce(((e,t)=>{var i,n;return e+(null!==(n=null===(i=t.indices)||void 0===i?void 0:i.length)&&void 0!==n?n:0)}),null!==(a=null===(r=this.indices)||void 0===r?void 0:r.length)&&void 0!==a?a:0);let d=s||h.some((e=>e.indices===this.indices))?null===(o=this.indices)||void 0===o?void 0:o.slice():this.indices;if(c>0){let s=null!==(l=null==d?void 0:d.length)&&void 0!==l?l:0;if(d||(d=new Array(c)),d.length!==c){if(Array.isArray(d))d.length=c;else{const e=i||d instanceof Uint32Array?new Uint32Array(c):new Uint16Array(c);e.set(d),d=e}e&&e.determinant()<0&&Ns._FlipFaces(d,0,s)}let r=this.positions?this.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t[e.vertexData.positions,e.transform]))),n&&(yield),this.normals=Ns._MergeElement(Lt.NormalKind,this.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),n&&(yield),this.tangents=Ns._MergeElement(Lt.TangentKind,this.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),n&&(yield),this.uvs=Ns._MergeElement(Lt.UVKind,this.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),n&&(yield),this.uvs2=Ns._MergeElement(Lt.UV2Kind,this.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),n&&(yield),this.uvs3=Ns._MergeElement(Lt.UV3Kind,this.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),n&&(yield),this.uvs4=Ns._MergeElement(Lt.UV4Kind,this.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),n&&(yield),this.uvs5=Ns._MergeElement(Lt.UV5Kind,this.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),n&&(yield),this.uvs6=Ns._MergeElement(Lt.UV6Kind,this.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),n&&(yield),this.colors=Ns._MergeElement(Lt.ColorKind,this.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),n&&(yield),this.matricesIndices=Ns._MergeElement(Lt.MatricesIndicesKind,this.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),n&&(yield),this.matricesWeights=Ns._MergeElement(Lt.MatricesWeightsKind,this.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),n&&(yield),this.matricesIndicesExtra=Ns._MergeElement(Lt.MatricesIndicesExtraKind,this.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),n&&(yield),this.matricesWeightsExtra=Ns._MergeElement(Lt.MatricesWeightsExtraKind,this.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform]))),this}static _MergeElement(e,t,i,n){const s=n.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==s.length)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));const r=s.reduce(((e,t)=>e+t[0].length),t.length),a=e===Lt.PositionKind?Ns._TransformVector3Coordinates:e===Lt.NormalKind?Ns._TransformVector3Normals:e===Lt.TangentKind?Ns._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(r);e.set(t),i&&a(e,i,0,t.length);let n=t.length;for(const[t,i]of s)e.set(t,n),i&&a(e,i,n,t.length),n+=t.length;return e}{const e=new Array(r);for(let i=0;i{const i=Lt.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(Lt.PositionKind,this.positions),i=(i,n)=>{const s=e(i,n);if(s!==t)throw new Error("The "+i+"s element count ("+s+") does not match the positions count ("+t+")")};this.normals&&i(Lt.NormalKind,this.normals),this.tangents&&i(Lt.TangentKind,this.tangents),this.uvs&&i(Lt.UVKind,this.uvs),this.uvs2&&i(Lt.UV2Kind,this.uvs2),this.uvs3&&i(Lt.UV3Kind,this.uvs3),this.uvs4&&i(Lt.UV4Kind,this.uvs4),this.uvs5&&i(Lt.UV5Kind,this.uvs5),this.uvs6&&i(Lt.UV6Kind,this.uvs6),this.colors&&i(Lt.ColorKind,this.colors),this.matricesIndices&&i(Lt.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(Lt.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(Lt.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(Lt.MatricesWeightsExtraKind,this.matricesWeightsExtra)}serialize(){const e={};return this.positions&&(e.positions=this.positions),this.normals&&(e.normals=this.normals),this.tangents&&(e.tangents=this.tangents),this.uvs&&(e.uvs=this.uvs),this.uvs2&&(e.uvs2=this.uvs2),this.uvs3&&(e.uvs3=this.uvs3),this.uvs4&&(e.uvs4=this.uvs4),this.uvs5&&(e.uvs5=this.uvs5),this.uvs6&&(e.uvs6=this.uvs6),this.colors&&(e.colors=this.colors),this.matricesIndices&&(e.matricesIndices=this.matricesIndices,e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=this.matricesWeights),this.matricesIndicesExtra&&(e.matricesIndicesExtra=this.matricesIndicesExtra,e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=this.matricesWeightsExtra),e.indices=this.indices,e}static ExtractFromMesh(e,t,i){return Ns._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return Ns._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const n=new Ns;return e.isVerticesDataPresent(Lt.PositionKind)&&(n.positions=e.getVerticesData(Lt.PositionKind,t,i)),e.isVerticesDataPresent(Lt.NormalKind)&&(n.normals=e.getVerticesData(Lt.NormalKind,t,i)),e.isVerticesDataPresent(Lt.TangentKind)&&(n.tangents=e.getVerticesData(Lt.TangentKind,t,i)),e.isVerticesDataPresent(Lt.UVKind)&&(n.uvs=e.getVerticesData(Lt.UVKind,t,i)),e.isVerticesDataPresent(Lt.UV2Kind)&&(n.uvs2=e.getVerticesData(Lt.UV2Kind,t,i)),e.isVerticesDataPresent(Lt.UV3Kind)&&(n.uvs3=e.getVerticesData(Lt.UV3Kind,t,i)),e.isVerticesDataPresent(Lt.UV4Kind)&&(n.uvs4=e.getVerticesData(Lt.UV4Kind,t,i)),e.isVerticesDataPresent(Lt.UV5Kind)&&(n.uvs5=e.getVerticesData(Lt.UV5Kind,t,i)),e.isVerticesDataPresent(Lt.UV6Kind)&&(n.uvs6=e.getVerticesData(Lt.UV6Kind,t,i)),e.isVerticesDataPresent(Lt.ColorKind)&&(n.colors=e.getVerticesData(Lt.ColorKind,t,i)),e.isVerticesDataPresent(Lt.MatricesIndicesKind)&&(n.matricesIndices=e.getVerticesData(Lt.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(Lt.MatricesWeightsKind)&&(n.matricesWeights=e.getVerticesData(Lt.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(Lt.MatricesIndicesExtraKind)&&(n.matricesIndicesExtra=e.getVerticesData(Lt.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(Lt.MatricesWeightsExtraKind)&&(n.matricesWeightsExtra=e.getVerticesData(Lt.MatricesWeightsExtraKind,t,i)),n.indices=e.getIndices(t,i),n}static CreateRibbon(e){throw _("ribbonBuilder")}static CreateBox(e){throw _("boxBuilder")}static CreateTiledBox(e){throw _("tiledBoxBuilder")}static CreateTiledPlane(e){throw _("tiledPlaneBuilder")}static CreateSphere(e){throw _("sphereBuilder")}static CreateCylinder(e){throw _("cylinderBuilder")}static CreateTorus(e){throw _("torusBuilder")}static CreateLineSystem(e){throw _("linesBuilder")}static CreateDashedLines(e){throw _("linesBuilder")}static CreateGround(e){throw _("groundBuilder")}static CreateTiledGround(e){throw _("groundBuilder")}static CreateGroundFromHeightMap(e){throw _("groundBuilder")}static CreatePlane(e){throw _("planeBuilder")}static CreateDisc(e){throw _("discBuilder")}static CreatePolygon(e,t,i,n,s,r,a){throw _("polygonBuilder")}static CreateIcoSphere(e){throw _("icoSphereBuilder")}static CreatePolyhedron(e){throw _("polyhedronBuilder")}static CreateCapsule(e={orientation:ze.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw _("capsuleBuilder")}static CreateTorusKnot(e){throw _("torusKnotBuilder")}static ComputeNormals(e,t,i,n){let s=0,r=0,a=0,o=0,l=0,h=0,c=0,d=0,u=0,f=0,_=0,p=0,m=0,g=0,E=0,T=0,A=0,v=0,S=0,R=0,C=!1,x=!1,M=!1,I=!1,b=1,y=0,P=null;n&&(C=!!n.facetNormals,x=!!n.facetPositions,M=!!n.facetPartitioning,b=!0===n.useRightHandedSystem?-1:1,y=n.ratio||0,I=!!n.depthSort,P=n.distanceTo,I&&void 0===P&&(P=ze.Zero()));let D=0,O=0,L=0,N=0;for(M&&n&&n.bbSize&&(D=n.subDiv.X*y/n.bbSize.x,O=n.subDiv.Y*y/n.bbSize.y,L=n.subDiv.Z*y/n.bbSize.z,N=n.subDiv.max*n.subDiv.max,n.facetPartitioning.length=0),s=0;s!Array.isArray(e)))],Ns,"_TransformVector3Coordinates",null),Qe([Et.filter(((...[e])=>!Array.isArray(e)))],Ns,"_TransformVector3Normals",null),Qe([Et.filter(((...[e])=>!Array.isArray(e)))],Ns,"_TransformVector4Normals",null),Qe([Et.filter(((...[e])=>!Array.isArray(e)))],Ns,"_FlipFaces",null);class Fs{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 Fs(Fs.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,n=!1,s=null){this.delayLoadState=0,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=n,i?this.setAllVerticesData(i,n):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),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){2!==this.delayLoadState&&(this.isReady()?t&&t():(this.delayLoadState=2,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=1,this._delayInfo=[],e.removePendingData(this);const n=this._meshes,s=n.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new Ns;t.indices=[];const i=this.getIndices();if(i)for(let e=0;e0){const n=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(Lt.PositionKind,n,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const n=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(Lt.NormalKind,n,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const n=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(Lt.TangentKind,n,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const n=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(Zi.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(Zi.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(Zi.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(Zi.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(Zi.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(Zi.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(Lt.ColorKind,n,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const n=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(Lt.MatricesIndicesKind,s,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const n=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(Lt.MatricesIndicesExtraKind,s,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const n=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(Lt.MatricesWeightsKind,n,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){const n=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(n,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){const n=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&n)>>16),i.push(n>>24&255)}t.setVerticesData(Lt.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(Lt.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t>8),i.push((16711680&n)>>16),i.push(n>>24&255)}t.setVerticesData(Lt.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(Fs._CleanMatricesWeights(e,t),t.setVerticesData(Lt.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(Lt.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;n=i.bones.length}const s=t.getVerticesData(Lt.MatricesIndicesKind),r=t.getVerticesData(Lt.MatricesIndicesExtraKind),a=e.matricesWeights,o=e.matricesWeightsExtra,l=e.numBoneInfluencer,h=a.length;for(let e=0;el-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]=n):(a[e+h]=1-t,s[e+h]=n)}t.setVerticesData(Lt.MatricesIndicesKind,s),e.matricesWeightsExtra&&t.setVerticesData(Lt.MatricesIndicesExtraKind,r)}static Parse(e,t,i){const n=new Fs(e.id,t,void 0,e.updatable);return n._loadedUniqueId=e.uniqueId,Oe&&Oe.AddTagsTo(n,e.tags),e.delayLoadingFile?(n.delayLoadState=4,n.delayLoadingFile=i+e.delayLoadingFile,n._boundingInfo=new Oi(ze.FromArray(e.boundingBoxMinimum),ze.FromArray(e.boundingBoxMaximum)),n._delayInfo=[],e.hasUVs&&n._delayInfo.push(Lt.UVKind),e.hasUVs2&&n._delayInfo.push(Lt.UV2Kind),e.hasUVs3&&n._delayInfo.push(Lt.UV3Kind),e.hasUVs4&&n._delayInfo.push(Lt.UV4Kind),e.hasUVs5&&n._delayInfo.push(Lt.UV5Kind),e.hasUVs6&&n._delayInfo.push(Lt.UV6Kind),e.hasColors&&n._delayInfo.push(Lt.ColorKind),e.hasMatricesIndices&&n._delayInfo.push(Lt.MatricesIndicesKind),e.hasMatricesWeights&&n._delayInfo.push(Lt.MatricesWeightsKind),n._delayLoadingFunction=Ns.ImportVertexData):Ns.ImportVertexData(e,n),t.pushGeometry(n,!0),n}}class ws extends Ei{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=0!=(this._billboardMode&ws.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!==ws.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),this._forward=new ze(0,0,1),this._up=new ze(0,1,0),this._right=new ze(1,0,0),this._position=ze.Zero(),this._rotation=ze.Zero(),this._rotationQuaternion=null,this._scaling=ze.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=ws.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=Xe.Zero(),this._usePivotMatrix=!1,this._absolutePosition=ze.Zero(),this._absoluteScaling=ze.Zero(),this._absoluteRotationQuaternion=We.Identity(),this._pivotMatrix=Xe.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new s,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}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 ze.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return ze.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return ze.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=Xe.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==ws.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=Xe.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const n=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);n&&i&&i(this,n);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(n,t,i);return n}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||We.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,n;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],n=arguments[2]}else t=e.x,i=e.y,n=e.z;if(this.parent){const e=Ke.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),ze.TransformCoordinatesFromFloatsToRef(t,i,n,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=n;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=ze.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=Ke.Matrix[0];return this._localMatrix.invertToRef(e),ze.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=ze.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,n=0,s=ui.LOCAL){const r=ws._LookAtVectorCache,a=s===ui.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,r),this.setDirection(r,t,i,n),s===ui.WORLD&&this.parent)if(this.rotationQuaternion){const e=Ke.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=Ke.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=Ke.Quaternion[0];We.FromEulerVectorToRef(this.rotation,e);const t=Ke.Matrix[0];e.toRotationMatrix(t);const i=Ke.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=ze.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return ze.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,n=0){const s=-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?We.RotationYawPitchRollToRef(s+t,a+i,n,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=s+t,this.rotation.z=n),this}setPivotPoint(e,t=ui.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==ui.WORLD){const t=Ke.Matrix[0];i.invertToRef(t),e=ze.TransformCoordinates(e,t)}return this.setPivotMatrix(Xe.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=ze.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=ze.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),ze.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 n=Ke.Quaternion[0],s=Ke.Vector3[0],r=Ke.Vector3[1],a=Ke.Matrix[1];Xe.IdentityToRef(a);const o=Ke.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=ws._TmpRotation,We.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),Xe.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,n,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(n):n.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(r),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(Xe.Identity()),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(),e.getWorldMatrix().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 n;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==ui.LOCAL){if(this.parent){const t=Ke.Matrix[0];this.parent.getWorldMatrix().invertToRef(t),e=ze.TransformNormal(e,t)}n=We.RotationAxisToRef(e,t,ws._RotationAxisCache),n.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else n=We.RotationAxisToRef(e,t,ws._RotationAxisCache),this.rotationQuaternion.multiplyToRef(n,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=We.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const n=Ke.Vector3[0],s=Ke.Vector3[1],r=Ke.Vector3[2],a=Ke.Quaternion[0],o=Ke.Matrix[0],l=Ke.Matrix[1],h=Ke.Matrix[2],c=Ke.Matrix[3];return e.subtractToRef(this.position,n),Xe.TranslationToRef(n.x,n.y,n.z,o),Xe.TranslationToRef(-n.x,-n.y,-n.z,l),Xe.RotationAxisToRef(t,i,h),l.multiplyToRef(h,c),c.multiplyToRef(o,c),c.decompose(s,a,r),this.position.addInPlace(r),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const n=e.scale(t);if(i&&i!==ui.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(n));else{const e=this.getPositionExpressedInLocalSpace().add(n);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let n;this.rotationQuaternion?n=this.rotationQuaternion:(n=Ke.Quaternion[1],We.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,n));const s=Ke.Quaternion[0];return We.RotationYawPitchRollToRef(t,e,i,s),n.multiplyInPlace(s),this.rotationQuaternion||n.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==ws.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 n=this._cache;n.pivotMatrixUpdated=!1,n.billboardMode=this.billboardMode,n.infiniteDistance=this.infiniteDistance,n.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 s=this._getEffectiveParent(),r=ws._TmpScaling;let a,o=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new ze(e.m[12],e.m[13],e.m[14]);o=ws._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?(this._rotationQuaternion._isDirty=!1,a=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(We.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(a=ws._TmpRotation,We.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,a)),this._usePivotMatrix){const e=Ke.Matrix[1];Xe.ScalingToRef(r.x,r.y,r.z,e);const t=Ke.Matrix[0];a.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,Ke.Matrix[4]),Ke.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 Xe.ComposeToRef(r,a,o,this._localMatrix);if(s&&s.getWorldMatrix){if(e&&s.computeWorldMatrix(e),n.useBillboardPath){this._transformToBoneReferal?s.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),Ke.Matrix[7]):Ke.Matrix[7].copyFrom(s.getWorldMatrix());const e=Ke.Vector3[5],t=Ke.Vector3[6],i=Ke.Quaternion[0];Ke.Matrix[7].decompose(t,i,e),Xe.ScalingToRef(t.x,t.y,t.z,Ke.Matrix[7]),Ke.Matrix[7].setTranslation(e),ws.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(Ke.Matrix[7],this._worldMatrix)}else this._transformToBoneReferal?(this._localMatrix.multiplyToRef(s.getWorldMatrix(),Ke.Matrix[6]),Ke.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localMatrix.multiplyToRef(s.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(n.useBillboardPath&&t&&this.billboardMode&&!n.useBillboardPosition){const e=Ke.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),Ke.Matrix[1].copyFrom(t.getViewMatrix()),Ke.Matrix[1].setTranslationFromFloats(0,0,0),Ke.Matrix[1].invertToRef(Ke.Matrix[0]),(this.billboardMode&ws.BILLBOARDMODE_ALL)!==ws.BILLBOARDMODE_ALL){Ke.Matrix[0].decompose(void 0,Ke.Quaternion[0],void 0);const e=Ke.Vector3[1];Ke.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&ws.BILLBOARDMODE_X)!==ws.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&ws.BILLBOARDMODE_Y)!==ws.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&ws.BILLBOARDMODE_Z)!==ws.BILLBOARDMODE_Z&&(e.z=0),Xe.RotationYawPitchRollToRef(e.y,e.x,e.z,Ke.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(Ke.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(Ke.Vector3[0])}else if(n.useBillboardPath&&t&&n.useBillboardPosition){const e=Ke.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(Ke.Matrix[1]);const n=Ke.Vector3[1];ze.TransformCoordinatesToRef(i,Ke.Matrix[1],n),n.normalize();const s=-Math.atan2(n.z,n.x)+Math.PI/2,r=Math.sqrt(n.x*n.x+n.z*n.z),a=-Math.atan2(n.y,r);if(We.RotationYawPitchRollToRef(s,a,0,Ke.Quaternion[0]),(this.billboardMode&ws.BILLBOARDMODE_ALL)!==ws.BILLBOARDMODE_ALL){const e=Ke.Vector3[1];Ke.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&ws.BILLBOARDMODE_X)!==ws.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&ws.BILLBOARDMODE_Y)!==ws.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&ws.BILLBOARDMODE_Z)!==ws.BILLBOARDMODE_Z&&(e.z=0),Xe.RotationYawPitchRollToRef(e.y,e.x,e.z,Ke.Matrix[0])}else Xe.FromQuaternionToRef(Ke.Quaternion[0],Ke.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(Ke.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(Ke.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):s&&s._nonUniformScaling?this._updateNonUniformScalingState(s._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=Xe.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;tnew ws(e,this.getScene())),this);if(n.name=e,n.id=e,t&&(n.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;inew ws(e.name,t)),e,t,i);return e.localMatrix?n.setPreTransformMatrix(Xe.FromArray(e.localMatrix)):e.pivotMatrix&&n.setPivotMatrix(Xe.FromArray(e.pivotMatrix)),n.setEnabled(e.isEnabled),n._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),n}getChildTransformNodes(e,t){const i=[];return this._getDescendants(i,e,(e=>(!t||t(e))&&e instanceof ws)),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 n=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(n=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&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&n&&this.rotation.copyFrom(n)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}ws.BILLBOARDMODE_NONE=0,ws.BILLBOARDMODE_X=1,ws.BILLBOARDMODE_Y=2,ws.BILLBOARDMODE_Z=4,ws.BILLBOARDMODE_ALL=7,ws.BILLBOARDMODE_USE_POSITION=128,ws.BillboardUseParentOrientation=!1,ws._TmpRotation=We.Zero(),ws._TmpScaling=ze.Zero(),ws._TmpTranslation=ze.Zero(),ws._LookAtVectorCache=new ze(0,0,0),ws._RotationAxisCache=new We,Qe([pt("position")],ws.prototype,"_position",void 0),Qe([pt("rotation")],ws.prototype,"_rotation",void 0),Qe([lt(10,"rotationQuaternion")],ws.prototype,"_rotationQuaternion",void 0),Qe([pt("scaling")],ws.prototype,"_scaling",void 0),Qe([ct("billboardMode")],ws.prototype,"_billboardMode",void 0),Qe([ct()],ws.prototype,"scalingDeterminant",void 0),Qe([ct("infiniteDistance")],ws.prototype,"_infiniteDistance",void 0),Qe([ct()],ws.prototype,"ignoreNonUniformScaling",void 0),Qe([ct()],ws.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class Bs{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new ze(0,0,0),this._diffPositionForCollisions=new ze(0,0,0),this._collisionResponse=!0}}class Us{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=ze.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class ks{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Us,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 Bs,this._enableDistantPicking=!1}}class Gs extends ws{static get BILLBOARDMODE_NONE(){return ws.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return ws.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return ws.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return ws.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return ws.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return ws.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)}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._markSubMeshesAsMiscDirty()}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._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){var t;return null===(t=this._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[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}get _positions(){return null}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 ks,this._waitingMaterialId=null,this.cullingStrategy=Gs.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new s,this.onCollisionPositionChangeObservable=new s,this.onMaterialChangedObservable=new s,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=tt.Red(),this.outlineWidth=.02,this.overlayColor=tt.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 ze(.5,1,.5),this.ellipsoidOffset=new ze(0,0,0),this.edgesWidth=1,this.edgesColor=new it(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 s,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>tn.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 Dt(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case di.Aggressive:this.doNotSyncBoundingInfo=!0;case di.Intermediate: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!==ws.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()}_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 n=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;n=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(n)}_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;it.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,n){return this}updateVerticesData(e,t,i,n){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)}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new Oi(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(Lt.MatricesIndicesKind)&&this.isVerticesDataPresent(Lt.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===ws.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 n=new Xe;(this.rotationQuaternion?this.rotationQuaternion:We.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(n);const s=ze.Zero(),r=this.definedFacingForward?-1:1;return ze.TransformCoordinatesFromFloatsToRef(e*r,t,i*r,n,s),s}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const n=this.definedFacingForward?1:-1;return new ze(e*n,t,i*n)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){const i=Ni(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new Oi(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t0){const e=t.getPositions();e&&(i[s]+=(e[s]-i[s])*n)}}if(e++,n===Lt.PositionKind&&this._positions&&3===e){e=0;const n=3*t;this._positions[t++].copyFromFloats(i[n],i[n+1],i[n+2])}}}if(i&&e&&this.skeleton){const e=this.getVerticesData(Lt.MatricesIndicesKind),t=this.getVerticesData(Lt.MatricesWeightsKind);if(t&&e){const s=this.numBoneInfluencers>4,r=s?this.getVerticesData(Lt.MatricesIndicesExtraKind):null,a=s?this.getVerticesData(Lt.MatricesWeightsExtraKind):null,o=this.skeleton.getTransformMatrices(this),l=Ke.Vector3[0],h=Ke.Matrix[0],c=Ke.Matrix[1];let d=0;for(let u=0;u0&&(Xe.FromFloat32ArrayToRefScaled(o,Math.floor(16*e[d+f]),_,c),h.addToSelf(c));if(s)for(f=0;f<4;f++)_=a[d+f],_>0&&(Xe.FromFloat32ArrayToRefScaled(o,Math.floor(16*r[d+f]),_,c),h.addToSelf(c));n===Lt.NormalKind?ze.TransformNormalFromFloatsToRef(i[u],i[u+1],i[u+2],h,l):ze.TransformCoordinatesFromFloatsToRef(i[u],i[u+1],i[u+2],h,l),l.toArray(i,u),n===Lt.PositionKind&&this._positions&&this._positions[u/3].copyFrom(l)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,Lt.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,Lt.PositionKind)}_getPositionData(e,t){var i;let n=this.getVerticesData(Lt.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),n&&(e&&this.skeleton||t&&this.morphTargetManager)){if(n=n.slice(),this._generatePointsArray(),this._positions){const e=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(e.length);for(let t=0;t1||!n.IsGlobal)&&n.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 n=this.getBoundingInfo(),s=e.getBoundingInfo();if(n.intersects(s,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){var n;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,n=e.verticesStart+e.verticesCount;for(let s=i;s1&&!r._checkCollision(e)||this._collideForSubMesh(r,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=Ke.Matrix[0],i=Ke.Matrix[1];return Xe.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,n=!1,s,r=!1){const a=new Nt,o="InstancedLinesMesh"===this.getClassName()||"LinesMesh"===this.getClassName()?this.intersectionThreshold:0,l=this.getBoundingInfo();if(!this.subMeshes)return a;if(!(r||e.intersectsSphere(l.boundingSphere,o)&&e.intersectsBox(l.boundingBox,o)))return a;if(n)return a.hit=!r,a.pickedMesh=r?null:this,a.distance=r?0:ze.Distance(e.origin,l.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;let h=null;const c=this._scene.getIntersectingSubMeshCandidates(this,e),d=c.length;let u=!1;for(let e=0;e1&&!s.canIntersects(e))continue;const r=s.intersects(e,this._positions,this.getIndices(),t,i);if(r&&(t||!h||r.distance{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=this.getScene().getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,n.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),n.wipeCaches(),this.getScene().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;i65535){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:ze.Zero()}e.depthSortedFacets=[];for(let t=0;twe?s.maximum.x-s.minimum.x:we,e.bbSize.y=s.maximum.y-s.minimum.y>we?s.maximum.y-s.minimum.y:we,e.bbSize.z=s.maximum.z-s.minimum.z>we?s.maximum.z-s.minimum.z:we;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=s,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),ze.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,n&&Ns.ComputeNormals(t,i,n,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let n=0;ns.subDiv.max||a<0||a>s.subDiv.max||o<0||o>s.subDiv.max?null:s.facetPartitioning[r+s.subDiv.max*a+s.subDiv.max*s.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,i,n,s=!1,r=!0){const a=this.getWorldMatrix(),o=Ke.Matrix[5];a.invertToRef(o);const l=Ke.Vector3[8];ze.TransformCoordinatesFromFloatsToRef(e,t,i,o,l);const h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,n,s,r);return n&&ze.TransformCoordinatesFromFloatsToRef(n.x,n.y,n.z,a,n),h}getClosestFacetAtLocalCoordinates(e,t,i,n,s=!1,r=!0){let a=null,o=0,l=0,h=0,c=0,d=0,u=0,f=0,_=0;const p=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let E,T,A,v=Number.MAX_VALUE,S=v;for(let R=0;R=0||s&&!r&&c<=0)&&(c=T.x*A.x+T.y*A.y+T.z*A.z,d=-(T.x*e+T.y*t+T.z*i-c)/(T.x*T.x+T.y*T.y+T.z*T.z),u=e+T.x*d,f=t+T.y*d,_=i+T.z*d,o=u-e,l=f-t,h=_-i,S=o*o+l*l+h*h,Se.emitter===this))}}Gs.OCCLUSION_TYPE_NONE=0,Gs.OCCLUSION_TYPE_OPTIMISTIC=1,Gs.OCCLUSION_TYPE_STRICT=2,Gs.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,Gs.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,Gs.CULLINGSTRATEGY_STANDARD=0,Gs.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Gs.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Gs.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,Se("BABYLON.AbstractMesh",Gs);class Vs extends Yi{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().multiMaterials.push(this),this.subMaterials=new Array,this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...i)=>{const n=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),n};const i=e.splice;e.splice=(t,n)=>{const s=i.apply(e,[t,n]);return this._markAllSubMeshesAsTexturesDirty(),s}}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){var t;if(super.hasTexture(e))return!0;for(let i=0;i=0&&n.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new Vs(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,Oe&&Oe.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}Se("BABYLON.MultiMaterial",Vs);class zs{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class Hs{constructor(){this.visibleInstances={},this.batchCache=new Ws,this.batchCacheReplacementModeInFrozenMode=new Ws,this.instancesBufferSize=2048}}class Ws{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=new Array,this.hardwareInstancedRendering=new Array}}class Xs{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class Ys{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}}class Ks extends Gs{static _GetDefaultSideOrientation(e){return e||Ks.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(Lt.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(Lt.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 s),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new s),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new s),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new s),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new s),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(){var e;return(null!==(e=this._thinInstanceDataStorage.instancesCount)&&void 0!==e?e:0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=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}constructor(e,t=null,i=null,n=null,r,a=!0){if(super(e,t),this._internalMeshDataInfo=new Ys,this.delayLoadState=0,this.instances=new Array,this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new Hs,this._thinInstanceDataStorage=new Xs,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=Ks.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},n){if(n._geometry&&n._geometry.applyToMesh(this),u.DeepCopy(n,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"],["_poseMatrix"]),this._internalMeshDataInfo._source=n,t.useClonedMeshMap&&(n._internalMeshDataInfo.meshMap||(n._internalMeshDataInfo.meshMap={}),n._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=n._originalBuilderSideOrientation,this._creationDataStorage=n._creationDataStorage,n._ranges){const e=n._ranges;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(n.metadata&&n.metadata.clone?this.metadata=n.metadata.clone():this.metadata=n.metadata,this._internalMetadata=n._internalMetadata,Oe&&Oe.HasTags(n)&&Oe.AddTagsTo(this,Oe.GetTags(n,!0)),this.setEnabled(n.isEnabled(!1)),this.parent=n.parent,this.setPivotMatrix(n.getPivotMatrix()),this.id=e+"."+n.id,this.material=n.material,!r){const t=n.getDescendants(!0);for(let i=0;i{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 s(this._internalMeshDataInfo._onMeshReadyObserverAdded),n&&n.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const n=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));n.parent=e||this.parent,n.position=this.position.clone(),n.scaling=this.scaling.clone(),this.rotationQuaternion?n.rotationQuaternion=this.rotationQuaternion.clone():n.rotation=this.rotation.clone(),i&&i(this,n);for(const e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===n.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(n,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:n},i):e.instantiateHierarchy(n,t,i);return n}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;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort(((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0))}addLODLevel(e,t){if(t&&t._masterMesh)return c.Warn("You cannot use a mesh as LOD level twice"),this;const i=new zs(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;ia*r)return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,this),this;for(let e=0;e0||this.hasThinInstances);this.computeWorldMatrix();const d=this.material||h.defaultMaterial;if(d)if(d._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,c))return!1}else if(!t.isReady(this,c))return!1}else if(!d.isReady(this,c))return!1;const u=l.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const h=t.values();for(let e=h.next();!0!==e.done;e=h.next()){const t=e.value;if(t&&(!(null===(i=t.getShadowMap())||void 0===i?void 0:i.renderList)||(null===(n=t.getShadowMap())||void 0===n?void 0:n.renderList)&&-1!==(null===(r=null===(s=t.getShadowMap())||void 0===s?void 0:s.renderList)||void 0===r?void 0:r.indexOf(this)))){t.getShadowMap()&&(l.currentRenderPassId=t.getShadowMap().renderPassId);for(const e of this.subMeshes)if(!t.isReady(e,c,null!==(o=null===(a=e.getMaterial())||void 0===a?void 0:a.needAlphaBlendingForMesh(this))&&void 0!==o&&o))return l.currentRenderPassId=u,!1;l.currentRenderPassId=u}}}for(const e of this._internalMeshDataInfo._LODLevels)if(e.mesh&&!e.mesh.isReady(c))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;const i=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getPositionData(e,t),i),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 n=i.length;let s=!1;if(e)s=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>n){s=!0;break}if(e.verticesStart+e.verticesCount>t){s=!0;break}}if(!s)return this.subMeshes[0]}return this.releaseSubMeshes(),new Fi(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,n=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let s=0;s=t);s++)Fi.CreateFromIndices(0,n,s===e-1?t-n:i,this),n+=i;this.synchronizeInstances()}setVerticesData(e,t,i=!1,n){if(this._geometry)this._geometry.setVerticesData(e,t,i,n);else{const n=new Ns;n.set(t,e);const s=this.getScene();new Fs(Fs.RandomId(),s,n,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=Fs.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,n){return this._geometry?(n?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(Lt.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(Lt.PositionKind,i,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(Lt.NormalKind);if(!t)return this;Ns.ComputeNormals(i,e,t),this.updateVerticesData(Lt.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(Fs.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const t=new Ns;t.indices=e;const n=this.getScene();new Fs(Fs.RandomId(),n,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,n=!0){if(!this._geometry)return this;const s=this.getScene().getEngine();let r;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)r=null;else switch(i){case Yi.PointFillMode:r=null;break;case Yi.WireFrameFillMode:r=e._getLinesIndexBuffer(this.getIndices(),s);break;default:case Yi.TriangleFillMode:r=this._geometry.getIndexBuffer()}return n&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,r,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,r),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 n=this.getScene().getEngine();return this._unIndexed||t==Yi.PointFillMode?n.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Yi.WireFrameFillMode?n.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):n.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(),n=i._isInIntermediateRendering(),s=n?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,r=this._instanceDataStorage.batchCache;if(r.mustReturn=!1,r.renderSelf[e]=t||!s&&this.isEnabled()&&this.isVisible,r.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,s=i.getRenderId(),a=n?t.intermediateDefaultRenderId:t.defaultRenderId;r.visibleInstances[e]=t[s],!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,n,s){var r;const a=i.visibleInstances[e._id],o=a?a.length:0,l=this._instanceDataStorage,h=l.instancesBufferSize;let c=l.instancesBuffer,d=l.instancesPreviousBuffer;const u=16*(o+1)*4;for(;l.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamerai&&n++,0!==r&&d++,c+=r,i=r}if(l[d]++,d>r&&(r=d),0===c)s++;else{const i=1/c;let n=0;for(let s=0;s.001&&a++}}const h=this.skeleton.bones.length,c=this.getVerticesData(Lt.MatricesIndicesKind),d=this.getVerticesData(Lt.MatricesIndicesExtraKind);let u=0;for(let e=0;e=h||i<0)&&u++}return{skinned:!0,valid:0===s&&0===a&&0===u,report:"Number of Weights = "+i/4+"\nMaximum influences = "+r+"\nMissing Weights = "+s+"\nNot Sorted = "+n+"\nNot Normalized = "+a+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+u}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return Me.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=1,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return 2!==this.delayLoadState&&!!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 n=this.getScene().multiMaterials;for(i=n.length-1;i>-1;i--)if(n[i].id===e)return this.material=n[i],this;return this}getAnimatables(){const e=new Array;return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(Lt.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(Lt.PositionKind);const n=ze.Zero();let s;for(s=0;s{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,s,r,a),n&&n(this)}),(()=>{}),o.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,n,s,r,a,o=!1){if(!this.isVerticesDataPresent(Lt.PositionKind)||!this.isVerticesDataPresent(Lt.NormalKind)||!this.isVerticesDataPresent(Lt.UVKind))return c.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(Lt.PositionKind,!0,!0),h=this.getVerticesData(Lt.NormalKind),d=this.getVerticesData(Lt.UVKind);let u=ze.Zero();const f=ze.Zero(),_=Ve.Zero();r=r||Ve.Zero(),a=a||new Ve(1,1);for(let o=0;o{const t=n.length-1-e,i=n[t];for(let e=0;e{for(let e=0;e-1&&(n.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(n.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(n.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t4,l=o?this.getVerticesData(Lt.MatricesIndicesExtraKind):null,h=o?this.getVerticesData(Lt.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),d=ze.Zero(),u=new Xe,f=new Xe;let _,p=0;for(let e=0;e0&&(Xe.FromFloat32ArrayToRefScaled(c,Math.floor(16*r[p+_]),m,f),u.addToSelf(f));if(o)for(_=0;_<4;_++)m=h[p+_],m>0&&(Xe.FromFloat32ArrayToRefScaled(c,Math.floor(16*l[p+_]),m,f),u.addToSelf(f));ze.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],u,d),d.toArray(n,e),t&&(ze.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],u,d),d.toArray(s,e)),u.reset()}return this.updateVerticesData(Lt.PositionKind,n),t&&this.updateVerticesData(Lt.NormalKind,s),this}static MinMax(e){let t=null,i=null;return e.forEach((function(e){const n=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(n.minimumWorld),i.maximizeInPlace(n.maximumWorld)):(t=n.minimumWorld,i=n.maximumWorld)})),t&&i?{min:t,max:i}:{min:ze.Zero(),max:ze.Zero()}}static Center(e){const t=e instanceof Array?Ks.MinMax(e):e;return ze.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,n,s,r){return Os(Ks._MergeMeshesCoroutine(e,t,i,n,s,r,!1))}static MergeMeshesAsync(e,t=!0,i,n,s,r){return Ls(Ks._MergeMeshesCoroutine(e,t,i,n,s,r,!0),function(e=25){let t;return(i,n,s)=>{const r=performance.now();void 0===t||r-t>e?(t=r,setTimeout((()=>{Ps(i,n,s)}),0)):Ps(i,n,s)}}())}static*_MergeMeshesCoroutine(e,t=!0,i,n,s,r,a){if(0===(e=e.filter(Boolean)).length)return null;let o;if(!i){let t=0;for(o=0;o=65536)return c.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}r&&(s=!1);const l=new Array,h=new Array,d=new Array,u=e[0].overrideMaterialSideOrientation;for(o=0;o{const t=e.computeWorldMatrix(!0);return{vertexData:Ns.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:p,transform:m}=_(f);a&&(yield);const g=new Array(e.length-1);for(let t=1;t{throw _("GroundMesh")},Ks._GoldbergMeshParser=(e,t)=>{throw _("GoldbergMesh")},Ks._LinesMeshParser=(e,t)=>{throw _("LinesMesh")},Se("BABYLON.Mesh",Ks),Ks.prototype.setMaterialByID=function(e){return this.setMaterialById(e)},Ks.CreateDisc=Ks.CreateDisc||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.CreateBox=Ks.CreateBox||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.CreateSphere=Ks.CreateSphere||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.CreateCylinder=Ks.CreateCylinder||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.CreateTorusKnot=Ks.CreateTorusKnot||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.CreateTorus=Ks.CreateTorus||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.CreatePlane=Ks.CreatePlane||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.CreateGround=Ks.CreateGround||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.CreateTiledGround=Ks.CreateTiledGround||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.CreateGroundFromHeightMap=Ks.CreateGroundFromHeightMap||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.CreateTube=Ks.CreateTube||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.CreatePolyhedron=Ks.CreatePolyhedron||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.CreateIcoSphere=Ks.CreateIcoSphere||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.CreateDecal=Ks.CreateDecal||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.CreateCapsule=Ks.CreateCapsule||(()=>{throw new Error("Import MeshBuilder to populate this function")}),Ks.ExtendToGoldberg=Ks.ExtendToGoldberg||(()=>{throw new Error("Import MeshBuilder to populate this function")});class js{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class qs extends js{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof Ks))return!1;const t=e;return!(t.isDisposed()||!t.isVisible||!t.isEnabled()||t.instances.length>0||t.skeleton||t.hasLODLevels)}}static get UpdateSelectionTree(){return qs._UpdateSelectionTree}static set UpdateSelectionTree(e){qs._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const n=e.meshes.slice(0);let s=n.length;for(let e=0;e{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),Qs[e.id]=!0)},Js=(e,t)=>{const i={},n=e._geometry;return n&&(e.getScene().getGeometryById(n.id)||Zs(n,t.geometries)),e.serialize&&e.serialize(i),i};class $s{static ClearCache(){Qs=[]}static Serialize(e){return $s._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&Ji.ForceSerializeBuffers&&console.warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),$s.ClearCache(),i.useDelayedTextureLoading=e.useDelayedTextureLoading,i.autoClear=e.autoClear,i.clearColor=e.clearColor.asArray(),i.ambientColor=e.ambientColor.asArray(),i.gravity=e.gravity.asArray(),i.collisionsEnabled=e.collisionsEnabled,i.useRightHandedSystem=e.useRightHandedSystem,e.fogMode&&0!==e.fogMode&&(i.fogMode=e.fogMode,i.fogColor=e.fogColor.asArray(),i.fogStart=e.fogStart,i.fogEnd=e.fogEnd,i.fogDensity=e.fogDensity),e.isPhysicsEnabled()){const t=e.getPhysicsEngine();t&&(i.physicsEnabled=!0,i.physicsGravity=t.gravity.asArray(),i.physicsEngine=t.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const t of e.meshes){const e=t.morphTargetManager;e&&i.morphTargetManagers.push(e.serialize())}let n,s,r;for(i.lights=[],n=0;n0){i.animationGroups=[];for(let t=0;t0)for(i.reflectionProbes=[],n=0;nt))}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t))):(n instanceof Object||Array.isArray(n))&&this._CollectPromises(n,t)}else if(e instanceof Object)for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const n=e[i];n instanceof Promise?t.push(n.then((t=>e[i]=t))):(n instanceof Object||Array.isArray(n))&&this._CollectPromises(n,t)}}static SerializeMesh(e,t=!1,i=!1){const n={};if($s.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let n=0;n{t instanceof Ks&&e.indexOf(t)<0&&!t.doNotSerialize&&e.push(t)})),t&&e[n].parent&&e.indexOf(e[n].parent)<0&&!e[n].parent.doNotSerialize&&e.push(e[n].parent);return e.forEach((e=>{((e,t)=>{if(1===e.delayLoadState||0===e.delayLoadState){const i=i=>{t.materials=t.materials||[],e.material&&!t.materials.some((t=>t.id===e.material.id))&&t.materials.push(i.serialize())};if(e.material&&!e.material.doNotSerialize)if(e.material instanceof Vs){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some((t=>t.id===e.material.id))){t.multiMaterials.push(e.material.serialize());for(const t of e.material.subMaterials)t&&i(t)}}else i(e.material);else e.material||i(e.getScene().defaultMaterial);const n=e._geometry;n&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),Zs(n,t.geometries)),e.skeleton&&!e.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(e.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(Js(e,t))}})(e,n)})),n}}class er{static IsSupported(e){const t=e.getRenderingCanvas();return!!t&&"function"==typeof t.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!er.IsSupported(e))throw"Your browser does not support recording so far.";const i=e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options={...er._DefaultOptions,...t};const n=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const e of this._options.audioTracks)n.addTrack(e);this._mediaRecorder=new MediaRecorder(n,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=this._handleDataAvailable.bind(this),this._mediaRecorder.onerror=this._handleError.bind(this),this._mediaRecorder.onstop=this._handleStop.bind(this)}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout((()=>{this.stopRecording()}),1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)}_handleStop(){this.stopRecording();const e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&Me.Download(e,this._fileName)}}var tr;er._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3},function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(tr||(tr={}));class ir{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;const i={...ir._GetDefaultOptions(),...t};if(this._leftJoystick=!!e,ir._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=tr.X,this._axisTargetedByUpAndDown=tr.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new Pe,this.deltaPosition=ze.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{ir._VJCanvasWidth=window.innerWidth,ir._VJCanvasHeight=window.innerHeight,ir.Canvas&&(ir.Canvas.width=ir._VJCanvasWidth,ir.Canvas.height=ir._VJCanvasHeight),ir._HalfWidth=ir._VJCanvasWidth/2},!ir.Canvas){window.addEventListener("resize",this._onResize,!1),ir.Canvas=document.createElement("canvas"),ir._VJCanvasWidth=window.innerWidth,ir._VJCanvasHeight=window.innerHeight,ir.Canvas.width=window.innerWidth,ir.Canvas.height=window.innerHeight,ir.Canvas.style.width="100%",ir.Canvas.style.height="100%",ir.Canvas.style.position="absolute",ir.Canvas.style.backgroundColor="transparent",ir.Canvas.style.top="0px",ir.Canvas.style.left="0px",ir.Canvas.style.zIndex="5",ir.Canvas.style.touchAction="none",ir.Canvas.setAttribute("touch-action","none");const e=ir.Canvas.getContext("2d");if(!e)throw new Error("Unable to create canvas for virtual joystick");ir._VJCanvasContext=e,ir._VJCanvasContext.strokeStyle="#ffffff",ir._VJCanvasContext.lineWidth=2,document.body.appendChild(ir.Canvas)}ir._HalfWidth=ir.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&ir._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new Ve(0,0),this._joystickPreviousPointerPos=new Ve(0,0),this._joystickPointerStartPos=new Ve(0,0),this._deltaJoystickVector=new Ve(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},ir.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),ir.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),ir.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),ir.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),ir.Canvas.addEventListener("contextmenu",(e=>{e.preventDefault()}),!1),requestAnimationFrame((()=>{this._drawVirtualJoystick()}))}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),t=!0===this._leftJoystick?e.clientXir._HalfWidth,t&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):ir._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){const t=new Ve(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?ir._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(ir._VJCanvasContext.beginPath(),ir._VJCanvasContext.strokeStyle=this._joystickColor,ir._VJCanvasContext.lineWidth=2,ir._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),ir._VJCanvasContext.stroke(),ir._VJCanvasContext.closePath(),ir._VJCanvasContext.beginPath(),ir._VJCanvasContext.lineWidth=6,ir._VJCanvasContext.strokeStyle=this._joystickColor,ir._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),ir._VJCanvasContext.stroke(),ir._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?ir._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(ir._VJCanvasContext.beginPath(),ir._VJCanvasContext.strokeStyle=this._joystickColor,ir._VJCanvasContext.lineWidth=2,ir._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),ir._VJCanvasContext.stroke(),ir._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach(((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(ir._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),ir._VJCanvasContext.beginPath(),ir._VJCanvasContext.fillStyle="white",ir._VJCanvasContext.beginPath(),ir._VJCanvasContext.strokeStyle="red",ir._VJCanvasContext.lineWidth=6,ir._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),ir._VJCanvasContext.stroke(),ir._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)})),requestAnimationFrame((()=>{this._drawVirtualJoystick()})))}releaseCanvas(){ir.Canvas&&(ir.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),ir.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),ir.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),ir.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(ir.Canvas),ir.Canvas=null),this._released=!0}}ir._GlobalJoystickIndex=0,ir._AlwaysVisibleSticks=0;class nr{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 sr extends nr{constructor(e,t,i=sr.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,(()=>{n(),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))}))}))}}sr.DefaultOptions={idleTimeElapsedBeforeRelease:1e3};class rr{static _RemoveAndStorePivotPoint(e){e&&0===rr._PivotCached&&(e.getPivotPointToRef(rr._OldPivotPoint),rr._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,rr._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(Xe.IdentityReadOnly),rr._OldPivotPoint.subtractToRef(e.getPivotPoint(),rr._PivotTranslation),rr._PivotTmpVector.copyFromFloats(1,1,1),rr._PivotTmpVector.subtractInPlace(e.scaling),rr._PivotTmpVector.multiplyInPlace(rr._PivotTranslation),e.position.addInPlace(rr._PivotTmpVector))),rr._PivotCached++}static _RestorePivotPoint(e){e&&!rr._OldPivotPoint.equalsToFloats(0,0,0)&&1===rr._PivotCached&&(e.setPivotPoint(rr._OldPivotPoint),e._postMultiplyPivotMatrix=rr._PivotPostMultiplyPivotMatrix,rr._PivotTmpVector.copyFromFloats(1,1,1),rr._PivotTmpVector.subtractInPlace(e.scaling),rr._PivotTmpVector.multiplyInPlace(rr._PivotTranslation),e.position.subtractInPlace(rr._PivotTmpVector)),this._PivotCached--}}rr._PivotCached=0,rr._OldPivotPoint=new ze,rr._PivotTranslation=new ze,rr._PivotTmpVector=new ze,rr._PivotPostMultiplyPivotMatrix=!1;B.ShadersStore.fxaaPixelShader="#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\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN{const t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)}))}_getDefines(){const e=this.getEngine();if(!e)return null;const t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,n){return gt.Parse((()=>new ar(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}Se("BABYLON.FxaaPostProcess",ar);let or=null;function lr(e,t,i,n,s="image/png",r=!1){const{height:a,width:o}=cr(e,t,i);if(!a||!o)return void c.Error("Invalid 'size' parameter !");or||(or=document.createElement("canvas")),or.width=o,or.height=a;const l=or.getContext("2d"),h=e.getRenderWidth()/e.getRenderHeight();let d=o,u=d/h;u>a&&(u=a,d=u*h);const f=Math.max(0,o-d)/2,_=Math.max(0,a-u)/2;t.getScene().activeCamera!==t?hr(e,t,i,(e=>{if(r){const t=new Blob([e]);Me.DownloadBlob(t),n&&n("")}else n&&n(e)}),s,1,e.getCreationOptions().antialias):e.onEndFrameObservable.addOnce((()=>{const t=e.getRenderingCanvas();l&&t&&l.drawImage(t,f,_,d,u),or&&(r?(Me.EncodeScreenshotCanvasData(or,void 0,s),n&&n("")):Me.EncodeScreenshotCanvasData(or,n,s))}))}function hr(e,t,i,n,s="image/png",r=1,a=!1,o,l=!1,h=!1,d=!0){const{height:u,width:f}=cr(e,t,i),_={width:f,height:u};if(!u||!f)return void c.Error("Invalid 'size' parameter !");const p={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(f,u);const m=t.getScene(),g=new Un("screenShot",_,m,!1,!1,0,!1,Ji.NEAREST_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,r);g.renderList=m.meshes.slice(),g.samples=r,g.renderSprites=l,g.activeCamera=t,g.forceLayerMaskCheck=d;const E=()=>{e.onEndFrameObservable.addOnce((()=>{g.readPixels(void 0,void 0,void 0,!1).then((e=>{Bn.DumpData(f,u,e,n,s,o,!0),g.dispose()}))})),m.incrementRenderId(),m.resetCachedMaterial(),g.render(!0),m.incrementRenderId(),m.resetCachedMaterial(),e.setSize(p.width,p.height),t.getProjectionMatrix(!0),m.render()};if(a){const e=new ar("antialiasing",1,m.activeCamera);g.addPostProcess(e),e.getEffect().isReady()?E():e.getEffect().onCompiled=()=>{E()}}else E()}function cr(e,t,i){let n=0,s=0;if("object"==typeof i){const r=i.precision?Math.abs(i.precision):1;i.width&&i.height?(n=i.height*r,s=i.width*r):i.width&&!i.height?(s=i.width*r,n=Math.round(s/e.getAspectRatio(t))):i.height&&!i.width?(n=i.height*r,s=Math.round(n*e.getAspectRatio(t))):(s=Math.round(e.getRenderWidth()*r),n=Math.round(s/e.getAspectRatio(t)))}else isNaN(i)||(n=i,s=i);return s&&(s=Math.floor(s)),n&&(n=Math.floor(n)),{height:0|n,width:0|s}}var dr;Me.CreateScreenshot=lr,Me.CreateScreenshotAsync=function(e,t,i,n="image/png"){return new Promise(((s,r)=>{lr(e,t,i,(e=>{void 0!==e?s(e):r(new Error("Data is undefined"))}),n)}))},Me.CreateScreenshotUsingRenderTarget=hr,Me.CreateScreenshotUsingRenderTargetAsync=function(e,t,i,n="image/png",s=1,r=!1,a,o=!1,l=!1,h=!0){return new Promise(((c,d)=>{hr(e,t,i,(e=>{void 0!==e?c(e):d(new Error("Data is undefined"))}),n,s,r,a,o,l,h)}))},function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(dr||(dr={}));let ur=0;const fr=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const n=Ji.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"+ur++,e,!0,!1,Ji.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const s=e.getEngine().getLoadedTexturesCache(),r=s.indexOf(n.getInternalTexture());-1!==r&&s.splice(r,1),n.isRGBD=!0,n.wrapU=Ji.CLAMP_ADDRESSMODE,n.wrapV=Ji.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=n,e.useDelayedTextureLoading=t,Ms.ExpandRGBDTexture(n);const a=e.getEngine().onContextRestoredObservable.add((()=>{n.isRGBD=!0;const e=()=>{n.isReady()?Ms.ExpandRGBDTexture(n):Me.SetImmediate(e)};e()}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(a)}))}return e.environmentBRDFTexture};class _r{constructor(e,t,i){this.gradient=e,this.color1=t,this.color2=i}getColorToRef(e){this.color2?it.LerpToRef(this.color1,this.color2,Math.random(),e):e.copyFrom(this.color1)}}class pr{constructor(e,t){this.gradient=e,this.color=t}}class mr{constructor(e,t,i){this.gradient=e,this.factor1=t,this.factor2=i}getFactor(){return void 0===this.factor2||this.factor2===this.factor1?this.factor1:this.factor1+(this.factor2-this.factor1)*Math.random()}}class gr{static GetCurrentGradient(e,t,i){if(t[0].gradient>e)return void i(t[0],t[0],1);for(let n=0;n=s.gradient&&e<=r.gradient)return void i(s,r,(e-s.gradient)/(r.gradient-s.gradient))}const n=t.length-1;i(t[n],t[n],1)}}class Er{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.clear(this.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((()=>{var e;null===(e=o._debugPushGroup)||void 0===e||e.call(o,"depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((()=>{var e;null===(e=o._debugPopGroup)||void 0===e||e.call(o,1)})),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{var t,i;const n=e.getRenderingMesh(),s=e.getEffectiveMesh(),r=this._scene,a=r.getEngine(),o=e.getMaterial();if(s._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!o||s.infiniteDistance||o.disableDepthWrite||0===e.verticesCount||e._renderId===r.getRenderId())return;const l=s._getWorldMatrixDeterminant()<0;let h=null!==(t=n.overrideMaterialSideOrientation)&&void 0!==t?t:o.sideOrientation;l&&(h=0===h?1:0);const c=0===h;a.setState(o.backFaceCulling,0,!1,c,this.reverseCulling?!o.cullBackFaces:o.cullBackFaces);const d=n._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(d.mustReturn)return;const u=a.getCaps().instancedArrays&&(null!==d.visibleInstances[e._id]&&void 0!==d.visibleInstances[e._id]||n.hasThinInstances),f=this._camera||r.activeCamera;if(this.isReady(e,u)&&f){e._renderId=r.getRenderId();const t=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[a.currentRenderPassId];let l=e._getDrawWrapper();!l&&t&&(l=t._getDrawWrapper());const h=f.mode===wi.ORTHOGRAPHIC_CAMERA;if(!l)return;const c=l.effect;let _,p;if(a.enableEffect(l),u||n._bind(e,c,o.fillMode),t?t.bindForSubMesh(s.getWorldMatrix(),s,e):(c.setMatrix("viewProjection",r.getTransformMatrix()),c.setMatrix("world",s.getWorldMatrix()),this._storeCameraSpaceZ&&c.setMatrix("view",r.getViewMatrix())),h?(_=!a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1,p=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1):(_=a.useReverseDepthBuffer&&a.isNDCHalfZRange?f.minZ:a.isNDCHalfZRange?0:f.minZ,p=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:f.maxZ),c.setFloat2("depthValues",_,_+p),!t){if(o.needAlphaTesting()){const e=o.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(n.useBones&&n.computeBonesUsingShaders&&n.skeleton){const e=n.skeleton;if(e.isUsingTextureForMatrices){const t=e.getTransformMatrixTexture(n);if(!t)return;c.setTexture("boneSampler",t),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",e.getTransformMatrices(n))}ki(c,o,r),zi.BindMorphTargetParameters(n,c),n.morphTargetManager&&n.morphTargetManager.isUsingTextureForTargets&&n.morphTargetManager._bind(c)}n._processRendering(s,e,c,o.fillMode,d,u,((e,t)=>c.setMatrix("world",t)))}};this._depthMap.customRenderFunction=(e,t,i,n)=>{let s;if(n.length)for(s=0;s4&&(h.push(Lt.MatricesIndicesExtraKind),h.push(Lt.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),l.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));const t=e.getRenderingMesh().skeleton;(null==t?void 0:t.isUsingTextureForMatrices)&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");const c=s.morphTargetManager;let d=0;c&&c.numInfluencers>0&&(d=c.numInfluencers,l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+d),c.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),zi.PrepareAttributesForMorphTargetsInfluencers(h,s,d)),t&&(l.push("#define INSTANCES"),zi.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&l.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&l.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&l.push("#define PACKED"),Ui(o,r,l);const u=e._getDrawWrapper(void 0,!0),f=u.defines,_=l.join("\n");if(f!==_){const e=["world","mBones","boneTextureWidth","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];Bi(e),u.setEffect(n.createEffect("depth",h,e,["diffuseSampler","morphTargets","boneSampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:d}),_)}return u.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}Tr._SceneComponentInitialization=e=>{throw _("DepthRendererSceneComponent")};class Ar{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch(e){const t={};return{getItem:e=>{const i=t[e];return void 0===i?null:i},setItem:(e,i)=>{t[e]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}Ar._Storage=Ar._GetStorage();class vr extends Ei{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){this._needToCompose=!1,e.updateFlag!==this._localMatrix.updateFlag&&(this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,n=null,s=null,r=null,a=null){super(e,t.getScene()),this.name=e,this.children=new Array,this.animations=new Array,this._index=null,this._absoluteTransform=new Xe,this._invertedAbsoluteTransform=new Xe,this._scalingDeterminant=1,this._worldTransform=new Xe,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=n?n.clone():Xe.Identity(),this._restPose=s||this._localMatrix.clone(),this._baseMatrix=r||this._localMatrix.clone(),this._index=a,t.bones.push(this),this.setParent(i,!1),(r||n)&&this._updateDifferenceMatrix()}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._updateDifferenceMatrix(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBaseMatrix(){return this._baseMatrix}getRestPose(){return this._restPose}setRestPose(e){this._restPose.copyFrom(e)}getBindPose(){return this._baseMatrix}setBindPose(e){this.updateMatrix(e)}getWorldMatrix(){return this._worldTransform}returnToRest(){var e;if(this._linkedTransformNode){const t=Ke.Vector3[0],i=Ke.Quaternion[0],n=Ke.Vector3[1];this.getRestPose().decompose(t,i,n),this._linkedTransformNode.position.copyFrom(n),this._linkedTransformNode.rotationQuaternion=null!==(e=this._linkedTransformNode.rotationQuaternion)&&void 0!==e?e:We.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}else this._matrix=this._restPose}getInvertedAbsoluteTransform(){return this._invertedAbsoluteTransform}getAbsoluteTransform(){return this._absoluteTransform}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=ze.Zero(),this._localRotation=We.Zero(),this._localPosition=ze.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,Xe.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)}updateMatrix(e,t=!0,i=!0){this._baseMatrix.copyFrom(e),t&&this._updateDifferenceMatrix(),i?this._matrix=e:this.markAsDirty()}_updateDifferenceMatrix(e,t=!0){if(e||(e=this._baseMatrix),this.parent?e.multiplyToRef(this.parent._absoluteTransform,this._absoluteTransform):this._absoluteTransform.copyFrom(e),this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform),t)for(let e=0;e=0?t:0;let a=0;const o=r._keys[0];let l=r._keys.length-1;const h=r._keys[l],c={referenceValue:o.value,referencePosition:Ke.Vector3[0],referenceQuaternion:Ke.Quaternion[0],referenceScaling:Ke.Vector3[1],keyPosition:Ke.Vector3[2],keyQuaternion:Ke.Quaternion[1],keyScaling:Ke.Vector3[3]};let d=!1,u=o.frame,f=h.frame;if(i){const e=r.getRange(i);e&&(u=e.from,f=e.to)}let _=o.frame===u,p=h.frame===f;if(1===r._keys.length){const e=r._getKeyValue(r._keys[0]);c.referenceValue=e.clone?e.clone():e,d=!0}else if(t<=o.frame){const e=r._getKeyValue(o.value);c.referenceValue=e.clone?e.clone():e,d=!0}else if(t>=h.frame){const e=r._getKeyValue(h.value);c.referenceValue=e.clone?e.clone():e,d=!0}let m=0;for(;!d||!_||!p&&m=e.frame&&t<=i.frame){let n;if(t===e.frame)n=r._getKeyValue(e.value);else if(t===i.frame)n=r._getKeyValue(i.value);else{const e={key:m,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT};n=r._interpolate(t,e)}c.referenceValue=n.clone?n.clone():n,d=!0}if(!_&&u>=e.frame&&u<=i.frame){if(u===e.frame)a=m;else if(u===i.frame)a=m+1;else{const e={key:m,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},t=r._interpolate(u,e),i={frame:u,value:t.clone?t.clone():t};r._keys.splice(m+1,0,i),a=m+1}_=!0}if(!p&&f>=e.frame&&f<=i.frame){if(f===e.frame)l=m;else if(f===i.frame)l=m+1;else{const e={key:m,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},t=r._interpolate(f,e),i={frame:f,value:t.clone?t.clone():t};r._keys.splice(m+1,0,i),l=m+1}p=!0}m++}for(r.dataType===Mr.ANIMATIONTYPE_QUATERNION?c.referenceValue.normalize().conjugateInPlace():r.dataType===Mr.ANIMATIONTYPE_MATRIX&&(c.referenceValue.decompose(c.referenceScaling,c.referenceQuaternion,c.referencePosition),c.referenceQuaternion.normalize().conjugateInPlace()),m=a;m<=l;m++){const e=r._keys[m];if(!m||r.dataType===Mr.ANIMATIONTYPE_FLOAT||e.value!==o.value)switch(r.dataType){case Mr.ANIMATIONTYPE_MATRIX:e.value.decompose(c.keyScaling,c.keyQuaternion,c.keyPosition),c.keyPosition.subtractInPlace(c.referencePosition),c.keyScaling.divideInPlace(c.referenceScaling),c.referenceQuaternion.multiplyToRef(c.keyQuaternion,c.keyQuaternion),Xe.ComposeToRef(c.keyScaling,c.keyQuaternion,c.keyPosition,e.value);break;case Mr.ANIMATIONTYPE_QUATERNION:c.referenceValue.multiplyToRef(e.value,e.value);break;case Mr.ANIMATIONTYPE_VECTOR2:case Mr.ANIMATIONTYPE_VECTOR3:case Mr.ANIMATIONTYPE_COLOR3:case Mr.ANIMATIONTYPE_COLOR4:e.value.subtractToRef(c.referenceValue,e.value);break;case Mr.ANIMATIONTYPE_SIZE:e.value.width-=c.referenceValue.width,e.value.height-=c.referenceValue.height;break;default:e.value-=c.referenceValue}}return r}static TransitionTo(e,t,i,n,s,r,a,o=null){if(a<=0)return i[e]=t,o&&o(),null;const l=s*(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=n.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,n,s,r){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=n,this.loopMode=s,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=n,this.loopMode=void 0===s?Mr.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=Mr._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=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;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const i=this._keys,n=i.length;let s=t.key;for(;s>=0&&e=i[s+1].frame;)++s;if(t.key=s,s<0)return this._getKeyValue(i[0].value);if(s+1>n-1)return this._getKeyValue(i[n-1].value);const r=i[s],a=i[s+1],o=this._getKeyValue(r.value),l=this._getKeyValue(a.value);if(r.interpolation===Rr.STEP)return a.frame>e?o:l;const h=void 0!==r.outTangent&&void 0!==a.inTangent,c=a.frame-r.frame;let d=(e-r.frame)/c;const u=this.getEasingFunction();switch(null!==u&&(d=u.ease(d)),this.dataType){case Mr.ANIMATIONTYPE_FLOAT:{const e=h?this.floatInterpolateFunctionWithTangents(o,r.outTangent*c,l,a.inTangent*c,d):this.floatInterpolateFunction(o,l,d);switch(t.loopMode){case Mr.ANIMATIONLOOPMODE_CYCLE:case Mr.ANIMATIONLOOPMODE_CONSTANT:return e;case Mr.ANIMATIONLOOPMODE_RELATIVE:return t.offsetValue*t.repeatCount+e}break}case Mr.ANIMATIONTYPE_QUATERNION:{const e=h?this.quaternionInterpolateFunctionWithTangents(o,r.outTangent.scale(c),l,a.inTangent.scale(c),d):this.quaternionInterpolateFunction(o,l,d);switch(t.loopMode){case Mr.ANIMATIONLOOPMODE_CYCLE:case Mr.ANIMATIONLOOPMODE_CONSTANT:return e;case Mr.ANIMATIONLOOPMODE_RELATIVE:return e.addInPlace(t.offsetValue.scale(t.repeatCount))}return e}case Mr.ANIMATIONTYPE_VECTOR3:{const e=h?this.vector3InterpolateFunctionWithTangents(o,r.outTangent.scale(c),l,a.inTangent.scale(c),d):this.vector3InterpolateFunction(o,l,d);switch(t.loopMode){case Mr.ANIMATIONLOOPMODE_CYCLE:case Mr.ANIMATIONLOOPMODE_CONSTANT:return e;case Mr.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case Mr.ANIMATIONTYPE_VECTOR2:{const e=h?this.vector2InterpolateFunctionWithTangents(o,r.outTangent.scale(c),l,a.inTangent.scale(c),d):this.vector2InterpolateFunction(o,l,d);switch(t.loopMode){case Mr.ANIMATIONLOOPMODE_CYCLE:case Mr.ANIMATIONLOOPMODE_CONSTANT:return e;case Mr.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case Mr.ANIMATIONTYPE_SIZE:switch(t.loopMode){case Mr.ANIMATIONLOOPMODE_CYCLE:case Mr.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(o,l,d);case Mr.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(o,l,d).add(t.offsetValue.scale(t.repeatCount))}break;case Mr.ANIMATIONTYPE_COLOR3:{const e=h?this.color3InterpolateFunctionWithTangents(o,r.outTangent.scale(c),l,a.inTangent.scale(c),d):this.color3InterpolateFunction(o,l,d);switch(t.loopMode){case Mr.ANIMATIONLOOPMODE_CYCLE:case Mr.ANIMATIONLOOPMODE_CONSTANT:return e;case Mr.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case Mr.ANIMATIONTYPE_COLOR4:{const e=h?this.color4InterpolateFunctionWithTangents(o,r.outTangent.scale(c),l,a.inTangent.scale(c),d):this.color4InterpolateFunction(o,l,d);switch(t.loopMode){case Mr.ANIMATIONLOOPMODE_CYCLE:case Mr.ANIMATIONLOOPMODE_CONSTANT:return e;case Mr.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case Mr.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case Mr.ANIMATIONLOOPMODE_CYCLE:case Mr.ANIMATIONLOOPMODE_CONSTANT:return Mr.AllowMatricesInterpolation?this.matrixInterpolateFunction(o,l,d,t.workValue):o;case Mr.ANIMATIONLOOPMODE_RELATIVE:return o}}return 0}matrixInterpolateFunction(e,t,i,n){return Mr.AllowMatrixDecomposeForInterpolation?n?(Xe.DecomposeLerpToRef(e,t,i,n),n):Xe.DecomposeLerp(e,t,i):n?(Xe.LerpToRef(e,t,i,n),n):Xe.Lerp(e,t,i)}clone(){const e=new Mr(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){this._keys=e.slice(0)}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 n=0;n=2&&(a=t.values[1]),t.values.length>=3&&(o=t.values[2]),t.values.length>=4&&(l=t.values[3]);break;case Mr.ANIMATIONTYPE_QUATERNION:if(s=We.FromArray(t.values),t.values.length>=8){const e=We.FromArray(t.values.slice(4,8));e.equals(We.Zero())||(a=e)}if(t.values.length>=12){const e=We.FromArray(t.values.slice(8,12));e.equals(We.Zero())||(o=e)}t.values.length>=13&&(l=t.values[12]);break;case Mr.ANIMATIONTYPE_MATRIX:s=Xe.FromArray(t.values),t.values.length>=17&&(l=t.values[16]);break;case Mr.ANIMATIONTYPE_COLOR3:s=tt.FromArray(t.values),t.values[3]&&(a=tt.FromArray(t.values[3])),t.values[4]&&(o=tt.FromArray(t.values[4])),t.values[5]&&(l=t.values[5]);break;case Mr.ANIMATIONTYPE_COLOR4:s=it.FromArray(t.values),t.values[4]&&(a=it.FromArray(t.values[4])),t.values[5]&&(o=it.FromArray(t.values[5])),t.values[6]&&(l=it.FromArray(t.values[6]));break;case Mr.ANIMATIONTYPE_VECTOR3:default:s=ze.FromArray(t.values),t.values[3]&&(a=ze.FromArray(t.values[3])),t.values[4]&&(o=ze.FromArray(t.values[4])),t.values[5]&&(l=t.values[5])}const h={};h.frame=t.frame,h.value=s,null!=a&&(h.inTangent=a),null!=o&&(h.outTangent=o),null!=l&&(h.interpolation=l),n.push(h)}if(t.setKeys(n),e.ranges)for(r=0;r{const s=new p;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){let t=JSON.parse(s.responseText);if(t.animations&&(t=t.animations),t.length){const e=new Array;for(const i of t)e.push(this.Parse(i));i(e)}else{const n=this.Parse(t);e&&(n.name=e),i(n)}}else n("Unable to load the animation")})),s.open("GET",t),s.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const n=new p;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const i=JSON.parse(JSON.parse(n.responseText).jsonPayload);if(i.animations){const n=JSON.parse(i.animations),s=new Array;for(const t of n.animations){const i=this.Parse(t);i.snippetId=e,s.push(i)}t(s)}else{const n=JSON.parse(i.animation),s=this.Parse(n);s.snippetId=e,t(s)}}else i("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}Mr._UniqueIdGenerator=0,Mr.AllowMatricesInterpolation=!1,Mr.AllowMatrixDecomposeForInterpolation=!0,Mr.SnippetUrl="https://snippet.babylonjs.com",Mr.ANIMATIONTYPE_FLOAT=0,Mr.ANIMATIONTYPE_VECTOR3=1,Mr.ANIMATIONTYPE_QUATERNION=2,Mr.ANIMATIONTYPE_MATRIX=3,Mr.ANIMATIONTYPE_COLOR3=4,Mr.ANIMATIONTYPE_COLOR4=7,Mr.ANIMATIONTYPE_VECTOR2=5,Mr.ANIMATIONTYPE_SIZE=6,Mr.ANIMATIONLOOPMODE_RELATIVE=0,Mr.ANIMATIONLOOPMODE_CYCLE=1,Mr.ANIMATIONLOOPMODE_CONSTANT=2,Mr.CreateFromSnippetAsync=Mr.ParseFromSnippetAsync,Se("BABYLON.Animation",Mr),Ei._AnimationRangeFactory=(e,t,i)=>new xr(e,t,i);class Ir{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=new Array,this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=Xe.Identity(),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 s,this.bones=[],this._scene=i||m.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const n=this._scene.getEngine().getCaps();this._canUseTextureForBones=n.textureFloat&&n.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter((e=>!e.getParent()))}getTransformMatrices(e){return this.needInitialSkinMatrix?(e._bonesTransformMatrices||this.prepare(),e._bonesTransformMatrices):(this._transformMatrices&&!this._isDirty||this.prepare(),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-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0)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)e.getParent()||(e.getBaseMatrix().multiplyToRef(t,Ke.Matrix[1]),e._updateDifferenceMatrix(Ke.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=Sr.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))}}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=Sr.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))),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{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(){var e;const t={};t.name=this.name,t.id=this.id,this.dimensionsAtRest&&(t.dimensionsAtRest=this.dimensionsAtRest.asArray()),t.bones=[],t.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let i=0;i0&&(r.animation=n.animations[0].serialize()),t.ranges=[];for(const e in this._ranges){const i=this._ranges[e];if(!i)continue;const n={};n.name=e,n.from=i.from,n.to=i.to,t.ranges.push(n)}}return t}static Parse(e,t){const i=new Ir(e.name,e.id,t);let n;for(e.dimensionsAtRest&&(i.dimensionsAtRest=ze.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,n=0;n-1&&(r=i.bones[t.parentBoneIndex]);const a=t.rest?Xe.FromArray(t.rest):null,o=new vr(t.name,i,r,Xe.FromArray(t.matrix),a,null,s);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(Mr.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,o._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(n=0;n0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=new Array,t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()}))}}class br{constructor(){this.direction1=new ze(0,1,0),this.direction2=new ze(0,1,0),this.minEmitBox=new ze(-.5,-.5,-.5),this.maxEmitBox=new ze(.5,.5,.5)}startDirectionFunction(e,t,i,n){const s=Le.RandomRange(this.direction1.x,this.direction2.x),r=Le.RandomRange(this.direction1.y,this.direction2.y),a=Le.RandomRange(this.direction1.z,this.direction2.z);if(n)return t.x=s,t.y=r,void(t.z=a);ze.TransformNormalFromFloatsToRef(s,r,a,e,t)}startPositionFunction(e,t,i,n){const s=Le.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),r=Le.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),a=Le.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(n)return t.x=s,t.y=r,void(t.z=a);ze.TransformCoordinatesFromFloatsToRef(s,r,a,e,t)}clone(){const e=new br;return u.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){ze.FromArrayToRef(e.direction1,0,this.direction1),ze.FromArrayToRef(e.direction2,0,this.direction2),ze.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),ze.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class yr{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,n){n?Ke.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),Ke.Vector3[0]).normalize();const s=Le.RandomRange(0,this.directionRandomizer),r=Le.RandomRange(0,this.directionRandomizer),a=Le.RandomRange(0,this.directionRandomizer);t.x=Ke.Vector3[0].x+s,t.y=Ke.Vector3[0].y+r,t.z=Ke.Vector3[0].z+a,t.normalize()}startPositionFunction(e,t,i,n){const s=Le.RandomRange(0,2*Math.PI);let r;this.emitFromSpawnPointOnly?r=1e-4:(r=Le.RandomRange(0,this.heightRange),r=1-r*r);let a=this._radius-Le.RandomRange(0,this._radius*this.radiusRange);a*=r;const o=a*Math.sin(s),l=a*Math.cos(s),h=r*this._height;if(n)return t.x=o,t.y=h,void(t.z=l);ze.TransformCoordinatesFromFloatsToRef(o,h,l,e,t)}clone(){const e=new yr(this._radius,this._angle,this.directionRandomizer);return u.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e}getClassName(){return"ConeParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}}class Pr{constructor(e=1,t=1,i=1,n=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=n,this._tempVector=ze.Zero()}startDirectionFunction(e,t,i,n,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),ze.TransformNormalToRef(this._tempVector,s,this._tempVector);const r=Le.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let a=Math.atan2(this._tempVector.x,this._tempVector.z);a+=Le.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=r,this._tempVector.x=Math.sin(a),this._tempVector.z=Math.cos(a),this._tempVector.normalize(),n?t.copyFrom(this._tempVector):ze.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,n){const s=Le.RandomRange(-this.height/2,this.height/2),r=Le.RandomRange(0,2*Math.PI),a=Le.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),o=Math.sqrt(a)*this.radius,l=o*Math.cos(r),h=o*Math.sin(r);n?t.copyFromFloats(l,s,h):ze.TransformCoordinatesFromFloatsToRef(l,s,h,e,t)}clone(){const e=new Pr(this.radius,this.directionRandomizer);return u.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class Dr extends Pr{constructor(e=1,t=1,i=1,n=new ze(0,1,0),s=new ze(0,1,0)){super(e,t,i),this.direction1=n,this.direction2=s}startDirectionFunction(e,t){const i=Le.RandomRange(this.direction1.x,this.direction2.x),n=Le.RandomRange(this.direction1.y,this.direction2.y),s=Le.RandomRange(this.direction1.z,this.direction2.z);ze.TransformNormalFromFloatsToRef(i,n,s,e,t)}clone(){const e=new Dr(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return u.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class Or{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,n){const s=i.position.subtract(e.getTranslation()).normalize(),r=Le.RandomRange(0,this.directionRandomizer),a=Le.RandomRange(0,this.directionRandomizer),o=Le.RandomRange(0,this.directionRandomizer);s.x+=r,s.y+=a,s.z+=o,s.normalize(),n?t.copyFrom(s):ze.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,n){const s=this.radius-Le.RandomRange(0,this.radius*this.radiusRange),r=Le.RandomRange(0,1),a=Le.RandomRange(0,2*Math.PI),o=Math.acos(2*r-1),l=s*Math.cos(a)*Math.sin(o),h=s*Math.cos(o),c=s*Math.sin(a)*Math.sin(o);n?t.copyFromFloats(l,Math.abs(h),c):ze.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),c,e,t)}clone(){const e=new Or(this.radius,this.directionRandomizer);return u.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class Lr{constructor(){this.direction1=new ze(0,1,0),this.direction2=new ze(0,1,0)}startDirectionFunction(e,t,i,n){const s=Le.RandomRange(this.direction1.x,this.direction2.x),r=Le.RandomRange(this.direction1.y,this.direction2.y),a=Le.RandomRange(this.direction1.z,this.direction2.z);n?t.copyFromFloats(s,r,a):ze.TransformNormalFromFloatsToRef(s,r,a,e,t)}startPositionFunction(e,t,i,n){n?t.copyFromFloats(0,0,0):ze.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new Lr;return u.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){ze.FromArrayToRef(e.direction1,0,this.direction1),ze.FromArrayToRef(e.direction2,0,this.direction2)}}class Nr{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,n){const s=i.position.subtract(e.getTranslation()).normalize(),r=Le.RandomRange(0,this.directionRandomizer),a=Le.RandomRange(0,this.directionRandomizer),o=Le.RandomRange(0,this.directionRandomizer);s.x+=r,s.y+=a,s.z+=o,s.normalize(),n?t.copyFrom(s):ze.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,n){const s=this.radius-Le.RandomRange(0,this.radius*this.radiusRange),r=Le.RandomRange(0,1),a=Le.RandomRange(0,2*Math.PI),o=Math.acos(2*r-1),l=s*Math.cos(a)*Math.sin(o),h=s*Math.cos(o),c=s*Math.sin(a)*Math.sin(o);n?t.copyFromFloats(l,h,c):ze.TransformCoordinatesFromFloatsToRef(l,h,c,e,t)}clone(){const e=new Nr(this.radius,this.directionRandomizer);return u.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class Fr extends Nr{constructor(e=1,t=new ze(0,1,0),i=new ze(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=Le.RandomRange(this.direction1.x,this.direction2.x),n=Le.RandomRange(this.direction1.y,this.direction2.y),s=Le.RandomRange(this.direction1.z,this.direction2.z);ze.TransformNormalFromFloatsToRef(i,n,s,e,t)}clone(){const e=new Fr(this.radius,this.direction1,this.direction2);return u.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class wr{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(Lt.PositionKind),this._normals=e.getVerticesData(Lt.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=ze.Zero(),this._mesh=null,this.direction1=new ze(0,1,0),this.direction2=new ze(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,n){if(this.useMeshNormalsForDirection&&this._normals)return void ze.TransformNormalToRef(this._storedNormal,e,t);const s=Le.RandomRange(this.direction1.x,this.direction2.x),r=Le.RandomRange(this.direction1.y,this.direction2.y),a=Le.RandomRange(this.direction1.z,this.direction2.z);n?t.copyFromFloats(s,r,a):ze.TransformNormalFromFloatsToRef(s,r,a,e,t)}startPositionFunction(e,t,i,n){if(!this._indices||!this._positions)return;const s=3*Math.random()*(this._indices.length/3)|0,r=Math.random(),a=Math.random()*(1-r),o=1-r-a,l=this._indices[s],h=this._indices[s+1],c=this._indices[s+2],d=Ke.Vector3[0],u=Ke.Vector3[1],f=Ke.Vector3[2],_=Ke.Vector3[3];ze.FromArrayToRef(this._positions,3*l,d),ze.FromArrayToRef(this._positions,3*h,u),ze.FromArrayToRef(this._positions,3*c,f),_.x=r*d.x+a*u.x+o*f.x,_.y=r*d.y+a*u.y+o*f.y,_.z=r*d.z+a*u.z+o*f.z,n?t.copyFromFloats(_.x,_.y,_.z):ze.TransformCoordinatesFromFloatsToRef(_.x,_.y,_.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(ze.FromArrayToRef(this._normals,3*l,d),ze.FromArrayToRef(this._normals,3*h,u),ze.FromArrayToRef(this._normals,3*c,f),this._storedNormal.x=r*d.x+a*u.x+o*f.x,this._storedNormal.y=r*d.y+a*u.y+o*f.y,this._storedNormal.z=r*d.z+a*u.z+o*f.z)}clone(){const e=new wr(this.mesh);return u.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){var e;const t={};return t.type=this.getClassName(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.meshId=null===(e=this.mesh)||void 0===e?void 0:e.id,t.useMeshNormalsForDirection=this.useMeshNormalsForDirection,t}parse(e,t){ze.FromArrayToRef(e.direction1,0,this.direction1),ze.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class Br{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:ze.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:ze.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:ze.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:ze.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let n=0;for(const i of t){if(i.gradient===e){t.splice(n,1);break}n++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=ze.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new ze(10,10,10),this.onAnimationEnd=null,this.blendMode=Br.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new Ve(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new ze(0,0,0),this._useLogarithmicDepth=!1,this.gravity=ze.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new it(1,1,1,1),this.color2=new it(1,1,1,1),this.colorDead=new it(0,0,0,1),this.textureMask=new it(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new vt,this.id=e,this.name=e}createPointEmitter(e,t){const i=new Lr;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=new Or(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=new Nr(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new ze(0,1,0),i=new ze(0,1,0)){const n=new Fr(e,t,i);return this.particleEmitterType=n,n}createCylinderEmitter(e=1,t=1,i=1,n=0){const s=new Pr(e,t,i,n);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,n=new ze(0,1,0),s=new ze(0,1,0)){const r=new Dr(e,t,i,n,s);return this.particleEmitterType=r,r}createConeEmitter(e=1,t=Math.PI/4){const i=new yr(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,n){const s=new br;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=n,s}}Br.BLENDMODE_ONEONE=0,Br.BLENDMODE_STANDARD=1,Br.BLENDMODE_ADD=2,Br.BLENDMODE_MULTIPLY=3,Br.BLENDMODE_MULTIPLYADD=4;class Ur{constructor(e){this.particleSystem=e,this.position=ze.Zero(),this.direction=ze.Zero(),this.color=new it(0,0,0,0),this.colorStep=new it(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new Ve(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new it(0,0,0,0),this._currentColor2=new it(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=Ur._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===t?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID;let n;n=this._initialSpriteCellLoop?Le.Clamp(e*t%this.lifeTime/this.lifeTime):Le.Clamp(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+n*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const e=Ke.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,Ke.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(Ke.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach((e=>{this._inheritParticleInfoToSubEmitter(e)}))}_reset(){this.age=0,this.id=Ur._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new He(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}}Ur._Count=0,function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(Cr||(Cr={}));class kr{constructor(e){if(this.particleSystem=e,this.type=Cr.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=Re("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;e?e instanceof ze?e=e.clone():-1!==e.getClassName().indexOf("Mesh")&&(e=new(Re("BABYLON.Mesh"))("",e.getScene()),e.isVisible=!1):e=new ze;const t=new kr(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){const t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,n=!1){throw _("ParseParticle")}static Parse(e,t,i){const n=e.particleSystem,s=new kr(kr._ParseParticleSystem(n,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}}B.ShadersStore.particlesPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";B.ShadersStore.particlesVertexShader="attribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos; \n#endif\nvarying vec2 vUV;\nvarying vec4 vColor;\nvarying vec3 vPositionW;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix= mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvec3 row1=direction;\n#else\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nmat3 rotMatrix= mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvPositionW=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition;\nvPositionW=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;\nvPositionW=(invView*vec4(viewPos,1)).xyz;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\ngl_Position=projection*vec4(viewPos,1.0);\n#else\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvPositionW=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(vPositionW,1.0);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex*particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset/particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";class Gr extends Br{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){var t,i;return null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new $(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new s),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,n=null,r=!1,a=.01){super(e),this._emitterInverseWorldMatrix=Xe.Identity(),this._inheritedVelocityOffset=new ze,this.onDisposeObservable=new s,this.onStoppedObservable=new s,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new it(0,0,0,0),this._colorDiff=new it(0,0,0,0),this._scaledDirection=ze.Zero(),this._scaledGravity=ze.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this._disposeEmitterOnDispose=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this.recycleParticle=e=>{const t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;if(0!==this._stockParticles.length?(e=this._stockParticles.pop(),e._reset()):e=new Ur(this),this._subEmitters&&this._subEmitters.length>0){const t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach((t=>{if(t.type===Cr.ATTACHED){const i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}}))}return e},this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach((t=>{if(t.type===Cr.END){const i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}}))},this._capacity=t,this._epsilon=a,this._isAnimationSheetEnabled=r,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=Xe.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||m.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new $(this._engine)},this._customWrappers[0].effect=n,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new br;let o=null;this.updateFunction=e=>{var t;let i=null;this.noiseTexture&&(i=this.noiseTexture.getSize(),null===(t=this.noiseTexture.getContent())||void 0===t||t.then((e=>{o=e})));for(let t=0;tn.lifeTime){const e=n.age-r;s=(n.lifeTime-r)*s/e,n.age=n.lifeTime}const a=n.age/n.lifeTime;this._colorGradients&&this._colorGradients.length>0?gr.GetCurrentGradient(a,this._colorGradients,((e,t,i)=>{e!==n._currentColorGradient&&(n._currentColor1.copyFrom(n._currentColor2),t.getColorToRef(n._currentColor2),n._currentColorGradient=e),it.LerpToRef(n._currentColor1,n._currentColor2,i,n.color)})):(n.colorStep.scaleToRef(s,this._scaledColorStep),n.color.addInPlace(this._scaledColorStep),n.color.a<0&&(n.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&gr.GetCurrentGradient(a,this._angularSpeedGradients,((e,t,i)=>{e!==n._currentAngularSpeedGradient&&(n._currentAngularSpeed1=n._currentAngularSpeed2,n._currentAngularSpeed2=t.getFactor(),n._currentAngularSpeedGradient=e),n.angularSpeed=Le.Lerp(n._currentAngularSpeed1,n._currentAngularSpeed2,i)})),n.angle+=n.angularSpeed*s;let l=s;if(this._velocityGradients&&this._velocityGradients.length>0&&gr.GetCurrentGradient(a,this._velocityGradients,((e,t,i)=>{e!==n._currentVelocityGradient&&(n._currentVelocity1=n._currentVelocity2,n._currentVelocity2=t.getFactor(),n._currentVelocityGradient=e),l*=Le.Lerp(n._currentVelocity1,n._currentVelocity2,i)})),n.direction.scaleToRef(l,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&gr.GetCurrentGradient(a,this._limitVelocityGradients,((e,t,i)=>{e!==n._currentLimitVelocityGradient&&(n._currentLimitVelocity1=n._currentLimitVelocity2,n._currentLimitVelocity2=t.getFactor(),n._currentLimitVelocityGradient=e);const s=Le.Lerp(n._currentLimitVelocity1,n._currentLimitVelocity2,i);n.direction.length()>s&&n.direction.scaleInPlace(this.limitVelocityDamping)})),this._dragGradients&&this._dragGradients.length>0&&gr.GetCurrentGradient(a,this._dragGradients,((e,t,i)=>{e!==n._currentDragGradient&&(n._currentDrag1=n._currentDrag2,n._currentDrag2=t.getFactor(),n._currentDragGradient=e);const s=Le.Lerp(n._currentDrag1,n._currentDrag2,i);this._scaledDirection.scaleInPlace(1-s)})),this.isLocal&&n._localPosition?(n._localPosition.addInPlace(this._scaledDirection),ze.TransformCoordinatesToRef(n._localPosition,this._emitterWorldMatrix,n.position)):n.position.addInPlace(this._scaledDirection),o&&i&&n._randomNoiseCoordinates1){const e=this._fetchR(n._randomNoiseCoordinates1.x,n._randomNoiseCoordinates1.y,i.width,i.height,o),t=this._fetchR(n._randomNoiseCoordinates1.z,n._randomNoiseCoordinates2.x,i.width,i.height,o),r=this._fetchR(n._randomNoiseCoordinates2.y,n._randomNoiseCoordinates2.z,i.width,i.height,o),a=Ke.Vector3[0],l=Ke.Vector3[1];a.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*t-1)*this.noiseStrength.y,(2*r-1)*this.noiseStrength.z),a.scaleToRef(s,l),n.direction.addInPlace(l)}this.gravity.scaleToRef(s,this._scaledGravity),n.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&gr.GetCurrentGradient(a,this._sizeGradients,((e,t,i)=>{e!==n._currentSizeGradient&&(n._currentSize1=n._currentSize2,n._currentSize2=t.getFactor(),n._currentSizeGradient=e),n.size=Le.Lerp(n._currentSize1,n._currentSize2,i)})),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&gr.GetCurrentGradient(a,this._colorRemapGradients,((e,t,i)=>{const s=Le.Lerp(e.factor1,t.factor1,i),r=Le.Lerp(e.factor2,t.factor2,i);n.remapData.x=s,n.remapData.y=r-s})),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&gr.GetCurrentGradient(a,this._alphaRemapGradients,((e,t,i)=>{const s=Le.Lerp(e.factor1,t.factor1,i),r=Le.Lerp(e.factor2,t.factor2,i);n.remapData.z=s,n.remapData.w=r-s}))),this._isAnimationSheetEnabled&&n.updateCellIndex(),n._inheritParticleInfoToSubEmitters(),n.age>=n.lifeTime&&(this._emitFromParticle(n),n._attachedSubEmitters&&(n._attachedSubEmitters.forEach((e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()})),n._attachedSubEmitters=null),this.recycleParticle(n),t--)}}}_addFactorGradient(e,t,i,n){const s=new mr(t,i,n);e.push(s),e.sort(((e,t)=>e.gradientt.gradient?1:0))}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const n of e){if(n.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;const e=new Uint8Array(4*this._rawTextureWidth),t=nt.Color3[0];for(let i=0;i{tt.LerpToRef(n.color,s.color,r,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255}))}this._rampGradientsTexture=Sr.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new pr(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);const n=new _r(e,t,i);return this._colorGradients.push(n),this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(const i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(const e of this._drawWrappers)if(e)for(const t of e)null==t||t.dispose();this._drawWrappers=[]}_fetchR(e,t,i,n,s){return s[4*(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*n%n|0)*i)]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&this.billboardMode!==Gr.BILLBOARDMODE_STRETCHED&&this.billboardMode!==Gr.BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);const e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new Ot(e,this._vertexData,!0,t);let i=0;const n=this._vertexBuffer.createVertexBuffer(Lt.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[Lt.PositionKind]=n,i+=3;const s=this._vertexBuffer.createVertexBuffer(Lt.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[Lt.ColorKind]=s,i+=4;const r=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=r,i+=1;const a=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=a,i+=2,this._isAnimationSheetEnabled){const e=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,i+=1}if(!this._isBillboardBased||this.billboardMode===Gr.BILLBOARDMODE_STRETCHED||this.billboardMode===Gr.BILLBOARDMODE_STRETCHED_LOCAL){const e=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,i+=3}if(this._useRampGradients){const e=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,i+=4}let o;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Ot(e,t,!1,2),o=this._spriteBuffer.createVertexBuffer("offset",0,2)}else o=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=o,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing)return;const e=[];let t=0;for(let i=0;i{e instanceof Gr?this._subEmitters.push([new kr(e)]):e instanceof kr?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)}))}start(e=this.startDelay){var t;if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e)setTimeout((()=>{this.start(0)}),e);else{if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=new Array),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){-1!==(null===(t=this.emitter)||void 0===t?void 0:t.getClassName().indexOf("Mesh"))&&this.emitter.computeWorldMatrix(!0);const e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce((()=>{setTimeout((()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,e&&this._stopSubEmitters())}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,n){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)this.billboardMode!==Gr.BILLBOARDMODE_STRETCHED&&this.billboardMode!==Gr.BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexData[s++]=t.direction.x,this._vertexData[s++]=t.direction.y,this._vertexData[s++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(ze.TransformNormalToRef(e,this._emitterWorldMatrix,Ke.Vector3[0]),e=Ke.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}else{let e=t.direction;this.isLocal&&(ze.TransformNormalToRef(e,this._emitterWorldMatrix,Ke.Vector3[0]),e=Ke.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[s++]=t.remapData.x,this._vertexData[s++]=t.remapData.y,this._vertexData[s++]=t.remapData.z,this._vertexData[s++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===n?n=this._epsilon:1===n&&(n=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=n)}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach((e=>{e.stop(!0)})),this.activeSubSystems=new Array)}_removeFromRoot(){if(!this._rootParticleSystem)return;const e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{const e=this.emitter;this._emitterWorldMatrix=Xe.Translation(e.x,e.y,e.z)}let t;this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){const e=Le.Clamp(this._actualFrame/this.targetStopDuration);gr.GetCurrentGradient(e,this._lifeTimeGradients,((i,n)=>{const s=i,r=n,a=s.getFactor(),o=r.getFactor(),l=(e-s.gradient)/(r.gradient-s.gradient);t.lifeTime=Le.Lerp(a,o,l)}))}else t.lifeTime=Le.RandomRange(this.minLifeTime,this.maxLifeTime);const e=Le.RandomRange(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),ze.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=Le.RandomRange(this.minSize,this.maxSize),t.scale.copyFromFloats(Le.RandomRange(this.minScaleX,this.maxScaleX),Le.RandomRange(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const e=this._actualFrame/this.targetStopDuration;gr.GetCurrentGradient(e,this._startSizeGradients,((e,i,n)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);const s=Le.Lerp(this._currentStartSize1,this._currentStartSize2,n);t.scale.scaleInPlace(s)}))}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=Le.RandomRange(this.minAngularSpeed,this.maxAngularSpeed),t.angle=Le.RandomRange(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),this._colorGradients&&0!==this._colorGradients.length)t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);else{const e=Le.RandomRange(0,1);it.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new He(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new ze(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new ze(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const n=[Lt.PositionKind,Lt.ColorKind,"angle","offset","size"];return e&&n.push("cellIndex"),t||n.push("direction"),i&&n.push("remapData"),n}static _GetEffectCreationOptions(e=!1,t=!1){const i=["invView","view","projection","textureMask","translationPivot","eyePosition"];return Bi(i),e&&i.push("particlesInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t){if(this._scene&&Ui(this,this._scene,e),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===Gr.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case Gr.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case Gr.BILLBOARDMODE_STRETCHED:case Gr.BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===Gr.BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case Gr.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...Gr._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==Gr.BILLBOARDMODE_STRETCHED&&this.billboardMode!==Gr.BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push(...Gr._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(St.PrepareUniforms(e,this._imageProcessingConfigurationDefines),St.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;const i=[];this.fillDefines(i,e);const n=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let s=this._drawWrappers[n];s||(s=this._drawWrappers[n]=[]);let r=s[e];r||(r=new $(this._engine),r.drawContext&&(r.drawContext.useInstancing=this._useInstancing),s[e]=r);const a=i.join("\n");if(r.defines!==a){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),r.setEffect(this._engine.createEffect("particles",e,t,i,a),a)}return r}animate(e=!1){var t;if(!this._started)return;if(!e&&this._scene){if(!this.isReady())return;if(this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}let i;if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this.manualEmitCount>-1)i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const t=this._actualFrame/this.targetStopDuration;gr.GetCurrentGradient(t,this._emitRateGradients,((t,i,n)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=Le.Lerp(this._currentEmitRate1,this._currentEmitRate2,n)}))}i=e*this._scaledUpdateSpeed>>0,this._newPartsExcess+=e*this._scaledUpdateSpeed-i}if(this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){let e=0;for(let t=0;t=0&&(a.invertToRef(Ke.Matrix[0]),s.setMatrix("invView",Ke.Matrix[0])),void 0!==this._vertexArrayObject?(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,this._indexBuffer,s)),this._engine.bindVertexArrayObject(this._vertexArrayObject,this._indexBuffer)):r.bindBuffers(this._vertexBuffers,this._indexBuffer,s),this.useLogarithmicDepth&&this._scene&&zi.BindLogDepth(o,s,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(s),e){case Gr.BLENDMODE_ADD:r.setAlphaMode(1);break;case Gr.BLENDMODE_ONEONE:r.setAlphaMode(6);break;case Gr.BLENDMODE_STANDARD:r.setAlphaMode(2);break;case Gr.BLENDMODE_MULTIPLY:r.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(s),this._useInstancing?r.drawArraysType(7,0,4,this._particles.length):r.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;const e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===Gr.BLENDMODE_MULTIPLYADD?this._render(Gr.BLENDMODE_MULTIPLY)+this._render(Gr.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}dispose(e=!0){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length){for(let e=0;e-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}clone(e,t,i=!1){const n={...this._customWrappers};let s=null;const r=this._engine;if(r.createEffectForParticles&&null!=this.customShader){s=this.customShader;const e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"",t=r.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e);n[0]?n[0].effect=t:this.setCustomEffect(t,0)}const a=this.serialize(i),o=Gr.Parse(a,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=n,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,this.preventAutoStart||o.start(),o}serialize(e=!1){const t={};if(Gr._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const n=[];for(const t of i)n.push(t.serialize(e));t.subEmitters.push(n)}}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){const i=t.emitter;e.emitterId=i.id}else{const i=t.emitter;e.emitter=i.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,gt.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;const n=t.getColorGradients();if(n){e.colorGradients=[];for(const t of n){const i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}}const s=t.getRampGradients();if(s){e.rampGradients=[];for(const t of s){const i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}const r=t.getColorRemapGradients();if(r){e.colorRemapGradients=[];for(const t of r){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}}const a=t.getAlphaRemapGradients();if(a){e.alphaRemapGradients=[];for(const t of a){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}}const o=t.getSizeGradients();if(o){e.sizeGradients=[];for(const t of o){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}}const l=t.getAngularSpeedGradients();if(l){e.angularSpeedGradients=[];for(const t of l){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}}const h=t.getVelocityGradients();if(h){e.velocityGradients=[];for(const t of h){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}}const c=t.getDragGradients();if(c){e.dragGradients=[];for(const t of c){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}}const d=t.getEmitRateGradients();if(d){e.emitRateGradients=[];for(const t of d){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}}const u=t.getStartSizeGradients();if(u){e.startSizeGradients=[];for(const t of u){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}}const f=t.getLifeTimeGradients();if(f){e.lifeTimeGradients=[];for(const t of f){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}}const _=t.getLimitVelocityGradients();if(_){e.limitVelocityGradients=[];for(const t of _){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}static _Parse(e,t,i,n){var s,r,a;let o;o=i instanceof ie?null:i;const l=Re("BABYLON.Texture");if(l&&o&&(e.texture?t.particleTexture=l.Parse(e.texture,o,n):e.textureName&&(t.particleTexture=new l(n+e.textureName,o,!1,void 0===e.invertY||e.invertY),t.particleTexture.name=e.textureName)),e.emitterId||0===e.emitterId||void 0!==e.emitter?e.emitterId&&o?t.emitter=o.getLastMeshById(e.emitterId):t.emitter=ze.FromArray(e.emitter):t.emitter=ze.Zero(),t.isLocal=!!e.isLocal,void 0!==e.renderingGroupId&&(t.renderingGroupId=e.renderingGroupId),void 0!==e.isBillboardBased&&(t.isBillboardBased=e.isBillboardBased),void 0!==e.billboardMode&&(t.billboardMode=e.billboardMode),void 0!==e.useLogarithmicDepth&&(t.useLogarithmicDepth=e.useLogarithmicDepth),e.animations){for(let i=0;i0?h.shaderOptions.defines.join("\n"):"";l=a.createEffectForParticles(h.shaderPath.fragmentElement,h.shaderOptions.uniforms,h.shaderOptions.samplers,t)}const c=new Gr(r,s||e.capacity,t,l,e.isAnimationSheetEnabled);if(c.customShader=h,c._rootUrl=i,e.id&&(c.id=e.id),e.subEmitters){c.subEmitters=[];for(const n of e.subEmitters){const e=[];for(const s of n)e.push(kr.Parse(s,t,i));c.subEmitters.push(e)}}return Gr._Parse(e,c,t,i),e.textureMask&&(c.textureMask=it.FromArray(e.textureMask)),e.preventAutoStart&&(c.preventAutoStart=e.preventAutoStart),n||c.preventAutoStart||c.start(),c}}Gr.BILLBOARDMODE_Y=2,Gr.BILLBOARDMODE_ALL=7,Gr.BILLBOARDMODE_STRETCHED=8,Gr.BILLBOARDMODE_STRETCHED_LOCAL=9,kr._ParseParticleSystem=Gr.Parse;class Vr{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=new Array,this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new s,this._onDataLayoutChanged=new s,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=gt.Clone((()=>new Vr(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())),gt.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new Vr(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;t0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new be(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!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 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 Hr.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}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)}clone(){const e=new Hr(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>=Hr.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 n=e.getPositions();if(n){const e=n.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void c.Error("Incompatible target. Targets must all have the same vertices count.")}}this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;ee&&(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 n=0;n-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 Hr(t);i._uniqueId=e.id;for(const n of e.targets)i.addTarget(Vr.Parse(n,t));return i}}Hr.EnableTextureStorage=!0,Hr.MaxActiveMorphTargetsInVertexAttributeMode=8;B.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";B.IncludesShadersStore.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";B.IncludesShadersStore.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";B.ShadersStore.kernelBlurPixelShader="uniform sampler2D textureSampler;\nuniform vec2 delta;\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nfloat sampleCoC(in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r;\nreturn coc; \n}\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";B.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";B.ShadersStore.kernelBlurVertexShader="attribute vec2 position;\nuniform vec2 delta;\nvarying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Wr extends kn{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,n,s,r=Ji.BILINEAR_SAMPLINGMODE,a,o,l=0,h="",c=!1,d=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],n,s,r,a,o,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,d),this._blockCompilation=c,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add((e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)})),this.kernel=i}updateEffect(e=null,t=null,i=null,n,s,r){this._updateParameters(s,r)}_updateParameters(e,t){const i=this._kernel,n=(i-1)/2;let s=[],r=[],a=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,n){return gt.Parse((()=>new Wr(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,n)}}Qe([ct("kernel")],Wr.prototype,"_kernel",void 0),Qe([ct("packedFloat")],Wr.prototype,"_packedFloat",void 0),Qe([_t()],Wr.prototype,"direction",void 0),Se("BABYLON.BlurPostProcess",Wr);B.IncludesShadersStore.bayerDitherFunctions="float bayerDither2(vec2 _P) {\nreturn mod(2.0*_P.y+_P.x+1.0,4.0);\n}\nfloat bayerDither4(vec2 _P) {\nvec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5*mod(_P,4.0)); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);\n}\nfloat bayerDither8(vec2 _P) {\nvec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5 *mod(_P,4.0)); \nvec2 P4=floor(0.25*mod(_P,8.0)); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);\n}\n";B.IncludesShadersStore.shadowMapFragmentExtraDeclaration="#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform float softTransparentShadowSM;\n#endif\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;\nvarying vec3 vPositionWSM;\n#endif\nuniform vec3 biasAndScaleSM;\nuniform vec2 depthValuesSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";B.IncludesShadersStore.shadowMapFragment="float depthSM=vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depthSM);\n#endif\nreturn;";B.ShadersStore.shadowMapPixelShader="#include\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEXTURE\nfloat alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard;\n#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;\n#endif\n#endif\n#include\n}";B.IncludesShadersStore.sceneVertexDeclaration="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec4 vEyePosition;\n";B.IncludesShadersStore.meshVertexDeclaration="uniform mat4 world;\nuniform float visibility;\n";B.IncludesShadersStore.shadowMapVertexDeclaration="#include\n#include\n";B.IncludesShadersStore.shadowMapUboDeclaration="layout(std140,column_major) uniform;\n#include\n#include\n";B.IncludesShadersStore.shadowMapVertexExtraDeclaration="#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\n#endif\nuniform vec3 biasAndScaleSM;\nuniform vec2 depthValuesSM;\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";B.IncludesShadersStore.shadowMapVertexNormalBias="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\n#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;\nvec3 worldLightDirSM=normalize(directionToLightSM);\n#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);\nfloat sinNLSM=sqrt(1.0-ndlSM*ndlSM);\nfloat normalBiasSM=biasAndScaleSM.y*sinNLSM;\nworldPos.xyz-=vNormalW*normalBiasSM;\n#endif\n";B.IncludesShadersStore.shadowMapVertexMetric="#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;\ngl_Position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n";B.ShadersStore.shadowMapVertexShader="attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#endif\n#include\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));\nvNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include\ngl_Position=viewProjection*worldPos;\n#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}";B.ShadersStore.depthBoxBlurPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}";B.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;\n#endif\n";class Xr{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===Xr.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(e===Xr.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(e===Xr.FILTER_PCF||e===Xr.FILTER_PCSS)return void(this.usePoissonSampling=!0)}e!==Xr.FILTER_PCF&&e!==Xr.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0}get usePoissonSampling(){return this.filter===Xr.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(Xr.FILTER_POISSONSAMPLING);(e||this.filter===Xr.FILTER_POISSONSAMPLING)&&(this.filter=e?t:Xr.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===Xr.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(Xr.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===Xr.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:Xr.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===Xr.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(Xr.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===Xr.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:Xr.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===Xr.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(Xr.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===Xr.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:Xr.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===Xr.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(Xr.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===Xr.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:Xr.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===Xr.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(Xr.FILTER_PCF);(e||this.filter===Xr.FILTER_PCF)&&(this.filter=e?t:Xr.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===Xr.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(Xr.FILTER_PCSS);(e||this.filter===Xr.FILTER_PCSS)&&(this.filter=e?t:Xr.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return this._darkness=e>=1?1:e<=0?0:e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return Xr.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(const t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(const t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}_getCamera(){var e;return null!==(e=this._camera)&&void 0!==e?e:this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,n){this.onBeforeShadowMapRenderObservable=new s,this.onAfterShadowMapRenderObservable=new s,this.onBeforeShadowMapRenderMeshObservable=new s,this.onAfterShadowMapRenderMeshObservable=new s,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=Xr.FILTER_NONE,this._filteringQuality=Xr.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=ze.Zero(),this._viewMatrix=Xe.Zero(),this._projectionMatrix=Xe.Zero(),this._transformMatrix=Xe.Zero(),this._cachedPosition=new ze(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new ze(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=Xe.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=null!=n?n:null;let r=t._shadowGenerators;r||(r=t._shadowGenerators=new Map),r.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),Xr._SceneComponentInitialization(this._scene);const a=this._scene.getEngine().getCaps();i?a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new Un(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)):this._shadowMap=new Un(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube())}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=Ji.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=Ji.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(Ji.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=this._renderForShadowMap.bind(this),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),null===(t=e._debugPushGroup)||void 0===t||t.call(e,`shadow map generation for pass id ${e.currentRenderPassId}`,1)})),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===Xr.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onAfterUnbindObservable.add((()=>{var t,i;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===Xr.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap)return void(null===(t=e._debugPopGroup)||void 0===t||t.call(e,1));const n=this.getShadowMapForRendering();n&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,n.renderTarget,!0),e.unBindFramebuffer(n.renderTarget,!0),null===(i=e._debugPopGroup)||void 0===i||i.call(e,1))}));const t=new it(0,0,0,0),i=new it(1,1,1,1);this._shadowMap.onClearObservable.add((e=>{this._filter===Xr.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}));for(let e=kt.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)})),this._kernelBlurYPostprocess=new Wr(this._light.name+"KernelBlurY",new Ve(0,1),this.blurKernel,1,null,Ji.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new kn(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,Ji.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,n){let s;if(n.length)for(s=0;s{r===s||e?(r.getMeshUniformBuffer().bindToEffect(c,"Mesh"),r.transferToEffect(e?t:_)):(s.getMeshUniformBuffer().bindToEffect(c,"Mesh"),s.transferToEffect(t))})),this.forceBackFacesOnly&&o.setState(!0,0,!1,!1,l.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(c),this.onAfterShadowMapRenderMeshObservable.notifyObservers(s)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===Xr.FILTER_NONE||this.filter===Xr.FILTER_PCSS?this._shadowMap.updateSamplingMode(Ji.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(Ji.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},n=this.getShadowMap();if(!n)return void(e&&e(this));const s=n.renderList;if(!s)return void(e&&e(this));const r=new Array;for(const e of s)r.push(...e.subMeshes);if(0===r.length)return void(e&&e(this));let a=0;const o=()=>{var t,n;if(this._scene&&this._scene.getEngine()){for(;this.isReady(r[a],i.useInstances,null!==(n=null===(t=r[a].getMaterial())||void 0===t?void 0:t.needAlphaBlendingForMesh(r[a].getMesh()))&&void 0!==n&&n);)if(a++,a>=r.length)return void(e&&e(this));setTimeout(o,16)}};o()}forceCompilationAsync(e){return new Promise((t=>{this.forceCompilation((()=>{t()}),e)}))}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,n){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(Lt.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Ti.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&n?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var n;const s=e.getMaterial(),r=null==s?void 0:s.shadowDepthWrapper;if(!s)return!1;const a=[];if(this._prepareShadowDefines(e,t,a,i),r){if(!r.isReadyForSubMesh(e,a,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const i=e._getDrawWrapper(void 0,!0);let r=i.effect,o=i.defines;const l=[Lt.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent(Lt.NormalKind)&&(l.push(Lt.NormalKind),a.push("#define NORMAL"),h.nonUniformScaling&&a.push("#define NONUNIFORMSCALING"));const c=null==s?void 0:s.needAlphaTesting(),d=null==s?void 0:s.needAlphaBlending();if(s&&(c||d)){let e=null;if(e=this.useOpacityTextureForTransparentShadow?s.opacityTexture:s.getAlphaTestTexture(),e){if(!e.isReady())return!1;const t=null!==(n=s.alphaCutOff)&&void 0!==n?n:Xr.DEFAULT_ALPHA_CUTOFF;a.push("#define ALPHATEXTURE"),c&&a.push(`#define ALPHATESTVALUE ${t}${t%1==0?".":""}`),h.isVerticesDataPresent(Lt.UVKind)&&(l.push(Lt.UVKind),a.push("#define UV1")),h.isVerticesDataPresent(Lt.UV2Kind)&&1===e.coordinatesIndex&&(l.push(Lt.UV2Kind),a.push("#define UV2"))}}const u=new sn;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){l.push(Lt.MatricesIndicesKind),l.push(Lt.MatricesWeightsKind),h.numBoneInfluencers>4&&(l.push(Lt.MatricesIndicesExtraKind),l.push(Lt.MatricesWeightsExtraKind));const e=h.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+h.numBoneInfluencers),h.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,h),e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");const f=h.morphTargetManager;let _=0;if(f&&f.numInfluencers>0&&(a.push("#define MORPHTARGETS"),_=f.numInfluencers,a.push("#define NUM_MORPH_INFLUENCERS "+_),f.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),zi.PrepareAttributesForMorphTargetsInfluencers(l,h,_)),Ui(s,this._scene,a),t&&(a.push("#define INSTANCES"),zi.PushAttributesForInstances(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const e of this.customShaderOptions.defines)-1===a.indexOf(e)&&a.push(e);const p=a.join("\n");if(o!==p){o=p;let e="shadowMap";const t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],n=["diffuseSampler","boneSampler","morphTargets"],s=["Scene","Mesh"];if(Bi(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const e of this.customShaderOptions.attributes)-1===l.indexOf(e)&&l.push(e);if(this.customShaderOptions.uniforms)for(const e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(const e of this.customShaderOptions.samplers)-1===n.indexOf(e)&&n.push(e)}const a=this._scene.getEngine();r=a.createEffect(e,{attributes:l,uniformsNames:t,uniformBuffersNames:s,samplers:n,defines:p,fallbacks:u,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:_}},a),i.setEffect(r,o)}if(!r.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,n=this._light;i.shadowsEnabled&&n.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===Xr.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Xr.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===Xr.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Xr.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),n.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const n=this._getCamera();if(!n)return;const s=this.getShadowMap();s&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===Xr.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),s.getSize().width,1/s.getSize().width,this.frustumEdgeFalloff,e)):this._filter===Xr.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/s.getSize().width,this._contactHardeningLightSizeUVRatio*s.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/s.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(n),this.getLight().getDepthMinZ(n)+this.getLight().getDepthMaxZ(n),e))}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),ze.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(ze.Dot(this._lightDirection,ze.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),Xe.LookAtLHToRef(t,t.add(this._lightDirection),ze.Up(),this._viewMatrix);const e=this.getShadowMap();if(e){const t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const e of t)this._shadowMap.renderList.push(e)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){var e;const t={},i=this.getShadowMap();if(!i)return t;if(t.className=this.getClassName(),t.lightId=this._light.id,t.cameraId=null===(e=this._camera)||void 0===e?void 0:e.id,t.id=this.id,t.mapSize=i.getRenderSize(),t.forceBackFacesOnly=this.forceBackFacesOnly,t.darkness=this.getDarkness(),t.transparencyShadow=this._transparencyShadow,t.frustumEdgeFalloff=this.frustumEdgeFalloff,t.bias=this.bias,t.normalBias=this.normalBias,t.usePercentageCloserFiltering=this.usePercentageCloserFiltering,t.useContactHardeningShadow=this.useContactHardeningShadow,t.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,t.filteringQuality=this.filteringQuality,t.useExponentialShadowMap=this.useExponentialShadowMap,t.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,t.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.usePoissonSampling=this.usePoissonSampling,t.depthScale=this.depthScale,t.blurBoxOffset=this.blurBoxOffset,t.blurKernel=this.blurKernel,t.blurScale=this.blurScale,t.useKernelBlur=this.useKernelBlur,t.renderList=[],i.renderList)for(let e=0;e{throw _("ShadowGeneratorSceneComponent")},function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(Yr||(Yr={})),function(e){e[e.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",e[e.BC7_RGBA=1]="BC7_RGBA",e[e.BC3_RGBA=2]="BC3_RGBA",e[e.BC1_RGB=3]="BC1_RGB",e[e.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",e[e.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",e[e.ETC2_RGBA=6]="ETC2_RGBA",e[e.ETC1_RGB=7]="ETC1_RGB",e[e.RGBA32=8]="RGBA32",e[e.R8=9]="R8",e[e.RG8=10]="RG8"}(Kr||(Kr={})),function(e){e[e.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",e[e.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",e[e.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",e[e.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",e[e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",e[e.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",e[e.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",e[e.RGBA8Format=32856]="RGBA8Format",e[e.R8Format=33321]="R8Format",e[e.RG8Format=33323]="RG8Format"}(jr||(jr={}));class $r{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if($r._WorkerPoolPromise||$r._DecoderModulePromise)return;const t={jsDecoderModule:Me.GetAbsoluteUrl(this.URLConfig.jsDecoderModule),wasmUASTCToASTC:Zr(this.URLConfig.wasmUASTCToASTC),wasmUASTCToBC7:Zr(this.URLConfig.wasmUASTCToBC7),wasmUASTCToRGBA_UNORM:Zr(this.URLConfig.wasmUASTCToRGBA_UNORM),wasmUASTCToRGBA_SRGB:Zr(this.URLConfig.wasmUASTCToRGBA_SRGB),wasmUASTCToR8_UNORM:Zr(this.URLConfig.wasmUASTCToR8_UNORM),wasmUASTCToRG8_UNORM:Zr(this.URLConfig.wasmUASTCToRG8_UNORM),jsMSCTranscoder:Zr(this.URLConfig.jsMSCTranscoder),wasmMSCTranscoder:Zr(this.URLConfig.wasmMSCTranscoder),wasmZSTDDecoder:Zr(this.URLConfig.wasmZSTDDecoder)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?$r._WorkerPoolPromise=new Promise((i=>{const n=`${Jr}(${ea})()`,s=URL.createObjectURL(new Blob([n],{type:"application/javascript"}));i(new sr(e,(()=>new Promise(((e,i)=>{const n=new Worker(s),r=e=>{n.removeEventListener("error",r),n.removeEventListener("message",a),i(e)},a=t=>{"init"===t.data.action&&(n.removeEventListener("error",r),n.removeEventListener("message",a),e(n))};n.addEventListener("error",r),n.addEventListener("message",a),n.postMessage({action:"init",urls:t})})))))})):"undefined"==typeof KTX2DECODER?$r._DecoderModulePromise=Me.LoadScriptAsync(t.jsDecoderModule).then((()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,Jr(t),new KTX2DECODER.KTX2Decoder))):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,$r._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}constructor(e,t=$r.DefaultNumWorkers){this._engine=e,$r._Initialize(t)}uploadAsync(e,t,i){const n=this._engine.getCaps(),s={astc:!!n.astc,bptc:!!n.bptc,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,etc1:!!n.etc1};if($r._WorkerPoolPromise)return $r._WorkerPoolPromise.then((n=>new Promise(((r,a)=>{n.push(((n,o)=>{const l=e=>{n.removeEventListener("error",l),n.removeEventListener("message",h),a(e),o()},h=e=>{if("decoded"===e.data.action){if(n.removeEventListener("error",l),n.removeEventListener("message",h),e.data.success)try{this._createTexture(e.data.decodedData,t,i),r()}catch(e){a({message:e})}else a({message:e.data.msg});o()}};n.addEventListener("error",l),n.addEventListener("message",h),n.postMessage({action:"setDefaultDecoderOptions",options:$r.DefaultDecoderOptions._getKTX2DecoderOptions()});const c=new Uint8Array(e.byteLength);c.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),n.postMessage({action:"decode",data:c,caps:s,options:i},[c.buffer])}))}))));if($r._DecoderModulePromise)return $r._DecoderModulePromise.then((i=>($r.DefaultDecoderOptions.isDirty&&(KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=$r.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise(((s,r)=>{i.decode(e,n).then((e=>{this._createTexture(e,t),s()})).catch((e=>{r({message:e})}))})))));throw new Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let n=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,n=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}function ea(){let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{const i=t.data.urls;importScripts(i.jsDecoderModule),Jr(i),e=new KTX2DECODER.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=t.data.options;break;case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then((e=>{const t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})}))}}}$r.URLConfig={jsDecoderModule:"https://preview.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},$r.DefaultNumWorkers=$r.GetDefaultNumWorkers(),$r.DefaultDecoderOptions=new class{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;const e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[Kr.BC1_RGB,Kr.BC3_RGBA],yes:{transcodeFormat:Kr.RGBA32,engineFormat:jr.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}},function(e){class t{serialize(){const e={},t=new Array(this._characterToIdx.size);return this._characterToIdx.forEach(((e,i)=>{t[e]=i})),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){const i=JSON.parse(e),n=new t(i.characters);return n._insertionCosts=i.insertionCosts,n._deletionCosts=i.deletionCosts,n._substitutionCosts=i.substitutionCosts,n}constructor(e,t=null,i=null,n=null){let s;t=null!=t?t:()=>1,i=null!=i?i:()=>1,n=null!=n?n:(e,t)=>e===t?0:1,this._characterToIdx=new Map,this._insertionCosts=new Array(e.length),this._deletionCosts=new Array(e.length),this._substitutionCosts=new Array(e.length);for(let r=0;ri._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+i._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map((e=>this._alphabet.getCharacterIdx(e)))}distance(e){return i._Distance(this,e)}static _Distance(e,t){const n=e._alphabet;if(n!==t._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const s=e._characters,r=t._characters,a=s.length,o=r.length,l=i._CostMatrix;l[0][0]=0;for(let e=0;enew Array(i._MAX_SEQUENCE_LENGTH+1))),e.Sequence=i}(qr||(qr={}));class ta{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new ta(t._segmentLength);return i._points=t._points.map((e=>new ze(e._x,e._y,e._z))),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{const i=()=>this._segmentLength/ze.Distance(this._points[t-1],e);for(let n=i();n<=1;n=i()){const i=this._points[t-1].scale(1-n);e.scaleAndAddToRef(n,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){const t=new ta(this.getLength()/e);return this._points.forEach((e=>{t.add(e)})),t}tokenize(e){const t=[],i=new ze;for(let n=2;n.98||(ze.CrossToRef(ta._ForwardDir,ta._InverseFromVec,ta._UpDir),ta._UpDir.normalize(),Xe.LookAtLHToRef(e,t,ta._UpDir,ta._LookMatrix),i.subtractToRef(t,ta._FromToVec),ta._FromToVec.normalize(),ze.TransformNormalToRef(ta._FromToVec,ta._LookMatrix,n),0))}static _TokenizeSegment(e,t){ta._BestMatch=0,ta._Score=ze.Dot(e,t[0]),ta._BestScore=ta._Score;for(let i=1;ita._BestScore&&(ta._BestMatch=i,ta._BestScore=ta._Score);return ta._BestMatch}}ta._ForwardDir=new ze,ta._InverseFromVec=new ze,ta._UpDir=new ze,ta._FromToVec=new ze,ta._LookMatrix=new Xe;class ia{serialize(){return JSON.stringify(this._sequences.map((e=>e.serialize())))}static Deserialize(e,t){const i=new ia;return i._sequences=JSON.parse(e).map((e=>qr.Sequence.Deserialize(e,t))),i}static CreateFromTrajectory(e,t,i){return ia.CreateFromTokenizationPyramid(ia._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new ia;return i._sequences=e.map((e=>new qr.Sequence(e,t))),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=ia._FINEST_DESCRIPTOR_RESOLUTION){const n=[];for(let s=i;s>4;s=Math.floor(s/2))n.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return n}distance(e){let t,i=0;for(let n=0;ne.serialize())),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),n=new na;return n._descriptors=i.descriptors.map((e=>ia.Deserialize(e,t))),n._centroidIdx=i.centroidIdx,n._averageDistance=i.averageDistance,n}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map((t=>t.distance(e))))}_refreshDescription(){let e;this._centroidIdx=-1;const t=this._descriptors.map((t=>(e=0,this._descriptors.forEach((i=>{e+=t.distance(i)})),e)));for(let e=0;e{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])})),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,na._MIN_AVERAGE_DISTANCE))}}na._MIN_AVERAGE_DISTANCE=1,function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(Qr||(Qr={}));class sa{constructor(e,t,i){this._scene=e,c.Log(`[Reflector] Connecting to ws://${t}:${i}`),this._webSocket=new WebSocket(`ws://${t}:${i}`),this._webSocket.onmessage=e=>{const t=e.data;if(t.startsWith(sa._SERVER_PREFIX)){const e=t.substr(sa._SERVER_PREFIX.length);return c.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),void this._handleServerMessage(e)}c.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{c.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&$s.SerializeAsync(this._scene).then((e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)}))}_handleClientMessage(){}}sa._SERVER_PREFIX="$$";class ra{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){const e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}const aa=1800,oa="timestamp",la="numPoints",ha=/\r/g;class ca{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const e=f.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength;let n=0;if(i>0){const e=this.datasets.startingIndices.at(i-1);n=e+this.datasets.data.at(e+ca.NumberOfPointsOffset)+ca.SliceDataOffset}if(this.datasets.startingIndices.push(n),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach((e=>{const t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())})),this.datasetObservable.hasObservers()){const i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new i(0)))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var n;if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&(null===(n=this._strategies.get(e))||void 0===n||n.dispose(),this._strategies.delete(e));const s={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,n=0;const s=t.onAfterRenderObservable.add((()=>{n=i,i=0})),r=this._customEventObservable.add((t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)}));return{id:e,getData:()=>n,dispose:()=>{t.onAfterRenderObservable.remove(s),this._customEventObservable.remove(r)}}},category:i}),s}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach((e=>{this.registerEvent(e,!0)}))}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:n}of e){const e=t(this._scene);this._strategies.has(e.id)?e.dispose():(this.datasets.ids.push(e.id),i&&(i=i.replace(new RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:n}),this._strategies.set(e.id,e))}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i>e&255).toString(16)).substr(-2);return i}getCurrentSlice(){const e=[f.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach((t=>{const i=this._strategies.get(t);i&&this.datasetObservable.hasObservers()&&e.push(i.getData())})),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(e)}updateMetadata(e,t,i){const n=this._datasetMeta.get(e);n&&(n[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new ra(aa),this.datasets.ids.length=0,this.datasets.startingIndices=new ra(aa),this._datasetMeta.clear(),this._strategies.forEach((e=>e.dispose())),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(ha,"").split("\n").map((e=>e.split(",").filter((e=>e.length>0)))).filter((e=>e.length>0)),n=ca.NumberOfPointsOffset;if(i.length<2)return!1;const s={ids:[],data:new ra(aa),startingIndices:new ra(aa)},[r,...a]=i;if(r.length<2||r[0]!==oa||r[n]!==la)return!1;const o=new Map;for(let e=ca.SliceDataOffset;ee.dispose())),this._strategies.clear(),!t)for(const e of this.datasets.ids){const t=o.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${oa},${la}`;for(let t=0;t{e.dispose()})),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}pi.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new ca(this)),this._perfCollector},s.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){const e=function(e){const t=new Array,i=new Array,n=new Array,s=e.add((()=>{const e=t.length;for(let s=0;s{t.push(e),i.push(s),n.push(r)},dispose:()=>{e.remove(s)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return Ls(e,this._coroutineScheduler)},s.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};var da;B.ShadersStore.copyTextureToTexturePixelShader="uniform float conversion;\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#include\nvoid main(void) \n{\nvec4 color=texture2D(textureSampler,vUV);\n#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\n#else\nif (conversion==1.) {\ncolor=toLinearSpace(color);\n} else if (conversion==2.) {\ncolor=toGammaSpace(color);\n}\ngl_FragColor=color;\n#endif\n}\n",function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(da||(da={}));class ua extends wi{constructor(e,t,i,n=!0){super(e,t,i,n),this._tmpUpVector=ze.Zero(),this._tmpTargetVector=ze.Zero(),this.cameraDirection=new ze(0,0,0),this.cameraRotation=new Ve(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new We,this.rotation=new ze(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=ze.Zero(),this._initialFocalDistance=1,this._viewMatrix=Xe.Zero(),this._camMatrix=Xe.Zero(),this._cameraTransformMatrix=Xe.Zero(),this._cameraRotationMatrix=Xe.Zero(),this._referencePoint=new ze(0,0,1),this._transformedReferencePoint=ze.Zero(),this._defaultUp=ze.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 ze(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new ze(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new We(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+=we),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),Xe.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&&We.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(Ke.Matrix[0]),ze.TransformNormalToRef(this.cameraDirection,Ke.Matrix[0],Ke.Vector3[0]),void this.position.addInPlace(Ke.Vector3[0]);this.position.addInPlace(this.cameraDirection)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this.rotation),this.rotation.x+=this.cameraRotation.x*e,this.rotation.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this.rotation.x>e&&(this.rotation.x=e),this.rotation.x<-e&&(this.rotation.x=-e)}this.rotationQuaternion&&this.rotation.lengthSquared()&&We.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}t&&(Math.abs(this.cameraDirection.x){}}add(e){const t=e.getSimpleName();this.attached[t]?c.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=!wi.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],n=gt.Serialize(i);t[i.getClassName()]=n}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=_a[e];if(i){const n=t[e],s=gt.Parse((()=>new i),n,null);this.add(s)}}}else for(const t in this.attached){const i=_a[this.attached[t].getClassName()];if(i){const n=gt.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(n)}}}}class ma{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=Me.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===Kt.KEYDOWN)-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{const s=n.event,r="touch"===s.pointerType;if(t.isInVRExclusivePointerMode)return;if(!this.touchEnabled&&r)return;if(n.type!==zt.POINTERMOVE&&-1===this.buttons.indexOf(s.button))return;const a=s.target;if(n.type===zt.POINTERDOWN){if(r&&-1!==this._activePointerId||!r&&-1!==this._currentActiveButton)return;this._activePointerId=s.pointerId;try{null==a||a.setPointerCapture(s.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},e||(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(n.event)}else if(n.type===zt.POINTERUP){if(r&&this._activePointerId!==s.pointerId||!r&&this._currentActiveButton!==s.button)return;try{null==a||a.releasePointerCapture(s.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(n.type===zt.POINTERMOVE&&(this._activePointerId===s.pointerId||!r))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(n.event);else if(this._previousPosition){let t=s.clientX-this._previousPosition.x;const i=s.clientY-this._previousPosition.y;this.camera.getScene().useRightHandedSystem&&(t*=-1),this.camera.parent&&this.camera.parent._getWorldMatrixDeterminant()<0&&(t*=-1),this._allowCameraRotation&&(this.camera.cameraRotation.y+=t/this.angularSensibility,this.camera.cameraRotation.x+=i/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:t,offsetY:i}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;if(t.isInVRExclusivePointerMode)return;let n=i.movementX;this.camera.getScene().useRightHandedSystem&&(n*=-1),this.camera.parent&&this.camera.parent._getWorldMatrixDeterminant()<0&&(n*=-1),this.camera.cameraRotation.y+=n/this.angularSensibility;const s=i.movementY;this.camera.cameraRotation.x+=s/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,zt.POINTERDOWN|zt.POINTERUP|zt.POINTERMOVE),i&&(this._contextMenuBind=this.onContextMenu.bind(this),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._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}Qe([ct()],ga.prototype,"buttons",void 0),Qe([ct()],ga.prototype,"angularSensibility",void 0),_a.FreeCameraMouseInput=ga;class Ea{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new s,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=Me.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==zt.POINTERWHEEL)return;const i=t.event,n=i.deltaMode===Qt.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*n*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*n*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*n*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,zt.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"}}Qe([ct()],Ea.prototype,"wheelPrecisionX",void 0),Qe([ct()],Ea.prototype,"wheelPrecisionY",void 0),Qe([ct()],Ea.prototype,"wheelPrecisionZ",void 0),function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(fa||(fa={}));class Ta extends Ea{constructor(){super(...arguments),this._moveRelative=ze.Zero(),this._rotateRelative=ze.Zero(),this._moveScene=ze.Zero(),this._wheelXAction=fa.MoveRelative,this._wheelXActionCoordinate=fi.X,this._wheelYAction=fa.MoveRelative,this._wheelYActionCoordinate=fi.Z,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=Xe.Zero();this.camera.getViewMatrix().invertToRef(e);const t=ze.Zero();ze.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 n=null;switch(t){case fa.MoveRelative:n=this._moveRelative;break;case fa.RotateRelative:n=this._rotateRelative;break;case fa.MoveScene:n=this._moveScene}switch(i){case fi.X:n.set(e,0,0);break;case fi.Y:n.set(0,e,0);break;case fi.Z:n.set(0,0,e)}}}Qe([ct()],Ta.prototype,"wheelXMoveRelative",null),Qe([ct()],Ta.prototype,"wheelYMoveRelative",null),Qe([ct()],Ta.prototype,"wheelZMoveRelative",null),Qe([ct()],Ta.prototype,"wheelXRotateRelative",null),Qe([ct()],Ta.prototype,"wheelYRotateRelative",null),Qe([ct()],Ta.prototype,"wheelZRotateRelative",null),Qe([ct()],Ta.prototype,"wheelXMoveScene",null),Qe([ct()],Ta.prototype,"wheelYMoveScene",null),Qe([ct()],Ta.prototype,"wheelZMoveScene",null),_a.FreeCameraMouseWheelInput=Ta;class Aa{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=Me.IsSafari()}attachControl(e){e=Me.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const n=i.event,s="mouse"===n.pointerType||this._isSafari&&void 0===n.pointerType;if(this.allowMouse||!s)if(i.type===zt.POINTERDOWN){if(e||n.preventDefault(),this._pointerPressed.push(n.pointerId),1!==this._pointerPressed.length)return;t={x:n.clientX,y:n.clientY}}else if(i.type===zt.POINTERUP){e||n.preventDefault();const i=this._pointerPressed.indexOf(n.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===zt.POINTERMOVE){if(e||n.preventDefault(),!t)return;if(0!=this._pointerPressed.indexOf(n.pointerId))return;this._offsetX=n.clientX-t.x,this._offsetY=-(n.clientY-t.y)}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,zt.POINTERDOWN|zt.POINTERUP|zt.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;if(e.cameraRotation.y=this._offsetX/this.touchAngularSensibility,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 ze(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);Xe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(ze.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}Qe([ct()],Aa.prototype,"touchAngularSensibility",void 0),Qe([ct()],Aa.prototype,"touchMoveSensibility",void 0),_a.FreeCameraTouchInput=Aa;class va extends pa{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new ma),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new ga(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new Ta,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new Aa),this}clear(){super.clear(),this._mouseInput=null}}class Sa extends ua{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,n=!0){super(e,t,i,n),this.ellipsoid=new ze(.5,1,.5),this.ellipsoidOffset=new ze(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=ze.Zero(),this._diffPosition=ze.Zero(),this._newPosition=ze.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>tn.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new va(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Me.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new ze(0,0,0),this.cameraRotation=new Ve(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?ze.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 n=e;this.applyGravity&&(n=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,n,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=ze.Zero(),this._transformedDirection=ze.Zero()),this.inputs.checkInputs(),super._checkInputs()}_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"}}function Ra(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],n=[];let s=[];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 d=[2,0,3,1][h],u=[2,0,1,3][c],f=[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],f=[-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 n=[17,18,19,16],s=[22,23,20,21];for(;d>0;)e.unshift(e.pop()),n.unshift(n.pop()),d--;for(;u>0;)i.unshift(i.pop()),s.unshift(s.pop()),u--;e=e.flat(),i=i.flat(),f=f.concat(e).concat(i),t.push(n[0],n[2],n[3],n[0],n[1],n[2]),t.push(s[0],s[2],s[3],s[0],s[1],s[2])}const _=[r/2,a/2,o/2];s=f.reduce(((e,t,i)=>e.concat(t*_[i%3])),[]);const p=0===e.sideOrientation?0:e.sideOrientation||Ns.DEFAULTSIDE,m=e.faceUV||new Array(6),g=e.faceColors,E=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new He(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new it(1,1,1,1));for(let e=0;e<6;e++)if(n.push(m[e].z,Zi.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),n.push(m[e].x,Zi.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),n.push(m[e].x,Zi.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),n.push(m[e].z,Zi.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)E.push(g[e].r,g[e].g,g[e].b,g[e].a);Ns._ComputeSides(p,s,t,i,n,e.frontUVs,e.backUVs);const T=new Ns;if(T.indices=t,T.positions=s,T.normals=i,T.uvs=n,g){const e=p===Ns.DOUBLESIDE?E.concat(E):E;T.colors=e}return T}function Ca(e,t={},i=null){const n=new Ks(e,i);return t.sideOrientation=Ks._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,Ra(t).applyToMesh(n,t.updatable),n}Qe([pt()],Sa.prototype,"ellipsoid",void 0),Qe([pt()],Sa.prototype,"ellipsoidOffset",void 0),Qe([ct()],Sa.prototype,"checkCollisions",void 0),Qe([ct()],Sa.prototype,"applyGravity",void 0),Ns.CreateBox=Ra,Ks.CreateBox=(e,t,i=null,n,s)=>Ca(e,{size:t,sideOrientation:s,updatable:n},i);const xa=function(e,t,i){e.name="test",e.debugLayer.show();const n=new Sa("camera_player_pov",new ze(0,.75,0),e);n.minZ=.1,n.setTarget(new ze(0,0,-.5)),e.activeCamera.attachControl(t.canvas,!0),new Ai("light",new ze(-30,30,30),e).intensity=1;var s=new un("material",e);const r=new hs(e);r.addMeshTask("ground task","","/asset/model/","demo-ground.glb").onSuccess=function(e){const t=e.loadedMeshes[0];t.position=new ze(0,0,0),t.material=s},r.load();const a=Ca("marker1",{size:.1},e);a.position=new ze(0,.05,0),a.material=s;const o=Ca("marker2",{size:.1},e);o.position=new ze(0,.05,-.1),o.material=s;const l=Ca("marker3",{size:.1},e);l.position=new ze(0,.05,-.5),l.material=s,e.update=function(e){}};class Ma{constructor(){this._scenes={},this.set("test",mi.CreateScene(xa));for(const e of this)e.registerBeforeRender((function(t){e.update(t)}))}get(e){if(!(e in this._scenes))throw"Missing scene: "+e;return this._scenes[e]}set(e,t){this._scenes[e]=t}*[Symbol.iterator](){for(const e of Object.keys(this._scenes))yield this._scenes[e]}}Ks._instancedMeshFactory=(e,t)=>{const i=new Ia(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class Ia extends Gs{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}get material(){return this._sourceMesh.material}get visibility(){return this._sourceMesh.visibility}get skeleton(){return this._sourceMesh.skeleton}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){this._sourceMesh&&e!==this._sourceMesh.renderingGroupId&&c.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){return this._sourceMesh.getVerticesData(e,t)}setVerticesData(e,t,i,n){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,n),this.sourceMesh}updateVerticesData(e,t,i,n){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,n),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;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||c.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!==ws.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new Xe);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,Ke.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(Ke.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{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 Pa extends qe{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 n of e){const e=n.uniqueId,s=i.dependsOn.get(e);if(n instanceof Ia){const r=n.sourceMesh;t.has(r.uniqueId)&&(s.add(r.uniqueId),i.dependedBy.get(r.uniqueId).add(e))}const r=i.dependedBy.get(e);for(const s of n.getDescendants()){const n=s.uniqueId;t.has(n)&&(r.add(n),i.dependsOn.get(n).add(e))}}const n=[],s=[];for(const n of e){const e=n.uniqueId;0===i.dependsOn.get(e).size&&(s.push(n),t.delete(e))}const r=s;for(;r.length>0;){const e=r.shift();n.push(e);const s=i.dependedBy.get(e.uniqueId);for(const n of Array.from(s.values())){const s=i.dependsOn.get(n);s.delete(e.uniqueId),0===s.size&&t.get(n)&&(r.push(t.get(n)),t.delete(n))}}return t.size>0&&(console.error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>console.error(e.name)))),n}_addNodeAndDescendantsToList(e,t,i,n){if(i&&(!n||n(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(const s of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,s,n)}}_isNodeInContainer(e){return e instanceof Ks&&-1!==this.meshes.indexOf(e)||e instanceof ws&&-1!==this.transformNodes.indexOf(e)||e instanceof Ti&&-1!==this.lights.indexOf(e)||e instanceof wi&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return c.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 c.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 c.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 c.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Me.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const n={},s={},r=new ya,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 d=this._topologicalSort(h),u=(i,a)=>{if(((t,i)=>{if(n[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof Ks){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;te&&s[n[e.uniqueId]]))}}"InstancedMesh"!==r.getClassName()&&(r.material=s[n[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 d.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,r=n[i.uniqueId],a=("number"==typeof r?s[r]:i).createInstance(t.name);u(t,a)}else{let t=!0;"TransformNode"===e.getClassName()||e.skeleton||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}`);u(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=s[n[e.uniqueId]];if(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=s[n[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=>s[n[e.uniqueId]]||e));r.animationGroups.push(i)})),r}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Me.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){this.cameras.forEach((t=>{e&&!e(t)||this.scene.addCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.addLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.addMesh(t)})),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((t=>{e&&!e(t)||this.scene.addTransformNode(t)})),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)}))}removeAllFromScene(){this._isValidHierarchy()||Me.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)})),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 n of e){let e=!0;if(i)for(const t of i)if(n===t){e=!1;break}e&&(t.push(n),n._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new ba);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 Ks("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 c.Error("No scene available to merge animations to"),[];const n=i||(t=>{let i=null;const n=t.animations.length?t.animations[0].targetProperty:"",s=t.name.split(".").join("").split("_primitive")[0];switch(n){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(s);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(s);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(s)}return i});this.getNodes().forEach((e=>{const t=n(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 s=new Array;return this.animationGroups.slice().forEach((e=>{s.push(e.clone(e.name,n)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const i=n(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))})),s}}function Da(e,t,i,n){const s={externalResourceFunction:e=>n(e).then((e=>new Uint8Array(e)))};return i&&(s.uri="file:"===t?i:t+i),e instanceof ArrayBuffer?GLTFValidator.validateBytes(new Uint8Array(e),s):GLTFValidator.validateString(e,s)}function Oa(){const e=[];onmessage=t=>{const i=t.data;switch(i.id){case"init":importScripts(i.url);break;case"validate":Da(i.data,i.rootUrl,i.fileName,(t=>new Promise(((i,n)=>{const s=e.length;e.push({resolve:i,reject:n}),postMessage({id:"getExternalResource",index:s,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 La{static ValidateAsync(e,t,i,n){return"function"==typeof Worker?new Promise(((s,r)=>{const a=`${Da}(${Oa})()`,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":n(t.uri).then((e=>{l.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e])}),(e=>{l.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})}));break;case"validate.resolve":l.removeEventListener("error",h),l.removeEventListener("message",c),s(t.value),l.terminate();break;case"validate.reject":l.removeEventListener("error",h),l.removeEventListener("message",c),r(t.reason),l.terminate()}};l.addEventListener("error",h),l.addEventListener("message",c),l.postMessage({id:"init",url:this.Configuration.url}),l.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})})):(this._LoadScriptPromise||(this._LoadScriptPromise=Me.LoadScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then((()=>Da(e,t,i,n))))}}function Na(e,t,i){try{return Promise.resolve(new Uint8Array(e,t,i))}catch(e){return Promise.reject(e)}}var Fa,wa,Ba,Ua,ka,Ga,Va,za,Ha,Wa,Xa;La.Configuration={url:"https://preview.babylonjs.com/gltf_validator.js"},function(e){e[e.AUTO=0]="AUTO",e[e.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"}(Fa||(Fa={})),function(e){e[e.NONE=0]="NONE",e[e.FIRST=1]="FIRST",e[e.ALL=2]="ALL"}(wa||(wa={})),function(e){e[e.LOADING=0]="LOADING",e[e.READY=1]="READY",e[e.COMPLETE=2]="COMPLETE"}(Ba||(Ba={}));class Ya{constructor(){this.onParsedObservable=new s,this.coordinateSystemMode=Fa.AUTO,this.animationStartMode=wa.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 s,this.onSkinLoadedObservable=new s,this.onTextureLoadedObservable=new s,this.onMaterialLoadedObservable=new s,this.onCameraLoadedObservable=new s,this.onCompleteObservable=new s,this.onErrorObservable=new s,this.onDisposeObservable=new s,this.onExtensionLoadedObservable=new s,this.validate=!1,this.onValidatedObservable=new s,this._loader=null,this._state=null,this._requests=new Array,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new s,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,n,r,a){this._progressCallback=n;const o=t.name?"file:":Me.GetFolderPath(t),l=t.name||Me.GetFilename(t);if(r){if(this.useRangeRequests){this.validate&&c.Warn("glTF validation is not supported when range requests are enabled");const n={abort:()=>{},onCompleteObservable:new s},r={readAsync:(i,n)=>new Promise(((s,r)=>{this._loadFile(e,t,(e=>{s(new Uint8Array(e))}),!0,(e=>{r(e)}),(e=>{e.setRequestHeader("Range",`bytes=${i}-${i+n-1}`)}))})),byteLength:0};return this._unpackBinaryAsync(new Er(r)).then((e=>{n.onCompleteObservable.notifyObservers(n),i(e)}),a?e=>a(void 0,e):void 0),n}return this._loadFile(e,t,(t=>{this._validate(e,t,o,l),this._unpackBinaryAsync(new Er({readAsync:(e,i)=>Na(t,e,i),byteLength:t.byteLength})).then((e=>{i(e)}),a?e=>a(void 0,e):void 0)}),!0,a)}return this._loadFile(e,t,(t=>{this._validate(e,t,o,l),i({json:this._parseJson(t)})}),r,a)}importMeshAsync(e,t,i,n,s,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,n,s,r))))}loadAsync(e,t,i,n,s){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,n,s))))}loadAssetContainerAsync(e,t,i,n,s){return Promise.resolve().then((()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t);const r=new Pa(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,n,s).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,"+Ya._MagicBase64Encoded)||e.startsWith("data:;base64,"+Ya._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+Ya._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+Ya._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+Ya._MagicBase64Encoded)||t.startsWith(";base64,"+Ya._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+Ya._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+Ya._MagicBase64Encoded)){const i=Ee(t);return this._validate(e,i),this._unpackBinaryAsync(new Er({readAsync:(e,t)=>Na(i,e,t),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(){return new Ya}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(Ba[this._state]))}_loadFile(e,t,i,n,s,r){const a=e._loadFile(t,i,(e=>{this._onProgress(e,a)}),!0,n,s,r);return a.onCompleteObservable.add((e=>{this._requests.splice(this._requests.indexOf(e),1)})),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,n=0,s=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,n+=e._loaded,s+=e._total}this._progressCallback({lengthComputable:i,loaded:n,total:i?s:0})}_validate(e,t,i="",n=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),La.ValidateAsync(t,i,n,(t=>this.preprocessUrlAsync(i+t).then((t=>e._loadFileAsync(t,void 0,!0,!0))))).then((e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()}),(e=>{this._endPerformanceCounter("Validate JSON"),Me.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=Ya._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=Ya._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(Ya._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const n={1:Ya._CreateGLTF1Loader,2:Ya._CreateGLTF2Loader}[i.major];if(!n)throw new Error("Unsupported version: "+t.version);return n(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 A("Unexpected magic: "+t,2e3);const i=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${i}`);const n=e.readUint32();let s;switch(this.useRangeRequests||n===e.buffer.byteLength||c.Warn(`Length in header does not match actual data length: ${n} != ${e.buffer.byteLength}`),i){case 1:s=this._unpackBinaryV1Async(e,n);break;case 2:s=this._unpackBinaryV2Async(e,n);break;default:throw new Error("Unsupported version: "+i)}return this._endPerformanceCounter("Unpack Binary"),s}))}_unpackBinaryV1Async(e,t){const i=e.readUint32(),n=e.readUint32();if(0!==n)throw new Error(`Unexpected content format: ${n}`);const s=t-e.byteOffset,r={json:this._parseJson(e.readString(i)),bin:null};if(0!==s){const t=e.byteOffset;r.bin={readAsync:(i,n)=>e.buffer.readAsync(t+i,n),byteLength:s}}return Promise.resolve(r)}_unpackBinaryV2Async(e,t){const i=1313821514,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 s={json:this._parseJson(e.readString(n)),bin:null},r=()=>{const n=e.readUint32();switch(e.readUint32()){case i:throw new Error("Unexpected JSON chunk");case 5130562:{const t=e.byteOffset;s.bin={readAsync:(i,n)=>e.buffer.readAsync(t+i,n),byteLength:n},e.skipBytes(n);break}default:e.skipBytes(n)}return e.byteOffset!==t?e.loadAsync(8).then(r):Promise.resolve(s)};return r()}))}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.majort.minor?1:e.minor(t.toArray(e,e.length),e)),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(16*t.length);for(let e=0;e1&&(this._multiview=!0,c.push("#define MULTIVIEW"),-1!==this._options.uniforms.indexOf("viewProjection")&&-1===this._options.uniforms.indexOf("viewProjectionR")&&this._options.uniforms.push("viewProjectionR"));for(let e=0;e4&&(d.push(Lt.MatricesIndicesExtraKind),d.push(Lt.MatricesWeightsExtraKind));const t=e.skeleton;c.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),u.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(c.push("#define BONETEXTURE"),-1===this._options.uniforms.indexOf("boneTextureWidth")&&this._options.uniforms.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(c.push("#define BonesPerMesh "+(t.bones.length+1)),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones"))}else c.push("#define NUM_BONE_INFLUENCERS 0");let g=0;const E=e?e.morphTargetManager:null;if(E){const e=E.supportsUVs&&-1!==c.indexOf("#define UV1"),t=E.supportsTangents&&-1!==c.indexOf("#define TANGENT"),i=E.supportsNormals&&-1!==c.indexOf("#define NORMAL");g=E.numInfluencers,e&&c.push("#define MORPHTARGETS_UV"),t&&c.push("#define MORPHTARGETS_TANGENT"),i&&c.push("#define MORPHTARGETS_NORMAL"),g>0&&c.push("#define MORPHTARGETS"),E.isUsingTextureForTargets&&(c.push("#define MORPHTARGETS_TEXTURE"),-1===this._options.uniforms.indexOf("morphTargetTextureIndices")&&this._options.uniforms.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),c.push("#define NUM_MORPH_INFLUENCERS "+g);for(let n=0;n0&&(_=_.slice(),_.push("morphTargetInfluences"),_.push("morphTargetTextureInfo"),_.push("morphTargetTextureIndices"))}else c.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(c.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===this._options.uniforms.indexOf("bakedVertexAnimationSettings")&&this._options.uniforms.push("bakedVertexAnimationSettings"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted")&&this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTime")&&this._options.uniforms.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),zi.PrepareAttributesForBakedVertexAnimation(d,e,c)}for(const e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&c.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&(Bi(_),Ui(this,l,c)),this.customShaderNameResolve&&(_=_.slice(),p=p.slice(),m=m.slice(),f=this.customShaderNameResolve(f,_,p,m,c,d));const T=o?i._getDrawWrapper():this._drawWrapper,A=null!==(n=null==T?void 0:T.effect)&&void 0!==n?n:null,v=null!==(s=null==T?void 0:T.defines)&&void 0!==s?s:null,S=c.join("\n");let R=A;return v!==S&&(R=h.createEffect(f,{attributes:d,uniformsNames:_,uniformBuffersNames:p,samplers:m,defines:S,fallbacks:u,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:g},shaderLanguage:this._options.shaderLanguage},h),o?i.setEffect(R,S,this._materialContext):T&&T.setEffect(R,S),this._onEffectCreatedObservable&&(Ka.effect=R,Ka.subMesh=null!==(r=null!=i?i:null==e?void 0:e.subMeshes[0])&&void 0!==r?r:null,this._onEffectCreatedObservable.notifyObservers(Ka))),R._wasPreviouslyUsingInstances=!!t,null!==(a=!(null==R?void 0:R.isReady()))&&void 0!==a&&!a&&(A!==R&&l.resetCachedMaterial(),R._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),n=null!=t?t:this.getEffect();n&&(-1!==this._options.uniforms.indexOf("world")&&n.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),n.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),n.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))}bindForSubMesh(e,t,i){var n;this.bind(e,t,null===(n=i._drawWrapperOverride)||void 0===n?void 0:n.effect,i)}bind(e,t,i,n){var s;const r=n&&this._storeEffectOnSubMeshes,a=null!=i?i:r?n.effect:this.getEffect();if(!a)return;this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);const o=this._options.uniformBuffers;let l=!1;if(a&&o&&o.length>0&&this.getScene().getEngine().supportsUniformBuffers)for(let i=0;i0&&zi.BindMorphTargetParameters(t,a);const i=t.bakedVertexAnimationManager;i&&i.isEnabled&&(null===(s=t.bakedVertexAnimationManager)||void 0===s||s.bind(a,!!a._wasPreviouslyUsingInstances))}this._afterBind(t,a)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let t=0;tnew ja(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes)),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach((e=>{const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))})),this.stencil.copyTo(t.stencil);for(const e in this._textures)t.setTexture(e,this._textures[e]);for(const e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(const e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(const e in this._ints)t.setInt(e,this._ints[e]);for(const e in this._uints)t.setUInt(e,this._uints[e]);for(const e in this._floats)t.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(const e in this._colors3)t.setColor3(e,this._colors3[e]);for(const e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(const e in this._colors4)t.setColor4(e,this._colors4[e]);for(const e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(const e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(const e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(const e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(const e in this._matrices)t.setMatrix(e,this._matrices[e]);for(const e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(const e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(const e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(const e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(const e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(const e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(const e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(const e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(const e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;enew ja(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let s;for(s in e.stencil&&n.stencil.parse(e.stencil,t,i),e.textures)n.setTexture(s,Ji.Parse(e.textures[s],t,i));for(s in e.textureArrays){const r=e.textureArrays[s],a=new Array;for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>tt.FromArray(e)));n.setColor3Array(s,t)}for(s in e.colors4)n.setColor4(s,it.FromArray(e.colors4[s]));for(s in e.colors4Arrays){const t=e.colors4Arrays[s].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>it.FromArray(e)));n.setColor4Array(s,t)}for(s in e.vectors2)n.setVector2(s,Ve.FromArray(e.vectors2[s]));for(s in e.vectors3)n.setVector3(s,ze.FromArray(e.vectors3[s]));for(s in e.vectors4)n.setVector4(s,He.FromArray(e.vectors4[s]));for(s in e.quaternions)n.setQuaternion(s,We.FromArray(e.quaternions[s]));for(s in e.matrices)n.setMatrix(s,Xe.FromArray(e.matrices[s]));for(s in e.matrixArray)n._matrixArrays[s]=new Float32Array(e.matrixArray[s]);for(s in e.matrices3x3)n.setMatrix3x3(s,e.matrices3x3[s]);for(s in e.matrices2x2)n.setMatrix2x2(s,e.matrices2x2[s]);for(s in e.vectors2Arrays)n.setArray2(s,e.vectors2Arrays[s]);for(s in e.vectors3Arrays)n.setArray3(s,e.vectors3Arrays[s]);for(s in e.vectors4Arrays)n.setArray4(s,e.vectors4Arrays[s]);for(s in e.quaternionsArrays)n.setArray4(s,e.quaternionsArrays[s]);return n}static ParseFromFileAsync(e,t,i,n=""){return new Promise(((s,r)=>{const a=new p;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const t=JSON.parse(a.responseText),r=this.Parse(t,i||m.LastCreatedScene,n);e&&(r.name=e),s(r)}else r("Unable to load the ShaderMaterial")})),a.open("GET",t),a.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((n,s)=>{const r=new p;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){const s=JSON.parse(JSON.parse(r.responseText).jsonPayload),a=JSON.parse(s.shaderMaterial),o=this.Parse(a,t||m.LastCreatedScene,i);o.snippetId=e,n(o)}else s("Unable to load the snippet "+e)})),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()}))}}ja.SnippetUrl="https://snippet.babylonjs.com",ja.CreateFromSnippetAsync=ja.ParseFromSnippetAsync,Se("BABYLON.ShaderMaterial",ja);class qa extends Ti{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0}_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=ze.Zero()),ze.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=ze.Zero()),ze.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=ze.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=ze.Cross(this.direction,vi.Y),t=ze.Cross(e,this.direction);return ze.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=ze.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=Xe.Identity()),Xe.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)}}Qe([pt()],qa.prototype,"position",null),Qe([pt()],qa.prototype,"direction",null),Qe([ct()],qa.prototype,"shadowMinZ",null),Qe([ct()],qa.prototype,"shadowMaxZ",null),Ei.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new Qa(e,ze.Zero(),t)));class Qa extends qa{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 Ti.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&&Xe.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 n=this.getScene().activeCamera;if(!n)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=ze.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;let n=Number.MAX_VALUE,s=Number.MIN_VALUE;for(let r=0;rthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zs&&(s=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=n,this._shadowMaxZ=s)}const s=this._orthoRight-this._orthoLeft,r=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;Xe.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*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}}Qe([ct()],Qa.prototype,"shadowFrustumSize",null),Qe([ct()],Qa.prototype,"shadowOrthoScale",null),Qe([ct()],Qa.prototype,"autoUpdateExtends",void 0),Qe([ct()],Qa.prototype,"autoCalcShadowZBounds",void 0),Qe([ct("orthoLeft")],Qa.prototype,"_orthoLeft",void 0),Qe([ct("orthoRight")],Qa.prototype,"_orthoRight",void 0),Qe([ct("orthoTop")],Qa.prototype,"_orthoTop",void 0),Qe([ct("orthoBottom")],Qa.prototype,"_orthoBottom",void 0),Ei.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new Za(e,ze.Zero(),t)));class Za extends qa{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 Ti.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new ze(1,0,0);case 1:return new ze(-1,0,0);case 2:return new ze(0,-1,0);case 3:return new ze(0,1,0);case 4:return new ze(0,0,1);case 5:return new ze(0,0,-1)}return ze.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const n=this.getScene().activeCamera;if(!n)return;const s=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,r=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;Xe.PerspectiveFovLHToRef(this.shadowAngle,1,a?r:s,a?s: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}}Qe([ct()],Za.prototype,"shadowAngle",null),Ei.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new Ja(e,ze.Zero(),ze.Zero(),0,0,t)));class Ja extends qa{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()&&(Ja._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):Ja._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,n,s,r){super(e,r),this._innerAngle=0,this._projectionTextureMatrix=Xe.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=ze.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=ze.Zero(),this._projectionTextureViewLightMatrix=Xe.Zero(),this._projectionTextureProjectionLightMatrix=Xe.Zero(),this._projectionTextureScalingMatrix=Xe.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=n,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return Ti.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const n=this.getScene().activeCamera;if(!n)return;this._shadowAngleScale=this._shadowAngleScale||1;const s=this._shadowAngleScale*this._angle,r=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;Xe.PerspectiveFovLHToRef(s,1,o?a:r,o?r:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.position.addToRef(this.direction,this._projectionTextureViewTargetVector),Xe.LookAtLHToRef(this.position,this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),n=-i*t,s=1/Math.tan(this._angle/2);Xe.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,n,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof Ji){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;Xe.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("projectionLightSampler"+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=ze.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=ze.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()?ze.Normalize(this.transformedDirection):ze.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())}}Qe([ct()],Ja.prototype,"angle",null),Qe([ct()],Ja.prototype,"innerAngle",null),Qe([ct()],Ja.prototype,"shadowAngleScale",null),Qe([ct()],Ja.prototype,"exponent",void 0),Qe([ct()],Ja.prototype,"projectionTextureLightNear",null),Qe([ct()],Ja.prototype,"projectionTextureLightFar",null),Qe([ct()],Ja.prototype,"projectionTextureUpDirection",null),Qe([dt("projectedLightTexture")],Ja.prototype,"_projectionTexture",void 0);class $a{static SetMatrix(e,t,i,n,s){let r=null;if("MODEL"===i.semantic?r=t.getWorldMatrix():"PROJECTION"===i.semantic?r=e.getProjectionMatrix():"VIEW"===i.semantic?r=e.getViewMatrix():"MODELVIEWINVERSETRANSPOSE"===i.semantic?r=Xe.Transpose(t.getWorldMatrix().multiply(e.getViewMatrix()).invert()):"MODELVIEW"===i.semantic?r=t.getWorldMatrix().multiply(e.getViewMatrix()):"MODELVIEWPROJECTION"===i.semantic?r=t.getWorldMatrix().multiply(e.getTransformMatrix()):"MODELINVERSE"===i.semantic?r=t.getWorldMatrix().invert():"VIEWINVERSE"===i.semantic?r=e.getViewMatrix().invert():"PROJECTIONINVERSE"===i.semantic?r=e.getProjectionMatrix().invert():"MODELVIEWINVERSE"===i.semantic?r=t.getWorldMatrix().multiply(e.getViewMatrix()).invert():"MODELVIEWPROJECTIONINVERSE"===i.semantic?r=t.getWorldMatrix().multiply(e.getTransformMatrix()).invert():"MODELINVERSETRANSPOSE"===i.semantic&&(r=Xe.Transpose(t.getWorldMatrix().invert())),r)switch(i.type){case Ga.FLOAT_MAT2:s.setMatrix2x2(n,Xe.GetAsMatrix2x2(r));break;case Ga.FLOAT_MAT3:s.setMatrix3x3(n,Xe.GetAsMatrix3x3(r));break;case Ga.FLOAT_MAT4:s.setMatrix(n,r)}}static SetUniform(e,t,i,n){switch(n){case Ga.FLOAT:return e.setFloat(t,i),!0;case Ga.FLOAT_VEC2:return e.setVector2(t,Ve.FromArray(i)),!0;case Ga.FLOAT_VEC3:return e.setVector3(t,ze.FromArray(i)),!0;case Ga.FLOAT_VEC4:return e.setVector4(t,He.FromArray(i)),!0;default:return!1}}static GetWrapMode(e){switch(e){case Va.CLAMP_TO_EDGE:return Ji.CLAMP_ADDRESSMODE;case Va.MIRRORED_REPEAT:return Ji.MIRROR_ADDRESSMODE;case Va.REPEAT:default:return Ji.WRAP_ADDRESSMODE}}static GetByteStrideFromType(e){switch(e.type){case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 1}}static GetTextureFilterMode(e){switch(e){case za.LINEAR:case za.LINEAR_MIPMAP_NEAREST:case za.LINEAR_MIPMAP_LINEAR:return Ji.TRILINEAR_SAMPLINGMODE;case za.NEAREST:case za.NEAREST_MIPMAP_NEAREST:return Ji.NEAREST_SAMPLINGMODE;default:return Ji.BILINEAR_SAMPLINGMODE}}static GetBufferFromBufferView(e,t,i,n,s){i=t.byteOffset+i;const r=e.loadedBufferViews[t.buffer];if(i+n>r.byteLength)throw new Error("Buffer access is out of range");const a=r.buffer;switch(i+=r.byteOffset,s){case Ua.BYTE:return new Int8Array(a,i,n);case Ua.UNSIGNED_BYTE:return new Uint8Array(a,i,n);case Ua.SHORT:return new Int16Array(a,i,n);case Ua.UNSIGNED_SHORT:return new Uint16Array(a,i,n);default:return new Float32Array(a,i,n)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],n=t.count*$a.GetByteStrideFromType(t);return $a.GetBufferFromBufferView(e,i,t.byteOffset,n,t.componentType)}static DecodeBufferToText(e){let t="";const i=e.byteLength;for(let n=0;n=this._maxPos}}const no=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],so=["world","view","projection","worldView","worldViewProjection","mBones"],ro=["translation","rotation","scale"],ao=["position","rotationQuaternion","scaling"],oo=(e,t,i)=>{for(const n in e){const s=e[n];i[t][n]=s}},lo=e=>{if(e)for(let t=0;t{if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){const t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},co=e=>{let t=null;if(e.translation||e.rotation||e.scale){const i=ze.FromArray(e.scale||[1,1,1]),n=We.FromArray(e.rotation||[0,0,0,1]),s=ze.FromArray(e.translation||[0,0,0]);t=Xe.Compose(i,n,s)}else t=Xe.FromArray(e.matrix);return t},uo=(e,t,i,n)=>{for(let e=0;e{for(let i=0;i{const i=e.nodes;let n=i[t];if(n)return{node:n,id:t};for(const e in i)if(n=i[e],n.jointName===t)return{node:n,id:e};return null},po=(e,t)=>{for(let i=0;i{if(s||(e.scene._blockEntityCollection=!!e.assetContainer,(s=new Ks(t.name||"",e.scene))._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,s.id=n),!t.babylonNode)return s;const r=[];let a=null;const o=new Array,l=new Array,h=new Array,c=new Array;for(let t=0;t1?(d=new Vs("multimat"+n,e.scene),d.subMaterials=r):d=new un("multimat"+n,e.scene),1===r.length&&(d=r[0]),d._parentContainer=e.assetContainer,s.material||(s.material=d),new Fs(n,e.scene,a,!1,s),s.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,s.subMeshes=[];let u=0;for(let t=0;t{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=i),e.scaling&&(e.scaling=n)},Eo=(e,t,i)=>{let n=null;if(e.importOnlyMeshes&&(t.skin||t.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(t.name||""))return null;if(t.skin){if(t.meshes){const s=e.skins[t.skin],r=mo(e,t,t.meshes,i,t.babylonNode);r.skeleton=e.scene.getLastSkeletonById(t.skin),null===r.skeleton&&(r.skeleton=((e,t,i,n)=>{if(n||(n=new Ir(t.name||"","",e.scene)),!t.babylonSkeleton)return n;const s=[],r=[];((e,t,i,n)=>{for(const s in e.nodes){const r=e.nodes[s],a=s;if(!r.jointName||po(i,r.jointName))continue;const o=co(r),l=new vr(r.name||"",t,null,o);l.id=a,n.push({bone:l,node:r,id:a})}for(let e=0;e0&&(d=fo(s,l),d&&-1===r.indexOf(d)&&r.push(d)),new vr(o.jointName||"",n,d,u).id=l}const a=n.bones;n.bones=[];for(let i=0;i{if(t.matrix){const i=new ze(0,0,0),n=new We,s=new ze(0,0,0);Xe.FromArray(t.matrix).decompose(s,n,i),go(e,i,n,s)}else t.translation&&t.rotation&&t.scale&&go(e,ze.FromArray(t.translation),We.FromArray(t.rotation),ze.FromArray(t.scale));e.computeWorldMatrix(!0)})(n,t);else{const e=t.translation||[0,0,0],i=t.rotation||[0,0,0,1],s=t.scale||[1,1,1];go(n,ze.FromArray(e),We.FromArray(i),ze.FromArray(s))}n.updateCache(!0),t.babylonNode=n}return n},To=(e,t,i,n=!1)=>{const s=e.nodes[t];let r=null;if(n=!(e.importOnlyMeshes&&!n&&e.importMeshesNames)||-1!==e.importMeshesNames.indexOf(s.name||"")||0===e.importMeshesNames.length,!s.jointName&&n&&(r=Eo(e,s,t),null!==r&&(r.id=t,r.parent=i)),s.children)for(let t=0;t{let t=e.currentScene;if(t)for(let i=0;i{for(const t in e.animations){const i=e.animations[t];if(!i.channels||!i.samplers)continue;let n=null;for(let s=0;s{for(const n in t.uniforms){const s=t.uniforms[n],r=t.parameters[s];if(e.currentIdentifier===n&&r.semantic&&!r.source&&!r.node){const e=no.indexOf(r.semantic);if(-1!==e)return delete i[n],so[e]}}return e.currentIdentifier},So=e=>{for(const t in e.materials)xo.LoadMaterialAsync(e,t,(()=>{}),(()=>{}))};class Ro{static CreateRuntime(e,t,i){const n={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:i,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&oo(e.extensions,"extensions",n),e.extensionsUsed&&oo(e.extensionsUsed,"extensionsUsed",n),e.buffers&&((e,t)=>{for(const i in e){const n=e[i];t.buffers[i]=n,t.buffersCount++}})(e.buffers,n),e.bufferViews&&oo(e.bufferViews,"bufferViews",n),e.accessors&&oo(e.accessors,"accessors",n),e.meshes&&oo(e.meshes,"meshes",n),e.lights&&oo(e.lights,"lights",n),e.cameras&&oo(e.cameras,"cameras",n),e.nodes&&oo(e.nodes,"nodes",n),e.images&&oo(e.images,"images",n),e.textures&&oo(e.textures,"textures",n),e.shaders&&((e,t)=>{for(const i in e){const n=e[i];t.shaders[i]=n,t.shaderscount++}})(e.shaders,n),e.programs&&oo(e.programs,"programs",n),e.samplers&&oo(e.samplers,"samplers",n),e.techniques&&oo(e.techniques,"techniques",n),e.materials&&oo(e.materials,"materials",n),e.animations&&oo(e.animations,"animations",n),e.skins&&oo(e.skins,"skins",n),e.scenes&&(n.scenes=e.scenes),e.scene&&e.scenes&&(n.currentScene=e.scenes[e.scene]),n}static LoadBufferAsync(e,t,i,n,s){const r=e.buffers[t];Me.IsBase64(r.uri)?setTimeout((()=>i(new Uint8Array(Me.DecodeBase64(r.uri))))):Me.LoadFile(e.rootUrl+r.uri,(e=>i(new Uint8Array(e))),s,void 0,!0,(e=>{e&&n(e.status+" "+e.statusText)}))}static LoadTextureBufferAsync(e,t,i,n){const s=e.textures[t];if(!s||!s.source)return void n("");if(s.babylonTexture)return void i(null);const r=e.images[s.source];Me.IsBase64(r.uri)?setTimeout((()=>i(new Uint8Array(Me.DecodeBase64(r.uri))))):Me.LoadFile(e.rootUrl+r.uri,(e=>i(new Uint8Array(e))),void 0,void 0,!0,(e=>{e&&n(e.status+" "+e.statusText)}))}static CreateTextureAsync(e,t,i,n){const s=e.textures[t];if(s.babylonTexture)return void n(s.babylonTexture);const r=e.samplers[s.sampler],a=r.minFilter===za.NEAREST_MIPMAP_NEAREST||r.minFilter===za.NEAREST_MIPMAP_LINEAR||r.minFilter===za.LINEAR_MIPMAP_NEAREST||r.minFilter===za.LINEAR_MIPMAP_LINEAR,o=Ji.BILINEAR_SAMPLINGMODE,l=null==i?new Blob:new Blob([i]),h=URL.createObjectURL(l),c=()=>URL.revokeObjectURL(h),d=new Ji(h,e.scene,!a,!0,o,c,c);void 0!==r.wrapS&&(d.wrapU=$a.GetWrapMode(r.wrapS)),void 0!==r.wrapT&&(d.wrapV=$a.GetWrapMode(r.wrapT)),d.name=t,s.babylonTexture=d,n(d)}static LoadShaderStringAsync(e,t,i,n){const s=e.shaders[t];if(Me.IsBase64(s.uri)){const e=atob(s.uri.split(",")[1]);i&&i(e)}else Me.LoadFile(e.rootUrl+s.uri,i,void 0,void 0,!1,(e=>{e&&n&&n(e.status+" "+e.statusText)}))}static LoadMaterialAsync(e,t,i,n){const s=e.materials[t];if(!s.technique)return void(n&&n("No technique found."));const r=e.techniques[s.technique];if(!r){e.scene._blockEntityCollection=!!e.assetContainer;const n=new un(t,e.scene);return n._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,n.diffuseColor=new tt(.5,.5,.5),n.sideOrientation=Yi.CounterClockWiseSideOrientation,void i(n)}const a=e.programs[r.program],o=r.states,l=U.ShadersStore[a.vertexShader+"VertexShader"],h=U.ShadersStore[a.fragmentShader+"PixelShader"];let c="",d="";const u=new io(l),f=new io(h),_={},p=[],m=[],g=[];for(const e in r.uniforms){const t=r.uniforms[e],i=r.parameters[t];if(_[e]=i,!i.semantic||i.node||i.source)i.type===Ga.SAMPLER_2D?g.push(e):p.push(e);else{const t=no.indexOf(i.semantic);-1!==t?(p.push(so[t]),delete _[e]):p.push(e)}}for(const e in r.attributes){const t=r.attributes[e],i=r.parameters[t];if(i.semantic){const e=ho(i);e&&m.push(e)}}for(;!u.isEnd()&&u.getNextToken();){if(u.currentToken!==to.IDENTIFIER){c+=u.currentString;continue}let e=!1;for(const t in r.attributes){const i=r.attributes[t],n=r.parameters[i];if(u.currentIdentifier===t&&n.semantic){c+=ho(n),e=!0;break}}e||(c+=vo(u,r,_))}for(;!f.isEnd()&&f.getNextToken();)f.currentToken===to.IDENTIFIER?d+=vo(f,r,_):d+=f.currentString;const E={vertex:a.vertexShader+t,fragment:a.fragmentShader+t},T={attributes:m,uniforms:p,samplers:g,needAlphaBlending:o&&o.enable&&-1!==o.enable.indexOf(3042)};U.ShadersStore[a.vertexShader+t+"VertexShader"]=c,U.ShadersStore[a.fragmentShader+t+"PixelShader"]=d;const A=new ja(t,e.scene,E,T);if(A.onError=((e,t,i)=>(n,s)=>{t.dispose(!0),i("Cannot compile program named "+e.name+". Error: "+s+". Default material will be applied")})(a,A,n),A.onCompiled=((e,t,i,n,s,r)=>a=>{((e,t,i,n,s)=>{const r=n.values||i.parameters,a=i.uniforms;for(const i in s){const o=s[i],l=o.type;let h=r[a[i]];if(void 0===h&&(h=o.value),!h)continue;const c=e=>i=>{o.value&&e&&(t.setTexture(e,i),delete s[e])};l===Ga.SAMPLER_2D?xo.LoadTextureAsync(e,n.values?h:o.value,c(i),(()=>c(null))):o.value&&$a.SetUniform(t,i,n.values?h:o.value,l)&&delete s[i]}})(e,t,i,n,s),t.onBind=a=>{((e,t,i,n,s,r,a)=>{const o=r.values||s.parameters;for(const a in i){const l=i[a],h=l.type;if(h===Ga.FLOAT_MAT2||h===Ga.FLOAT_MAT3||h===Ga.FLOAT_MAT4)if(!l.semantic||l.source||l.node){if(l.semantic&&(l.source||l.node)){let e=t.scene.getNodeByName(l.source||l.node||"");if(null===e&&(e=t.scene.getNodeById(l.source||l.node||"")),null===e)continue;$a.SetMatrix(t.scene,e,l,a,n.getEffect())}}else $a.SetMatrix(t.scene,e,l,a,n.getEffect());else{const e=o[s.uniforms[a]];if(!e)continue;if(h===Ga.SAMPLER_2D){const i=t.textures[r.values?e:l.value].babylonTexture;if(null==i)continue;n.getEffect().setTexture(a,i)}else $a.SetUniform(n.getEffect(),a,e,h)}}a(n)})(a,e,s,t,i,n,r)}})(e,A,r,s,_,i),A.sideOrientation=Yi.CounterClockWiseSideOrientation,o&&o.functions){const e=o.functions;e.cullFace&&e.cullFace[0]!==Wa.BACK&&(A.backFaceCulling=!1);const t=e.blendFuncSeparate;t&&(t[0]===Xa.SRC_ALPHA&&t[1]===Xa.ONE_MINUS_SRC_ALPHA&&t[2]===Xa.ONE&&t[3]===Xa.ONE?A.alphaMode=eo.ALPHA_COMBINE:t[0]===Xa.ONE&&t[1]===Xa.ONE&&t[2]===Xa.ZERO&&t[3]===Xa.ONE?A.alphaMode=eo.ALPHA_ONEONE:t[0]===Xa.SRC_ALPHA&&t[1]===Xa.ONE&&t[2]===Xa.ZERO&&t[3]===Xa.ONE?A.alphaMode=eo.ALPHA_ADD:t[0]===Xa.ZERO&&t[1]===Xa.ONE_MINUS_SRC_COLOR&&t[2]===Xa.ONE&&t[3]===Xa.ONE?A.alphaMode=eo.ALPHA_SUBTRACT:t[0]===Xa.DST_COLOR&&t[1]===Xa.ZERO&&t[2]===Xa.ONE&&t[3]===Xa.ONE?A.alphaMode=eo.ALPHA_MULTIPLY:t[0]===Xa.SRC_ALPHA&&t[1]===Xa.ONE_MINUS_SRC_COLOR&&t[2]===Xa.ONE&&t[3]===Xa.ONE&&(A.alphaMode=eo.ALPHA_MAXIMIZED))}}}class Co{static RegisterExtension(e){Co.Extensions[e.name]?Me.Error('Tool with the same name "'+e.name+'" already exists'):Co.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,n,s,r,a,o){return t.useRightHandedSystem=!0,xo.LoadRuntimeAsync(t,i,n,(t=>{t.assetContainer=s,t.importOnlyMeshes=!0,""===e?t.importMeshesNames=[]:"string"==typeof e?t.importMeshesNames=[e]:!e||e instanceof Array?(t.importMeshesNames=[],Me.Warn("Argument meshesNames must be of type string or string[]")):t.importMeshesNames=[e],this._createNodes(t);const i=new Array,n=new Array;for(const e in t.nodes){const n=t.nodes[e];n.babylonNode instanceof Gs&&i.push(n.babylonNode)}for(const e in t.skins){const i=t.skins[e];i.babylonSkeleton instanceof Ir&&n.push(i.babylonSkeleton)}this._loadBuffersAsync(t,(()=>{this._loadShadersAsync(t,(()=>{So(t),Ao(t),!Ya.IncrementalLoading&&r&&r(i,n)}))})),Ya.IncrementalLoading&&r&&r(i,n)}),o),!0}importMeshAsync(e,t,i,n,s,r){return new Promise(((a,o)=>{this._importMeshAsync(e,t,n,s,i,((e,t)=>{a({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[]})}),r,(e=>{o(new Error(e))}))}))}_loadAsync(e,t,i,n,s,r){e.useRightHandedSystem=!0,xo.LoadRuntimeAsync(e,t,i,(e=>{xo.LoadRuntimeExtensionsAsync(e,(()=>{this._createNodes(e),this._loadBuffersAsync(e,(()=>{this._loadShadersAsync(e,(()=>{So(e),Ao(e),Ya.IncrementalLoading||n()}))})),Ya.IncrementalLoading&&n()}),r)}),r)}loadAsync(e,t,i,n){return new Promise(((s,r)=>{this._loadAsync(e,t,i,(()=>{s()}),n,(e=>{r(new Error(e))}))}))}_loadShadersAsync(e,t){let i=!1;const n=(i,n)=>{xo.LoadShaderStringAsync(e,i,(s=>{s instanceof ArrayBuffer||(e.loadedShaderCount++,s&&(U.ShadersStore[i+(n.type===ka.VERTEX?"VertexShader":"PixelShader")]=s),e.loadedShaderCount===e.shaderscount&&t())}),(()=>{Me.Error("Error when loading shader program named "+i+" located at "+n.uri)}))};for(const t in e.shaders){i=!0;const s=e.shaders[t];s?n.bind(this,t,s)():Me.Error("No shader named: "+t)}i||t()}_loadBuffersAsync(e,t){let i=!1;const n=(i,n)=>{xo.LoadBufferAsync(e,i,(s=>{e.loadedBufferCount++,s&&(s.byteLength!=e.buffers[i].byteLength&&Me.Error("Buffer named "+i+" is length "+s.byteLength+". Expected: "+n.byteLength),e.loadedBufferViews[i]=s),e.loadedBufferCount===e.buffersCount&&t()}),(()=>{Me.Error("Error when loading buffer named "+i+" located at "+n.uri)}))};for(const t in e.buffers){i=!0;const s=e.buffers[t];s?n.bind(this,t,s)():Me.Error("No buffer named: "+t)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;ir.loadRuntimeAsync(e,t,i,n,s)),(()=>{setTimeout((()=>{n&&n(Ro.CreateRuntime(t.json,e,i))}))}))}static LoadRuntimeExtensionsAsync(e,t,i){xo._ApplyExtensions((n=>n.loadRuntimeExtensionsAsync(e,t,i)),(()=>{setTimeout((()=>{t()}))}))}static LoadBufferAsync(e,t,i,n,s){xo._ApplyExtensions((r=>r.loadBufferAsync(e,t,i,n,s)),(()=>{Ro.LoadBufferAsync(e,t,i,n,s)}))}static LoadTextureAsync(e,t,i,n){xo._LoadTextureBufferAsync(e,t,(s=>{s&&xo._CreateTextureAsync(e,t,s,i,n)}),n)}static LoadShaderStringAsync(e,t,i,n){xo._ApplyExtensions((s=>s.loadShaderStringAsync(e,t,i,n)),(()=>{Ro.LoadShaderStringAsync(e,t,i,n)}))}static LoadMaterialAsync(e,t,i,n){xo._ApplyExtensions((s=>s.loadMaterialAsync(e,t,i,n)),(()=>{Ro.LoadMaterialAsync(e,t,i,n)}))}static _LoadTextureBufferAsync(e,t,i,n){xo._ApplyExtensions((s=>s.loadTextureBufferAsync(e,t,i,n)),(()=>{Ro.LoadTextureBufferAsync(e,t,i,n)}))}static _CreateTextureAsync(e,t,i,n,s){xo._ApplyExtensions((r=>r.createTextureAsync(e,t,i,n,s)),(()=>{Ro.CreateTextureAsync(e,t,i,n)}))}static _ApplyExtensions(e,t){for(const t in Co.Extensions)if(e(Co.Extensions[t]))return;t()}}Ya._CreateGLTF1Loader=()=>new Co,Co.RegisterExtension(new class extends xo{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,n){const s=t.json.extensionsUsed;return!(!s||-1===s.indexOf(this.name)||!t.bin||(this._bin=t.bin,n(Ro.CreateRuntime(t.json,e,i)),0))}loadBufferAsync(e,t,i,n){return-1!==e.extensionsUsed.indexOf(this.name)&&"binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(i,(e=>n(e.message))),!0)}loadTextureBufferAsync(e,t,i){const n=e.textures[t],s=e.images[n.source];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],a=e.bufferViews[r.bufferView];return i($a.GetBufferFromBufferView(e,a,0,a.byteLength,Ua.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,i){const n=e.shaders[t];if(!n.extensions||!(this.name in n.extensions))return!1;const s=n.extensions[this.name],r=e.bufferViews[s.bufferView],a=$a.GetBufferFromBufferView(e,r,0,r.byteLength,Ua.UNSIGNED_BYTE);return setTimeout((()=>{const e=$a.DecodeBufferToText(a);i(e)})),!0}}),Co.RegisterExtension(new class extends xo{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const t=e.extensions[this.name];if(!t)return!1;const i=t.lights;if(i)for(const t in i){const n=i[t];switch(n.type){case"ambient":{const t=new Ai(n.name,new ze(0,1,0),e.scene),i=n.ambient;i&&(t.diffuse=tt.FromArray(i.color||[1,1,1]));break}case"point":{const t=new Za(n.name,new ze(10,10,10),e.scene),i=n.point;i&&(t.diffuse=tt.FromArray(i.color||[1,1,1]));break}case"directional":{const t=new Qa(n.name,new ze(0,-1,0),e.scene),i=n.directional;i&&(t.diffuse=tt.FromArray(i.color||[1,1,1]));break}case"spot":{const t=n.spot;t&&(new Ja(n.name,new ze(0,10,0),new ze(0,-1,0),t.fallOffAngle||Math.PI,t.fallOffExponent||0,e.scene).diffuse=tt.FromArray(t.color||[1,1,1]));break}default:Me.Warn('GLTF Material Common extension: light type "'+n.type+"” not supported")}}return!1}loadMaterialAsync(e,t,i,n){const s=e.materials[t];if(!s||!s.extensions)return!1;const r=s.extensions[this.name];if(!r)return!1;const a=new un(t,e.scene);return a.sideOrientation=Yi.CounterClockWiseSideOrientation,"CONSTANT"===r.technique&&(a.disableLighting=!0),a.backFaceCulling=void 0!==r.doubleSided&&!r.doubleSided,a.alpha=void 0===r.values.transparency?1:r.values.transparency,a.specularPower=void 0===r.values.shininess?0:r.values.shininess,"string"==typeof r.values.ambient?this._loadTexture(e,r.values.ambient,a,"ambientTexture",n):a.ambientColor=tt.FromArray(r.values.ambient||[0,0,0]),"string"==typeof r.values.diffuse?this._loadTexture(e,r.values.diffuse,a,"diffuseTexture",n):a.diffuseColor=tt.FromArray(r.values.diffuse||[0,0,0]),"string"==typeof r.values.emission?this._loadTexture(e,r.values.emission,a,"emissiveTexture",n):a.emissiveColor=tt.FromArray(r.values.emission||[0,0,0]),"string"==typeof r.values.specular?this._loadTexture(e,r.values.specular,a,"specularTexture",n):a.specularColor=tt.FromArray(r.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,n,s){Ro.LoadTextureBufferAsync(e,t,(s=>{Ro.CreateTextureAsync(e,t,s,(e=>i[n]=e))}),s)}});class Mo{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class Io{get from(){return this._from}get to(){return 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;en[0].frame&&(this._from=n[0].frame),this._toe){const t={frame:e,value:s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation};n.splice(0,0,t)}if(r.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._targetedAnimations.length&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,n,s){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let r=0;r{this.onAnimationEndObservable.notifyObservers(a),this._checkAnimationGroupEnded(o)},this._processLoop(o,a,r),this._animatables.push(o)}return 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;ee._runtimeAnimations.length>0)),this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-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 n=new Io(e||this.name,this._scene);for(const e of this._targetedAnimations)n.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return n}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.targetedAnimations=[];for(let t=0;t0&&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){var t,i,n,s;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose(),null===(n=this._bumpTexture)||void 0===n||n.dispose(),null===(s=this._tintTexture)||void 0===s||s.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"}]}}}Do._DefaultIndexOfRefraction=1.5,Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Do.prototype,"isEnabled",void 0),Qe([ct()],Do.prototype,"intensity",void 0),Qe([ct()],Do.prototype,"roughness",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Do.prototype,"indexOfRefraction",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Do.prototype,"texture",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Do.prototype,"useRoughnessFromMainTexture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Do.prototype,"textureRoughness",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Do.prototype,"remapF0OnInterfaceChange",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Do.prototype,"bumpTexture",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Do.prototype,"isTintEnabled",void 0),Qe([ut()],Do.prototype,"tintColor",void 0),Qe([ct()],Do.prototype,"tintColorAtDistance",void 0),Qe([ct()],Do.prototype,"tintThickness",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Do.prototype,"tintTexture",void 0);class Oo extends Tt{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0,this.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=!1}}class Lo extends on{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new Oo,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=Lo._DefaultMinimumThickness,this.maximumThickness=Lo._DefaultMaximumThickness,this.indexOfRefraction=Lo._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&nn.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&nn.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.IRIDESCENCE=!0,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=null!==this._texture&&this._texture._texture===(null===(i=this._thicknessTexture)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._thicknessTexture),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&nn.IridescenceTextureEnabled?zi.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&nn.IridescenceTextureEnabled?zi.PrepareDefinesForMergedUV(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_USE_THICKNESS_FROM_MAINTEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t,i,n){var s,r,a,o,l,h,c,d;if(!this._isEnabled)return;const u=n.materialDefines,f=this._material.isFrozen,_=u.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;e.useUbo&&f&&e.isSync||(_&&nn.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),zi.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&nn.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",null!==(r=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==r?r:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._thicknessTexture)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(d=null===(c=this._thicknessTexture)||void 0===c?void 0:c.level)&&void 0!==d?d:0),this._texture&&zi.BindTextureMatrix(this._texture,e,"iridescence"),!this._thicknessTexture||_||u.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE||zi.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&nn.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!_&&!u.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&nn.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){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._thicknessTexture)||void 0===i||i.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"}]}}}Lo._DefaultMinimumThickness=100,Lo._DefaultMaximumThickness=400,Lo._DefaultIndexOfRefraction=1.3,Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Lo.prototype,"isEnabled",void 0),Qe([ct()],Lo.prototype,"intensity",void 0),Qe([ct()],Lo.prototype,"minimumThickness",void 0),Qe([ct()],Lo.prototype,"maximumThickness",void 0),Qe([ct()],Lo.prototype,"indexOfRefraction",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Lo.prototype,"texture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Lo.prototype,"thicknessTexture",void 0);class No extends Tt{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.MAINUV1=!1}}class Fo extends on{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new No,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new Ve(1,0),this._texture=null,this.texture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&nn.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(Lt.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&nn.AnisotropicTextureEnabled?zi.PrepareDefinesForMergedUV(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.MAINUV1=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&nn.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),zi.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&nn.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"}]}}}Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Fo.prototype,"isEnabled",void 0),Qe([ct()],Fo.prototype,"intensity",void 0),Qe([_t()],Fo.prototype,"direction",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Fo.prototype,"texture",void 0);class wo extends Tt{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,this.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1}}class Bo extends on{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new wo,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=tt.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[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&nn.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&nn.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){var i;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.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=null!==this._texture&&this._texture._texture===(null===(i=this._textureRoughness)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&nn.SheenTextureEnabled?(zi.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&nn.SheenTextureEnabled?zi.PrepareDefinesForMergedUV(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_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,n){var s,r,a,o,l,h,c,d;if(!this._isEnabled)return;const u=n.materialDefines,f=this._material.isFrozen,_=u.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;e.useUbo&&f&&e.isSync||(_&&nn.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),zi.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&nn.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",null!==(r=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==r?r:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(d=null===(c=this._textureRoughness)||void 0===c?void 0:c.level)&&void 0!==d?d:0),this._texture&&zi.BindTextureMatrix(this._texture,e,"sheen"),!this._textureRoughness||_||u.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE||zi.BindTextureMatrix(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&&nn.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!_&&!u.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&nn.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){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.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"}]}}}Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Bo.prototype,"isEnabled",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Bo.prototype,"linkSheenWithAlbedo",void 0),Qe([ct()],Bo.prototype,"intensity",void 0),Qe([ut()],Bo.prototype,"color",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Bo.prototype,"texture",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Bo.prototype,"useRoughnessFromMainTexture",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Bo.prototype,"roughness",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Bo.prototype,"textureRoughness",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Bo.prototype,"albedoScaling",void 0);class Uo extends Tt{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_SCATTERING=!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_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_MASK_FROM_THICKNESS_TEXTURE=!1,this.SS_USE_GLTF_TEXTURES=!1}}class ko extends on{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 Uo,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!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=tt.White(),this.tintColorAtDistance=1,this.diffusionDistance=tt.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this._useGltfStyleTextures=!1,this.useGltfStyleTextures=!1,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&nn.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&nn.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return e.SUBSURFACE=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_MASK_FROM_THICKNESS_TEXTURE=!1,void(e.SS_USE_GLTF_TEXTURES=!1);if(e._areTexturesDirty){e.SUBSURFACE=!0,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!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;const i=!!this._thicknessTexture&&!!this._refractionIntensityTexture&&this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._refractionIntensityTexture._texture===this._thicknessTexture._texture,n=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,s=(i||!this._refractionIntensityTexture)&&(n||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&nn.ThicknessTextureEnabled&&zi.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&nn.RefractionIntensityTextureEnabled&&!s&&zi.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&nn.TranslucencyIntensityTextureEnabled&&!s&&zi.PrepareDefinesForMergedUV(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_MASK_FROM_THICKNESS_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture||!!this._translucencyIntensityTexture)&&s,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&s,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&s,this._isRefractionEnabled&&t.texturesEnabled){const i=this._getRefractionTexture(t);i&&nn.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=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,n){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;n.getRenderingMesh().getWorldMatrix().decompose(Ke.Vector3[0]);const s=Math.max(Math.abs(Ke.Vector3[0].x),Math.abs(Ke.Vector3[0].y),Math.abs(Ke.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}bindForSubMesh(e,t,i,n){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const s=n.materialDefines,r=this._material.isFrozen,a=this._material.realTimeFiltering,o=s.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!r||!e.isSync){if(this._thicknessTexture&&nn.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),zi.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&nn.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),zi.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&nn.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),zi.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&nn.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getReflectionTextureMatrix());let t=1;l.isCube||l.depth&&(t=l.depth);const i=l.getSize().width,n=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",l.level,1/n,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),a&&e.updateFloat2("vRefractionFilteringInfo",i,Le.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.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0)}t.texturesEnabled&&(this._thicknessTexture&&nn.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&nn.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&nn.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),l&&nn.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){nn.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!(nn.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture)}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)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.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")}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"}]}}}Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],ko.prototype,"isRefractionEnabled",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],ko.prototype,"isTranslucencyEnabled",void 0),Qe([ct(),ht("_markScenePrePassDirty")],ko.prototype,"isScatteringEnabled",void 0),Qe([ct()],ko.prototype,"_scatteringDiffusionProfileIndex",void 0),Qe([ct()],ko.prototype,"refractionIntensity",void 0),Qe([ct()],ko.prototype,"translucencyIntensity",void 0),Qe([ct()],ko.prototype,"useAlbedoToTintRefraction",void 0),Qe([ct()],ko.prototype,"useAlbedoToTintTranslucency",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],ko.prototype,"thicknessTexture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],ko.prototype,"refractionTexture",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],ko.prototype,"indexOfRefraction",void 0),Qe([ct()],ko.prototype,"_volumeIndexOfRefraction",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],ko.prototype,"volumeIndexOfRefraction",null),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],ko.prototype,"invertRefractionY",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],ko.prototype,"linkRefractionWithTransparency",void 0),Qe([ct()],ko.prototype,"minimumThickness",void 0),Qe([ct()],ko.prototype,"maximumThickness",void 0),Qe([ct()],ko.prototype,"useThicknessAsDepth",void 0),Qe([ut()],ko.prototype,"tintColor",void 0),Qe([ct()],ko.prototype,"tintColorAtDistance",void 0),Qe([ut()],ko.prototype,"diffusionDistance",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],ko.prototype,"useMaskFromThicknessTexture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],ko.prototype,"refractionIntensityTexture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],ko.prototype,"translucencyIntensityTexture",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],ko.prototype,"useGltfStyleTextures",void 0);const Go={effect:null,subMesh:null};class Vo extends Tt{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.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_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=!1,this.TONEMAPPING_ACES=!1,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.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class zo extends Ki{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}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 He(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=zo.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=tt.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new tt(0,0,0),this._albedoColor=new tt(1,1,1),this._reflectivityColor=new tt(1,1,1),this._reflectionColor=new tt(1,1,1),this._emissiveColor=new tt(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=zo.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=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new be(16),this._globalAmbientColor=new tt(0,0,0),this._useLogarithmicDepth=!1,this._unlit=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new yo(this),this.clearCoat=new Do(this),this.iridescence=new Lo(this),this.anisotropy=new Fo(this),this.sheen=new Bo(this),this.subSurface=new ko(this),this.detailMap=new hn(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),nn.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=fr(this.getScene()),this.prePassConfiguration=new Ci}get hasRenderTargetTextures(){return!!(nn.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}get _disableAlphaBlending(){var e;return this._transparencyMode===zo.PBRMATERIAL_OPAQUE||this._transparencyMode===zo.PBRMATERIAL_ALPHATEST||(null===(e=this.subSurface)||void 0===e?void 0:e.disableAlphaBlending)}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){var e;return!!this._forceAlphaTest||!(null===(e=this.subSurface)||void 0===e?void 0:e.disableAlphaBlending)&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===zo.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==zo.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Wi.GetDefineNames,this._eventInfo),t.materialDefines=new Vo(this._eventInfo.defineNames));const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const s=this.getScene(),r=s.getEngine();if(n._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,s.texturesEnabled)){if(this._albedoTexture&&nn.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&nn.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&nn.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&nn.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture&&!e.irradianceTexture.isReadyOrNotBlocking())return!1}if(this._lightmapTexture&&nn.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&nn.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(nn.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(r.getCaps().standardDerivatives&&this._bumpTexture&&nn.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&nn.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;r.getCaps().standardDerivatives||e.isVerticesDataPresent(Lt.NormalKind)||(e.createNormals(!0),c.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const a=t.effect,o=n._areLightsDisposed;let l=this._prepareEffect(e,n,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),h=!1;if(l)if(this._onEffectCreatedObservable&&(Go.effect=l,Go.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Go)),this.allowShaderHotSwapping&&a&&!l.isReady()){if(l=a,n.markAsUnprocessed(),h=this.isFrozen,o)return n._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(l,n,this._materialContext);return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!h,t.effect._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),0))}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,i=null,n=null,s=null,r=null,a){if(this._prepareDefines(e,t,s,r,a),!t.isDirty)return null;t.markAsProcessed();const o=this.getScene().getEngine(),l=new sn;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.PARALLAXOCCLUSION&&l.addFallback(h++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(h++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(h++,"TANGENT"),t.BUMP&&l.addFallback(h++,"BUMP"),h=zi.HandleFallbacksForShadows(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=[Lt.PositionKind];t.NORMAL&&c.push(Lt.NormalKind),t.TANGENT&&c.push(Lt.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&c.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&c.push(Lt.ColorKind),t.INSTANCESCOLOR&&c.push(Lt.ColorInstanceKind),zi.PrepareAttributesForBones(c,e,t,l),zi.PrepareAttributesForInstances(c,t),zi.PrepareAttributesForMorphTargets(c,e,t),zi.PrepareAttributesForBakedVertexAnimation(c,e,t);let d="pbr";const u=["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"],f=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],_=["Material","Scene","Mesh"];this._eventInfo.fallbacks=l,this._eventInfo.fallbackRank=h,this._eventInfo.defines=t,this._eventInfo.uniforms=u,this._eventInfo.attributes=c,this._eventInfo.samplers=f,this._eventInfo.uniformBuffersNames=_,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._callbackPluginEventGeneric(Wi.PrepareEffect,this._eventInfo),Ci.AddUniforms(u),Ci.AddSamplers(f),Bi(u),St&&(St.PrepareUniforms(u,t),St.PrepareSamplers(f,t)),zi.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:_,samplers:f,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const p={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,u,_,f,t,c,p));const m=t.toString(),g=o.createEffect(d,{attributes:c,uniformsNames:u,uniformBuffersNames:_,samplers:f,defines:m,fallbacks:l,onCompiled:i,onError:n,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS},processFinalCode:p.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},o);return this._eventInfo.customCode=void 0,g}_prepareDefines(e,t,i=null,n=null,s=!1){var r;const a=this.getScene(),o=a.getEngine();zi.PrepareDefinesForLights(a,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,zi.PrepareDefinesForMultiview(a,t);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(zi.PrepareDefinesForPrePass(a,t,this.canRenderToMRT&&!l),zi.PrepareDefinesForOIT(a,t,l),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){if(t._needUVs=!1,a.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,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&nn.DiffuseTextureEnabled?(zi.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&nn.AmbientTextureEnabled?(zi.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&nn.OpacityTextureEnabled?(zi.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&nn.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,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===Ji.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 Ji.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case Ji.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case Ji.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case Ji.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case Ji.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case Ji.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Ji.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Ji.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Ji.CUBIC_MODE:case Ji.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==Ji.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||o.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;if(this._lightmapTexture&&nn.LightmapTextureEnabled?(zi.PrepareDefinesForMergedUV(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&nn.EmissiveTextureEnabled?(zi.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,nn.SpecularTextureEnabled){if(this._metallicTexture?(zi.PrepareDefinesForMergedUV(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?(zi.PrepareDefinesForMergedUV(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){const e=null!==this._metallicReflectanceTexture&&this._metallicReflectanceTexture._texture===(null===(r=this._reflectanceTexture)||void 0===r?void 0:r._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!e,this._metallicReflectanceTexture?(zi.PrepareDefinesForMergedUV(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&!e&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(zi.PrepareDefinesForMergedUV(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?zi.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;o.getCaps().standardDerivatives&&this._bumpTexture&&nn.BumpTextureEnabled&&!this._disableBumpMap?(zi.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&nn.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&nn.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===zo.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===zo.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=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,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&&(zi.PrepareDefinesForMisc(e,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(Lt.NormalKind),t.DEBUGMODE=this._debugMode),zi.PrepareDefinesForFrameBoundValues(a,o,this,t,!!i,n,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),zi.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==zo.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const n={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(Wi.GetDefineNames,this._eventInfo);const s=new Vo(this._eventInfo.defineNames),r=this._prepareEffect(e,s,void 0,void 0,n.useInstances,n.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(Go.effect=r,Go.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Go)),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){var n,s,r,a;const o=this.getScene(),l=i.materialDefines;if(!l)return;const h=i.effect;if(!h)return;this._activeEffect=h,t.getMeshUniformBuffer().bindToEffect(h,"Mesh"),t.transferToEffect(e);const c=o.getEngine();this._uniformBuffer.bindToEffect(h,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,o,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),l.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const d=h._forceRebindOnNextCall||this._mustRebind(o,h,t.visibility);zi.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let u=null;const f=this._uniformBuffer;if(d){if(this.bindViewProjection(h),u=this._getReflectionTexture(),!f.useUbo||!this.isFrozen||!f.isSync||h._forceRebindOnNextCall){if(o.texturesEnabled){if(this._albedoTexture&&nn.DiffuseTextureEnabled&&(f.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),zi.BindTextureMatrix(this._albedoTexture,f,"albedo")),this._ambientTexture&&nn.AmbientTextureEnabled&&(f.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),zi.BindTextureMatrix(this._ambientTexture,f,"ambient")),this._opacityTexture&&nn.OpacityTextureEnabled&&(f.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),zi.BindTextureMatrix(this._opacityTexture,f,"opacity")),u&&nn.ReflectionTextureEnabled){if(f.updateMatrix("reflectionMatrix",u.getReflectionTextureMatrix()),f.updateFloat2("vReflectionInfos",u.level,0),u.boundingBoxSize){const e=u;f.updateVector3("vReflectionPosition",e.boundingBoxPosition),f.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=u.getSize().width;f.updateFloat2("vReflectionFilteringInfo",e,Le.Log2(e))}if(!l.USEIRRADIANCEMAP){const e=u.sphericalPolynomial;if(l.USESPHERICALFROMREFLECTIONMAP&&e)if(l.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;f.updateVector3("vSphericalL00",t.l00),f.updateVector3("vSphericalL1_1",t.l1_1),f.updateVector3("vSphericalL10",t.l10),f.updateVector3("vSphericalL11",t.l11),f.updateVector3("vSphericalL2_2",t.l2_2),f.updateVector3("vSphericalL2_1",t.l2_1),f.updateVector3("vSphericalL20",t.l20),f.updateVector3("vSphericalL21",t.l21),f.updateVector3("vSphericalL22",t.l22)}else f.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),f.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),f.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),f.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),f.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),f.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),f.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),f.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),f.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}f.updateFloat3("vReflectionMicrosurfaceInfos",u.getSize().width,u.lodGenerationScale,u.lodGenerationOffset)}this._emissiveTexture&&nn.EmissiveTextureEnabled&&(f.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),zi.BindTextureMatrix(this._emissiveTexture,f,"emissive")),this._lightmapTexture&&nn.LightmapTextureEnabled&&(f.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),zi.BindTextureMatrix(this._lightmapTexture,f,"lightmap")),nn.SpecularTextureEnabled&&(this._metallicTexture?(f.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),zi.BindTextureMatrix(this._metallicTexture,f,"reflectivity")):this._reflectivityTexture&&(f.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),zi.BindTextureMatrix(this._reflectivityTexture,f,"reflectivity")),this._metallicReflectanceTexture&&(f.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),zi.BindTextureMatrix(this._metallicReflectanceTexture,f,"metallicReflectance")),this._reflectanceTexture&&l.REFLECTANCE&&(f.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),zi.BindTextureMatrix(this._reflectanceTexture,f,"reflectance")),this._microSurfaceTexture&&(f.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),zi.BindTextureMatrix(this._microSurfaceTexture,f,"microSurfaceSampler"))),this._bumpTexture&&c.getCaps().standardDerivatives&&nn.BumpTextureEnabled&&!this._disableBumpMap&&(f.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),zi.BindTextureMatrix(this._bumpTexture,f,"bump"),o._mirroredCameraPosition?f.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):f.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&f.updateFloat("pointSize",this.pointSize),l.METALLICWORKFLOW){nt.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,nt.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,f.updateColor4("vReflectivityColor",nt.Color3[0],1);const e=null!==(s=null===(n=this.subSurface)||void 0===n?void 0:n._indexOfRefraction)&&void 0!==s?s:1.5,t=1,i=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(i*this._metallicF0Factor,nt.Color3[0]);const r=this._metallicF0Factor;f.updateColor4("vMetallicReflectanceFactors",nt.Color3[0],r)}else f.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);f.updateColor3("vEmissiveColor",nn.EmissiveTextureEnabled?this._emissiveColor:tt.BlackReadOnly),f.updateColor3("vReflectionColor",this._reflectionColor),!l.SS_REFRACTION&&(null===(r=this.subSurface)||void 0===r?void 0:r._linkRefractionWithTransparency)?f.updateColor4("vAlbedoColor",this._albedoColor,1):f.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*o.environmentIntensity,this._lightingInfos.w=this._specularIntensity,f.updateVector4("vLightingIntensity",this._lightingInfos),o.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),f.updateColor3("vAmbientColor",this._globalAmbientColor),f.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}o.texturesEnabled&&(this._albedoTexture&&nn.DiffuseTextureEnabled&&f.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&nn.AmbientTextureEnabled&&f.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&nn.OpacityTextureEnabled&&f.setTexture("opacitySampler",this._opacityTexture),u&&nn.ReflectionTextureEnabled&&(l.LODBASEDMICROSFURACE?f.setTexture("reflectionSampler",u):(f.setTexture("reflectionSampler",u._lodTextureMid||u),f.setTexture("reflectionSamplerLow",u._lodTextureLow||u),f.setTexture("reflectionSamplerHigh",u._lodTextureHigh||u)),l.USEIRRADIANCEMAP&&f.setTexture("irradianceSampler",u.irradianceTexture)),l.ENVIRONMENTBRDF&&f.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&nn.EmissiveTextureEnabled&&f.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&nn.LightmapTextureEnabled&&f.setTexture("lightmapSampler",this._lightmapTexture),nn.SpecularTextureEnabled&&(this._metallicTexture?f.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&f.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&f.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&l.REFLECTANCE&&f.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&f.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&c.getCaps().standardDerivatives&&nn.BumpTextureEnabled&&!this._disableBumpMap&&f.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(h),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),ki(this._activeEffect,this,o),this.bindEyePosition(h)}else o.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!d&&this.isFrozen||(o.lightsEnabled&&!this._disableLighting&&zi.BindLights(o,t,this._activeEffect,l,this._maxSimultaneousLights),(o.fogEnabled&&t.applyFog&&o.fogMode!==pi.FOGMODE_NONE||u||t.receiveShadows||l.PREPASS)&&this.bindView(h),zi.BindFogParameters(o,t,this._activeEffect,!0),l.NUM_MORPH_INFLUENCERS&&zi.BindMorphTargetParameters(t,this._activeEffect),l.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(a=t.bakedVertexAnimationManager)||void 0===a||a.bind(h,l.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),zi.BindLogDepth(l,this._activeEffect,o)),this._afterBind(t,this._activeEffect),f.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(){var e;if(!(null===(e=this.subSurface)||void 0===e?void 0:e.isScatteringEnabled))return!1;const t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0}dispose(e,t){var i,n,s,r,a,o,l,h,c,d,u,f;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),null===(i=this._albedoTexture)||void 0===i||i.dispose(),null===(n=this._ambientTexture)||void 0===n||n.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(r=this._reflectionTexture)||void 0===r||r.dispose(),null===(a=this._emissiveTexture)||void 0===a||a.dispose(),null===(o=this._metallicTexture)||void 0===o||o.dispose(),null===(l=this._reflectivityTexture)||void 0===l||l.dispose(),null===(h=this._bumpTexture)||void 0===h||h.dispose(),null===(c=this._lightmapTexture)||void 0===c||c.dispose(),null===(d=this._metallicReflectanceTexture)||void 0===d||d.dispose(),null===(u=this._reflectanceTexture)||void 0===u||u.dispose(),null===(f=this._microSurfaceTexture)||void 0===f||f.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}zo.PBRMATERIAL_OPAQUE=Yi.MATERIAL_OPAQUE,zo.PBRMATERIAL_ALPHATEST=Yi.MATERIAL_ALPHATEST,zo.PBRMATERIAL_ALPHABLEND=Yi.MATERIAL_ALPHABLEND,zo.PBRMATERIAL_ALPHATESTANDBLEND=Yi.MATERIAL_ALPHATESTANDBLEND,zo.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,zo.LIGHTFALLOFF_PHYSICAL=0,zo.LIGHTFALLOFF_GLTF=1,zo.LIGHTFALLOFF_STANDARD=2,Qe([lt(9,void 0)],zo.prototype,"_imageProcessingConfiguration",void 0),Qe([ht("_markAllSubMeshesAsMiscDirty")],zo.prototype,"debugMode",void 0),Qe([ct()],zo.prototype,"useLogarithmicDepth",null);class Ho extends zo{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===zo.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?zo.LIGHTFALLOFF_PHYSICAL:zo.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===zo.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?zo.LIGHTFALLOFF_GLTF:zo.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=Ho.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=tt.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new tt(0,0,0),this.albedoColor=new tt(1,1,1),this.reflectivityColor=new tt(1,1,1),this.reflectionColor=new tt(1,1,1),this.emissiveColor=new tt(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._environmentBRDFTexture=fr(this.getScene())}getClassName(){return"PBRMaterial"}clone(e){const t=gt.Clone((()=>new Ho(e,this.getScene())),this);return t.id=e,t.name=e,this.stencil.copyTo(t.stencil),this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),this.iridescence.copyTo(t.iridescence),t}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const n=gt.Parse((()=>new Ho(e.name,t)),e,t,i);return e.stencil&&n.stencil.parse(e.stencil,t,i),e.clearCoat&&n.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&n.anisotropy.parse(e.anisotropy,t,i),e.brdf&&n.brdf.parse(e.brdf,t,i),e.sheen&&n.sheen.parse(e.sheen,t,i),e.subSurface&&n.subSurface.parse(e.subSurface,t,i),e.iridescence&&n.iridescence.parse(e.iridescence,t,i),n}}function Wo(e,t,i,n){return ze.FromArray(t,i).scaleInPlace(n)}Ho.PBRMATERIAL_OPAQUE=zo.PBRMATERIAL_OPAQUE,Ho.PBRMATERIAL_ALPHATEST=zo.PBRMATERIAL_ALPHATEST,Ho.PBRMATERIAL_ALPHABLEND=zo.PBRMATERIAL_ALPHABLEND,Ho.PBRMATERIAL_ALPHATESTANDBLEND=zo.PBRMATERIAL_ALPHATESTANDBLEND,Ho.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=zo.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"directIntensity",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"emissiveIntensity",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"environmentIntensity",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"specularIntensity",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"disableBumpMap",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"albedoTexture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"ambientTexture",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"ambientTextureStrength",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesAndMiscDirty")],Ho.prototype,"opacityTexture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"reflectionTexture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"emissiveTexture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"reflectivityTexture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"metallicTexture",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"metallic",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"roughness",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"metallicF0Factor",void 0),Qe([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"metallicReflectanceColor",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"metallicReflectanceTexture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"reflectanceTexture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"microSurfaceTexture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"bumpTexture",void 0),Qe([dt(),ht("_markAllSubMeshesAsTexturesDirty",null)],Ho.prototype,"lightmapTexture",void 0),Qe([ut("ambient"),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"ambientColor",void 0),Qe([ut("albedo"),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"albedoColor",void 0),Qe([ut("reflectivity"),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"reflectivityColor",void 0),Qe([ut("reflection"),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"reflectionColor",void 0),Qe([ut("emissive"),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"emissiveColor",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"microSurface",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useLightmapAsShadowmap",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesAndMiscDirty")],Ho.prototype,"useAlphaFromAlbedoTexture",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesAndMiscDirty")],Ho.prototype,"forceAlphaTest",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesAndMiscDirty")],Ho.prototype,"alphaCutOff",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useSpecularOverAlpha",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useRoughnessFromMetallicTextureGreen",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useMetallnessFromMetallicTextureBlue",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useAmbientInGrayScale",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),Qe([ct()],Ho.prototype,"usePhysicalLightFalloff",null),Qe([ct()],Ho.prototype,"useGLTFLightFalloff",null),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useRadianceOverAlpha",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useObjectSpaceNormalMap",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useParallax",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useParallaxOcclusion",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"parallaxScaleBias",void 0),Qe([ct(),ht("_markAllSubMeshesAsLightsDirty")],Ho.prototype,"disableLighting",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"forceIrradianceInFragment",void 0),Qe([ct(),ht("_markAllSubMeshesAsLightsDirty")],Ho.prototype,"maxSimultaneousLights",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"invertNormalMapX",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"invertNormalMapY",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"twoSidedLighting",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useAlphaFresnel",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useLinearAlphaFresnel",void 0),Qe([ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"environmentBRDFTexture",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"forceNormalForward",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"enableSpecularAntiAliasing",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useHorizonOcclusion",void 0),Qe([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useRadianceOcclusion",void 0),Qe([ct(),ht("_markAllSubMeshesAsMiscDirty")],Ho.prototype,"unlit",void 0),Se("BABYLON.PBRMaterial",Ho);class Xo{constructor(e,t,i,n){this.type=e,this.name=t,this.getValue=i,this.getStride=n}_buildAnimation(e,t,i){const n=new Mr(e,this.name,t,this.type);return n.setKeys(i),n}}class Yo extends Xo{buildAnimations(e,t,i,n,s){s(e._babylonTransformNode,this._buildAnimation(t,i,n))}}const Ko={translation:[new Yo(Mr.ANIMATIONTYPE_VECTOR3,"position",Wo,(()=>3))],rotation:[new Yo(Mr.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",(function(e,t,i,n){return We.FromArray(t,i).scaleInPlace(n)}),(()=>4))],scale:[new Yo(Mr.ANIMATIONTYPE_VECTOR3,"scaling",Wo,(()=>3))],weights:[new class extends Xo{buildAnimations(e,t,i,n,s){if(e._numMorphTargets)for(let r=0;r({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),s(e,i)}}}}(Mr.ANIMATIONTYPE_FLOAT,"influence",(function(e,t,i,n){const s=new Array(e._numMorphTargets);for(let e=0;ee._numMorphTargets))]};function jo(...e){const t=e=>e&&"object"==typeof e;return e.reduce(((e,i)=>(Object.keys(i).forEach((n=>{const s=e[n],r=i[n];Array.isArray(s)&&Array.isArray(r)?e[n]=s.concat(...r):t(s)&&t(r)?e[n]=jo(s,r):e[n]=r})),e)),{})}class qo{static Get(e,t,i){if(!t||null==i||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static Assign(e){if(e)for(let t=0;te.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,n,s,r,a=""){return Promise.resolve().then((()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(n);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(s,a,r,(()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries()})))}))}loadAsync(e,t,i,n,s=""){return Promise.resolve().then((()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,s,null,(()=>{})))))}_loadAsync(e,t,i,n){return Promise.resolve().then((()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._loadExtensions(),this._checkExtensions();const s=`${Ba[Ba.LOADING]} => ${Ba[Ba.READY]}`,r=`${Ba[Ba.LOADING]} => ${Ba[Ba.COMPLETE]}`;this._parent._startPerformanceCounter(s),this._parent._startPerformanceCounter(r),this._parent._setState(Ba.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=qo.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{})))}return this._babylonScene.blockMaterialDirtyMechanism=o,this._parent.compileMaterials&&a.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&a.push(this._compileShadowGeneratorsAsync()),Promise.all(a).then((()=>(this._rootBabylonMesh&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(Ba.READY),this._startAnimations(),n()))).then((e=>(this._parent._endPerformanceCounter(s),Me.SetImmediate((()=>{this._disposed||Promise.all(this._completePromises).then((()=>{this._parent._endPerformanceCounter(r),this._parent._setState(Ba.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.byteLengthe.bin.byteLength)&&c.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else c.Warn("Unexpected BIN chunk")}}_setupData(){if(qo.Assign(this._gltf.accessors),qo.Assign(this._gltf.animations),qo.Assign(this._gltf.buffers),qo.Assign(this._gltf.bufferViews),qo.Assign(this._gltf.cameras),qo.Assign(this._gltf.images),qo.Assign(this._gltf.materials),qo.Assign(this._gltf.meshes),qo.Assign(this._gltf.nodes),qo.Assign(this._gltf.samplers),qo.Assign(this._gltf.scenes),qo.Assign(this._gltf.skins),qo.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 n=e[i.index];i.parent=void 0===n?t:this._gltf.nodes[n]}}}_loadExtensions(){for(const e in Qo._RegisteredExtensions){const t=Qo._RegisteredExtensions[e].factory(this);t.name!==e&&c.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(`Require extension ${e} is not available`)}_createRootNode(){this._babylonScene._blockEntityCollection=!!this._assetContainer,this._rootBabylonMesh=new Ks("__root__",this._babylonScene),this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const e={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case Fa.AUTO:this._babylonScene.useRightHandedSystem||(e.rotation=[0,1,0,0],e.scale=[1,1,-1],Qo._LoadTransform(e,this._rootBabylonMesh));break;case Fa.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh),e}loadSceneAsync(e,t){const i=this._extensionsLoadSceneAsync(e,t);if(i)return i;const n=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const i of t.nodes){const t=qo.Get(`${e}/nodes/${i}`,this._gltf.nodes,i);n.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=this._rootBabylonMesh})))}for(const e of this._postSceneLoadActions)e();return n.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(n).then((()=>{}))}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){const e=new Array,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=new Array;this._rootBabylonMesh&&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=new Array,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=new Array,t=this._gltf.skins;if(t)for(const i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){const e=new Array,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 wa.NONE:break;case wa.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case wa.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void c.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,t,i=(()=>{})){const n=this._extensionsLoadNodeAsync(e,t,i);if(n)return n;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const s=new Array;this.logOpen(`${e} ${t.name||""}`);const r=n=>{if(Qo.AddPointerMetadata(n,e),Qo._LoadTransform(t,n),null!=t.camera){const i=qo.Get(`${e}/camera`,this._gltf.cameras,t.camera);s.push(this.loadCameraAsync(`/cameras/${i.index}`,i,(e=>{e.parent=n})))}if(t.children)for(const i of t.children){const t=qo.Get(`${e}/children/${i}`,this._gltf.nodes,i);s.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=n})))}i(n)};if(null==t.mesh||null!=t.skin){const e=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new ws(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=qo.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,r))}else{const i=qo.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,(i=>{const n=t._babylonTransformNodeForSkin;i.metadata=jo(n.metadata,i.metadata||{});const r=qo.Get(`${e}/skin`,this._gltf.skins,t.skin);s.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=qo.Get(`/skins/${r.index}/skeleton`,this._gltf.nodes,r.skeleton).parent;t.index===e.index?i.parent=n.parent:i.parent=e._babylonTransformNode}else i.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:n,skinnedNode:i})}))})))})))}return this.logClose(),Promise.all(s).then((()=>(this._forEachPrimitive(t,(e=>{e.geometry&&e.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0)})),t._babylonTransformNode)))}_loadMeshAsync(e,t,i,n){const s=i.primitives;if(!s||!s.length)throw new Error(`${e}: Primitives are missing`);null==s[0].index&&qo.Assign(s);const r=new Array;this.logOpen(`${e} ${i.name||""}`);const a=t.name||`node${t.index}`;if(1===s.length){const n=i.primitives[0];r.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${n.index}`,a,t,i,n,(e=>{t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]})))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new ws(a,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const n of s)r.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${n.index}`,`${a}_primitive${n.index}`,t,i,n,(e=>{e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)})))}return n(t._babylonTransformNode),this.logClose(),Promise.all(r).then((()=>t._babylonTransformNode))}_loadMeshPrimitiveAsync(e,t,i,n,s,r){const a=this._extensionsLoadMeshPrimitiveAsync(e,t,i,n,s,r);if(a)return a;this.logOpen(`${e}`);const o=0===this._disableInstancedMesh&&this._parent.createInstances&&null==i.skin&&!n.primitives[0].targets;let l,h;if(o&&s._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,l=s._instanceData.babylonSourceMesh.createInstance(t),l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,h=s._instanceData.promise;else{const r=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new Ks(t,this._babylonScene);a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?Yi.CounterClockWiseSideOrientation:Yi.ClockWiseSideOrientation,this._createMorphTargets(e,i,n,s,a),r.push(this._loadVertexDataAsync(e,s,a).then((t=>this._loadMorphTargetsAsync(e,s,a,t).then((()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(a),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})))));const c=Qo._GetDrawMode(e,s.mode);if(null==s.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=qo.Get(`${e}/material`,this._gltf.materials,s.material);r.push(this._loadMaterialAsync(`/materials/${t.index}`,t,a,c,(e=>{a.material=e})))}h=Promise.all(r),o&&(s._instanceData={babylonSourceMesh:a,promise:h}),l=a}return Qo.AddPointerMetadata(l,e),this._parent.onMeshLoadedObservable.notifyObservers(l),r(l),this.logClose(),h.then((()=>l))}_loadVertexDataAsync(e,t,i){const n=this._extensionsLoadVertexDataAsync(e,t,i);if(n)return n;const s=t.attributes;if(!s)throw new Error(`${e}: Attributes are missing`);const r=new Array,a=new Fs(i.name,this._babylonScene);if(null==t.indices)i.isUnIndexed=!0;else{const i=qo.Get(`${e}/indices`,this._gltf.accessors,t.indices);r.push(this._loadIndicesAccessorAsync(`/accessors/${i.index}`,i).then((e=>{a.setIndices(e)})))}const o=(t,n,o)=>{if(null==s[t])return;i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(n)&&i._delayInfo.push(n);const l=qo.Get(`${e}/attributes/${t}`,this._gltf.accessors,s[t]);r.push(this._loadVertexAccessorAsync(`/accessors/${l.index}`,l,n).then((e=>{if(e.getKind()===Lt.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton){const e=l.min,t=l.max;if(void 0!==e&&void 0!==t){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}for(let n=0;n<3;++n)e[n]=Math.max(e[n]/i,-1),t[n]=Math.max(t[n]/i,-1)}const i=Ke.Vector3[0],n=Ke.Vector3[1];i.copyFromFloats(...e),n.copyFromFloats(...t),a._boundingInfo=new Oi(i,n),a.useBoundingInfoFromGeometry=!0}}a.setVerticesBuffer(e,l.count)}))),n==Lt.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),o&&o(l)};return o("POSITION",Lt.PositionKind),o("NORMAL",Lt.NormalKind),o("TANGENT",Lt.TangentKind),o("TEXCOORD_0",Lt.UVKind),o("TEXCOORD_1",Lt.UV2Kind),o("TEXCOORD_2",Lt.UV3Kind),o("TEXCOORD_3",Lt.UV4Kind),o("TEXCOORD_4",Lt.UV5Kind),o("TEXCOORD_5",Lt.UV6Kind),o("JOINTS_0",Lt.MatricesIndicesKind),o("WEIGHTS_0",Lt.MatricesWeightsKind),o("JOINTS_1",Lt.MatricesIndicesExtraKind),o("WEIGHTS_1",Lt.MatricesWeightsExtraKind),o("COLOR_0",Lt.ColorKind,(e=>{"VEC4"===e.type&&(i.hasVertexAlpha=!0)})),Promise.all(r).then((()=>a))}_createMorphTargets(e,t,i,n,s){if(!n.targets)return;if(null==t._numMorphTargets)t._numMorphTargets=n.targets.length;else if(n.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,s.morphTargetManager=new Hr(this._babylonScene),s.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e{r.areUpdatesFrozen=!1}))}_loadMorphTargetVertexDataAsync(e,t,i,n){const s=new Array,r=(n,r,a)=>{if(null==i[n])return;const o=t.getVertexBuffer(r);if(!o)return;const l=qo.Get(`${e}/${n}`,this._gltf.accessors,i[n]);s.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then((e=>{a(o,e)})))};return r("POSITION",Lt.PositionKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(t.length,((e,n)=>{i[n]=t[n]+e})),n.setPositions(i)})),r("NORMAL",Lt.NormalKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(i.length,((e,n)=>{i[n]=t[n]+e})),n.setNormals(i)})),r("TANGENT",Lt.TangentKind,((e,t)=>{const i=new Float32Array(t.length/3*4);let s=0;e.forEach(t.length/3*4,((e,n)=>{(n+1)%4!=0&&(i[s]=t[s]+e,s++)})),n.setTangents(i)})),Promise.all(s).then((()=>{}))}static _LoadTransform(e,t){if(null!=e.skin)return;let i=ze.Zero(),n=We.Identity(),s=ze.One();e.matrix?Xe.FromArray(e.matrix).decompose(s,n,i):(e.translation&&(i=ze.FromArray(e.translation)),e.rotation&&(n=We.FromArray(e.rotation)),e.scale&&(s=ze.FromArray(e.scale))),t.position=i,t.rotationQuaternion=n,t.scaling=s}_loadSkinAsync(e,t,i,n){const s=this._extensionsLoadSkinAsync(e,t,i);if(s)return s;if(i._data)return n(i._data.babylonSkeleton),i._data.promise;const r=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new Ir(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},n(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 n=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},s=qo.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);s===i||n(s,i)||(c.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=i.index)}else c.Warn(`${e}: Failed to find common root`)}const n={};for(const s of t.joints){const r=qo.Get(`${e}/joints/${s}`,this._gltf.nodes,s);this._loadBone(r,t,i,n)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const i={};for(const n of t){const t=new Array;let s=qo.Get(`${e}/${n}`,this._gltf.nodes,n);for(;-1!==s.index;)t.unshift(s),s=s.parent;i[n]=t}let n=null;for(let e=0;;++e){let s=i[t[0]];if(e>=s.length)return n;const r=s[e];for(let a=1;a=s.length||r!==s[e])return n;n=r}}_loadBone(e,t,i,n){let s=n[e.index];if(s)return s;let r=null;e.index!==t.skeleton&&(e.parent&&-1!==e.parent.index?r=this._loadBone(e.parent,t,i,n):void 0!==t.skeleton&&c.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const a=t.joints.indexOf(e.index);return s=new vr(e.name||`joint${e.index}`,i,r,this._getNodeMatrix(e),null,null,a),n[e.index]=s,this._postSceneLoadActions.push((()=>{s.linkTransformNode(e._babylonTransformNode)})),s}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const i=qo.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=Xe.Identity(),n=i._index;t&&-1!==n&&(Xe.FromArrayToRef(t,16*n,e),e.invertToRef(e));const s=i.getParent();s&&e.multiplyToRef(s.getInvertedAbsoluteTransform(),e),i.updateMatrix(e,!1,!1),i._updateDifferenceMatrix(void 0,!1)}}_getNodeMatrix(e){return e.matrix?Xe.FromArray(e.matrix):Xe.Compose(e.scale?ze.FromArray(e.scale):ze.One(),e.rotation?We.FromArray(e.rotation):We.Identity(),e.translation?ze.FromArray(e.translation):ze.Zero())}loadCameraAsync(e,t,i=(()=>{})){const n=this._extensionsLoadCameraAsync(e,t,i);if(n)return n;const s=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const r=new Sa(t.name||`camera${t.index}`,ze.Zero(),this._babylonScene,!1);switch(r._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.ignoreParentScaling=!0,t._babylonCamera=r,r.rotation=new ze(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=wi.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 Qo.AddPointerMetadata(r,e),this._parent.onCameraLoadedObservable.notifyObservers(r),i(r),this.logClose(),Promise.all(s).then((()=>r))}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i{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 n=new Io(t.name||`animation${t.index}`,this._babylonScene);n._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=n;const s=new Array;qo.Assign(t.channels),qo.Assign(t.samplers);for(const i of t.channels)s.push(this._loadAnimationChannelAsync(`${e}/channels/${i.index}`,e,t,i,((e,t)=>{e.animations=e.animations||[],e.animations.push(t),n.addTargetedAnimation(t,e)})));return Promise.all(s).then((()=>(n.normalize(0),n)))}_loadAnimationChannelAsync(e,t,i,n,s){const r=this._extensionsLoadAnimationChannelAsync(e,t,i,n,s);if(r)return r;if(null==n.target.node)return Promise.resolve();const a=qo.Get(`${e}/target/node`,this._gltf.nodes,n.target.node);if("weights"===n.target.path&&!a._numMorphTargets||"weights"!==n.target.path&&!a._babylonTransformNode)return Promise.resolve();let o;switch(n.target.path){case"translation":o=Ko.translation;break;case"rotation":o=Ko.rotation;break;case"scale":o=Ko.scale;break;case"weights":o=Ko.weights;break;default:throw new Error(`${e}/target/path: Invalid value (${n.target.path})`)}const l={target:a,properties:o};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,n,l,s)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,n,s,r){const a=this.parent.targetFps,o=1/a,l=qo.Get(`${e}/sampler`,i.samplers,n.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${n.sampler}`,l).then((e=>{let t=0;for(const l of s.properties){const h=l.getStride(s.target),c=e.input,d=e.output,u=new Array(c.length);let f=0;switch(e.interpolation){case"STEP":for(let e=0;e0){const e=`${i.name||`animation${i.index}`}_channel${n.index}_${t}`;l.buildAnimations(s.target,e,a,u,((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 n=qo.Get(`${e}/input`,this._gltf.accessors,t.input),s=qo.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${n.index}`,n),this._loadFloatAccessorAsync(`/accessors/${s.index}`,s)]).then((([e,t])=>({input:e,interpolation:i,output:t}))),t._data}loadBufferAsync(e,t,i,n){const s=this._extensionsLoadBufferAsync(e,t,i,n);if(s)return s;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,n)}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 n=qo.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${n.index}`,n,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;const n=Qo._GetNumComponents(e,t.type),s=n*Lt.GetTypeByteLength(t.componentType),r=n*t.count;if(null==t.bufferView)t._data=Promise.resolve(new i(r));else{const a=qo.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!==s){const e=new i(r);return Lt.ForEach(o,t.byteOffset||0,a.byteStride||s,n,t.componentType,e.length,t.normalized||!1,((t,i)=>{e[i]=t})),e}return Qo._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=qo.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,r.indices.bufferView),h=qo.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=Qo._GetTypedArray(`${e}/sparse/indices`,r.indices.componentType,a,r.indices.byteOffset,r.count),c=n*r.count;let d;if(5126!==t.componentType||t.normalized){const a=Qo._GetTypedArray(`${e}/sparse/values`,t.componentType,l,r.values.byteOffset,c);d=new i(c),Lt.ForEach(a,0,s,n,t.componentType,d.length,t.normalized||!1,((e,t)=>{d[t]=e}))}else d=Qo._GetTypedArray(`${e}/sparse/values`,t.componentType,l,r.values.byteOffset,c);let u=0;for(let e=0;eQo._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 Ot(t,e,!1))),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){var n;if(null===(n=t._babylonVertexBuffer)||void 0===n?void 0:n[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const s=this._babylonScene.getEngine();if(t.sparse)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new Lt(s,e,i,!1)));else if(i===Lt.MatricesIndicesKind||i===Lt.MatricesIndicesExtraKind)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new Lt(s,e,i,!1)));else{const n=qo.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(n).then((r=>{const a=Qo._GetNumComponents(e,t.type);return new Lt(s,r,i,!1,!1,n.byteStride,!1,t.byteOffset,a,t.componentType,t.normalized,!0,1,!0)}))}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof Ho))throw new Error(`${e}: Material type not supported`);const n=new Array;return t&&(t.baseColorFactor?(i.albedoColor=tt.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=tt.White(),i.metallic=null==t.metallicFactor?1:t.metallicFactor,i.roughness=null==t.roughnessFactor?1:t.roughnessFactor,t.baseColorTexture&&n.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e}))),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,n.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(n).then((()=>{}))}_loadMaterialAsync(e,t,i,n,s=(()=>{})){const r=this._extensionsLoadMaterialAsync(e,t,i,n,s);if(r)return r;t._data=t._data||{};let a=t._data[n];if(!a){this.logOpen(`${e} ${t.name||""}`);const i=this.createMaterial(e,t,n);a={babylonMaterial:i,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,i)},t._data[n]=a,Qo.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)}))),s(a.babylonMaterial),a.promise.then((()=>a.babylonMaterial))}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Ho(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=Ho.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const n=this._extensionsCreateMaterial(e,t,i);if(n)return n;const s=t.name||`material${t.index}`;return this._createDefaultMaterial(s,i)}loadMaterialPropertiesAsync(e,t,i){const n=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(n)return n;const s=new Array;return s.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&s.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then((()=>{}))}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof Ho))throw new Error(`${e}: Material type not supported`);const n=new Array;return i.emissiveColor=t.emissiveFactor?tt.FromArray(t.emissiveFactor):new tt(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,n.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,n.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&&n.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,(e=>{e.name=`${i.name} (Emissive)`,i.emissiveTexture=e}))),Promise.all(n).then((()=>{}))}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof Ho))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":i.transparencyMode=Ho.PBRMATERIAL_OPAQUE;break;case"MASK":i.transparencyMode=Ho.PBRMATERIAL_ALPHATEST,i.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break;case"BLEND":i.transparencyMode=Ho.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 n=this._extensionsLoadTextureInfoAsync(e,t,i);if(n)return n;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const s=qo.Get(`${e}/index`,this._gltf.textures,t.index);s._textureInfo=t;const r=this._loadTextureAsync(`/textures/${t.index}`,s,(n=>{n.coordinatesIndex=t.texCoord||0,Qo.AddPointerMetadata(n,e),this._parent.onTextureLoadedObservable.notifyObservers(n),i(n)}));return this.logClose(),r}_loadTextureAsync(e,t,i=(()=>{})){const n=this._extensionsLoadTextureAsync(e,t,i);if(n)return n;this.logOpen(`${e} ${t.name||""}`);const s=null==t.sampler?Qo.DefaultSampler:qo.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),r=qo.Get(`${e}/source`,this._gltf.images,t.source),a=this._createTextureAsync(e,s,r,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),a}_createTextureAsync(e,t,i,n=(()=>{}),s,r){const a=this._loadSampler(`/samplers/${t.index}`,t),o=new Array,l=new xs;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:s,useSRGBBuffer:!!r&&this._parent.useSRGBBuffers},c=new Ji(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}`,n=`data:${this._uniqueRootUrl}${t}`;c.updateURL(n,e)}))),c.wrapU=a.wrapU,c.wrapV=a.wrapV,n(c),Promise.all(o).then((()=>c))}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:Qo._GetTextureSamplingMode(e,t),wrapU:Qo._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:Qo._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=qo.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 n=this._extensionsLoadUriAsync(e,t,i);if(n)return n;if(!Qo._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(me(i)){const t=new Uint8Array(Ee(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(((n,s)=>{this._parent._loadFile(this._babylonScene,t,(t=>{this._disposed||(this.log(`${e}: Loaded ${i} (${t.byteLength} bytes)`),n(new Uint8Array(t)))}),!0,(t=>{s(new re(`${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||{},n=i.gltf=i.gltf||{};(n.pointers=n.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=null==t?10497:t){case 33071:return Ji.CLAMP_ADDRESSMODE;case 33648:return Ji.MIRROR_ADDRESSMODE;case 10497:return Ji.WRAP_ADDRESSMODE;default:return c.Warn(`${e}: Invalid value (${t})`),Ji.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=null==t.magFilter?9729:t.magFilter,n=null==t.minFilter?9987:t.minFilter;if(9729===i)switch(n){case 9728:return Ji.LINEAR_NEAREST;case 9729:return Ji.LINEAR_LINEAR;case 9984:return Ji.LINEAR_NEAREST_MIPNEAREST;case 9985:return Ji.LINEAR_LINEAR_MIPNEAREST;case 9986:return Ji.LINEAR_NEAREST_MIPLINEAR;case 9987:return Ji.LINEAR_LINEAR_MIPLINEAR;default:return c.Warn(`${e}/minFilter: Invalid value (${n})`),Ji.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==i&&c.Warn(`${e}/magFilter: Invalid value (${i})`),n){case 9728:return Ji.NEAREST_NEAREST;case 9729:return Ji.NEAREST_LINEAR;case 9984:return Ji.NEAREST_NEAREST_MIPNEAREST;case 9985:return Ji.NEAREST_LINEAR_MIPNEAREST;case 9986:return Ji.NEAREST_NEAREST_MIPLINEAR;case 9987:return Ji.NEAREST_LINEAR_MIPLINEAR;default:return c.Warn(`${e}/minFilter: Invalid value (${n})`),Ji.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,n,s){const r=i.buffer;n=i.byteOffset+(n||0);const a=Qo._GetTypedArrayConstructor(`${e}/componentType`,t),o=Lt.GetTypeByteLength(t);return n%o!=0?(c.Warn(`${e}: Copying buffer as byte offset (${n}) is not a multiple of component type byte length (${o})`),new a(r.slice(n,n+s*o),0)):new a(r,n,s)}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 Me.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,t){switch(null==t&&(t=4),t){case 0:return Yi.PointListDrawMode;case 1:return Yi.LineListDrawMode;case 2:return Yi.LineLoopDrawMode;case 3:return Yi.LineStripDrawMode;case 4:return Yi.TriangleFillMode;case 5:return Yi.TriangleStripDrawMode;case 6:return Yi.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 n=t._data[i];for(const t of n.babylonMeshes){t.computeWorldMatrix(!0);const i=n.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 n of this._extensions)if(n.enabled){const s=`${n.name}.${t}`,r=e;r._activeLoaderExtensionFunctions=r._activeLoaderExtensionFunctions||{};const a=r._activeLoaderExtensionFunctions;if(!a[s]){a[s]=!0;try{const e=i(n);if(e)return e}finally{delete a[s]}}}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",(n=>n.loadNodeAsync&&n.loadNodeAsync(e,t,i)))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",(n=>n.loadCameraAsync&&n.loadCameraAsync(e,t,i)))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",(n=>n._loadVertexDataAsync&&n._loadVertexDataAsync(e,t,i)))}_extensionsLoadMeshPrimitiveAsync(e,t,i,n,s,r){return this._applyExtensions(s,"loadMeshPrimitive",(a=>a._loadMeshPrimitiveAsync&&a._loadMeshPrimitiveAsync(e,t,i,n,s,r)))}_extensionsLoadMaterialAsync(e,t,i,n,s){return this._applyExtensions(t,"loadMaterial",(r=>r._loadMaterialAsync&&r._loadMaterialAsync(e,t,i,n,s)))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",(n=>n.createMaterial&&n.createMaterial(e,t,i)))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",(n=>n.loadMaterialPropertiesAsync&&n.loadMaterialPropertiesAsync(e,t,i)))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",(n=>n.loadTextureInfoAsync&&n.loadTextureInfoAsync(e,t,i)))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",(n=>n._loadTextureAsync&&n._loadTextureAsync(e,t,i)))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",(i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t)))}_extensionsLoadAnimationChannelAsync(e,t,i,n,s){return this._applyExtensions(i,"loadAnimationChannel",(r=>r._loadAnimationChannelAsync&&r._loadAnimationChannelAsync(e,t,i,n,s)))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",(n=>n._loadSkinAsync&&n._loadSkinAsync(e,t,i)))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",(n=>n._loadUriAsync&&n._loadUriAsync(e,t,i)))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",(i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t)))}_extensionsLoadBufferAsync(e,t,i,n){return this._applyExtensions(t,"loadBuffer",(s=>s.loadBufferAsync&&s.loadBufferAsync(e,t,i,n)))}static LoadExtensionAsync(e,t,i,n){if(!t.extensions)return null;const s=t.extensions[i];return s?n(`${e}/extensions/${i}`,s):null}static LoadExtraAsync(e,t,i,n){if(!t.extras)return null;const s=t.extras[i];return s?n(`${e}/extras/${i}`,s):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)}}Qo._RegisteredExtensions={},Qo.DefaultSampler={index:-1},Ya._CreateGLTF2Loader=e=>new Qo(e);class Zo extends mn{constructor(e,t,i,n=5,s=0,r=!1,a=!1,o=3,l=null){super("",e),this._texture=e.getEngine().createRawCubeTexture(t,i,n,s,r,a,o,l)}update(e,t,i,n,s=null){this._texture.getEngine().updateRawCubeTexture(this._texture,e,t,i,n,s)}updateRGBDAsync(e,t=null,i=.8,n=0){return function(e,t,i,n,s){const r=bs(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=H.CubeRawRGBD,e._bufferViewArrayArray=t,e._lodGenerationScale=n,e._lodGenerationOffset=s,e._sphericalPolynomial=i,bs(e,t).then((()=>(e.isReady=!0,e)))}(this._texture,e,t,i,n).then((()=>{}))}clone(){return gt.Clone((()=>{const e=this.getScene(),t=this._texture,i=new Zo(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return t.source===H.CubeRawRGBD&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i}),this)}}const Jo="EXT_lights_image_based";class $o{constructor(e){this.name=Jo,this._loader=e,this.enabled=this._loader.isExtensionUsed(Jo)}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 Qo.LoadExtensionAsync(e,t,this.name,((i,n)=>{const s=new Array;s.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const r=qo.Get(`${i}/light`,this._lights,n.light);return s.push(this._loadLightAsync(`/extensions/${this.name}/lights/${n.light}`,r).then((e=>{this._loader.babylonScene.environmentTexture=e}))),this._loader.logClose(),Promise.all(s).then((()=>{}))}))}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const n=new Array(t.specularImages.length);for(let s=0;s{n[s][t]=e}))),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then((()=>{const i=new Zo(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=We.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(e=We.Inverse(e)),Xe.FromQuaternionToRef(e,i.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const s=Rn.FromArray(t.irradianceCoefficients);s.scaleInPlace(t.intensity),s.convertIrradianceToLambertianRadiance();const r=Cn.FromHarmonics(s),a=(n.length-1)/Le.Log2(t.specularImageSize);return i.updateRGBDAsync(n,r,a)}))}return t._loaded.then((()=>t._babylonTexture))}}Qo.RegisterExtension(Jo,(e=>new $o(e))),Ks.prototype.thinInstanceAdd=function(e,t=!0){if(!this.getScene().getEngine().getCaps().instancedArrays)return c.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=this._thinInstanceDataStorage.instancesCount)return!1;const n=this._thinInstanceDataStorage.matrixData;return t.copyToArray(n,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},Ks.prototype.thinInstanceSetAttributeAt=function(e,t,i,n=!0){return e===Lt.ColorKind&&(e=Lt.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]),n&&this.thinInstanceBufferUpdated(e),0))},Object.defineProperty(Ks.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){var t,i;const n=null!==(t=this._thinInstanceDataStorage.matrixData)&&void 0!==t?t:null===(i=this.source)||void 0===i?void 0:i._thinInstanceDataStorage.matrixData;e<=(n?n.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),Ks.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!1){e===Lt.ColorKind&&(e=Lt.ColorInstanceKind);const n=new Ot(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(n.createVertexBuffer(e+t,4*t,4));return n},Ks.prototype.thinInstanceSetBuffer=function(e,t,i=0,n=!1){var s,r,a;i=i||16,"matrix"===e?(null===(s=this._thinInstanceDataStorage.matrixBuffer)||void 0===s||s.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,n),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(null===(r=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===r||r.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,n))):(e===Lt.ColorKind&&(e=Lt.ColorInstanceKind),null===t?(null===(a=this._userThinInstanceBuffersStorage)||void 0===a?void 0:a.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 Lt(this.getEngine(),t,e,!n,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},Ks.prototype.thinInstanceBufferUpdated=function(e){var t,i,n;"matrix"===e?null===(t=this._thinInstanceDataStorage.matrixBuffer)||void 0===t||t.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount):"previousMatrix"===e?null===(i=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===i||i.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount):(e===Lt.ColorKind&&(e=Lt.ColorInstanceKind),(null===(n=this._userThinInstanceBuffersStorage)||void 0===n?void 0:n.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0))},Ks.prototype.thinInstancePartialBufferUpdate=function(e,t,i){var n;"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===Lt.ColorKind&&(e=Lt.ColorInstanceKind),(null===(n=this._userThinInstanceBuffersStorage)||void 0===n?void 0:n.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},Ks.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=new Array;for(let t=0;t{this._loader._disableInstancedMesh++;const s=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return s;const r=new Array;let a=0;const o=t=>{if(null==n.attributes[t])return void r.push(Promise.resolve(null));const i=qo.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,n.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"),s.then((e=>Promise.all(r).then((([i,n,s])=>{const r=new Float32Array(16*a);Ke.Vector3[0].copyFromFloats(0,0,0),Ke.Quaternion[0].copyFromFloats(0,0,0,1),Ke.Vector3[1].copyFromFloats(1,1,1);for(let e=0;enew tl(e)));class il{static get Default(){return il._Default||(il._Default=new il),il._Default}constructor(){const e=il.Configuration.decoder;this._decoderModulePromise=Me.LoadScriptAsync(Me.GetAbsoluteUrl(e.url)).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,n,s){return this._decoderModulePromise.then((()=>{const r=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(r,t,i,e,n,s),r}))}}il.Configuration={decoder:{url:"https://preview.babylonjs.com/meshopt_decoder.js"}},il._Default=null;const nl="EXT_meshopt_compression";class sl{constructor(e){this.name=nl,this.enabled=e.isExtensionUsed(nl),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return Qo.LoadExtensionAsync(e,t,this.name,((i,n)=>{const s=t;if(s._meshOptData)return s._meshOptData;const r=qo.Get(`${e}/buffer`,this._loader.gltf.buffers,n.buffer);return s._meshOptData=this._loader.loadBufferAsync(`/buffers/${r.index}`,r,n.byteOffset||0,n.byteLength).then((e=>il.Default.decodeGltfBufferAsync(e,n.count,n.byteStride,n.mode,n.filter))),s._meshOptData}))}}Qo.RegisterExtension(nl,(e=>new sl(e)));const rl="EXT_texture_webp";class al{constructor(e){this.name=rl,this._loader=e,this.enabled=e.isExtensionUsed(rl)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=null==t.sampler?Qo.DefaultSampler:qo.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),a=qo.Get(`${n}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,r,a,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}function ol(e,t,i,n,s,r){const a=new e.DecoderBuffer;a.Init(t,t.byteLength);const o=new e.Decoder;let l,h;try{const t=o.GetEncodedGeometryType(a);switch(t){case e.TRIANGULAR_MESH:l=new e.Mesh,h=o.DecodeBufferToMesh(a,l);break;case e.POINT_CLOUD:l=new e.PointCloud,h=o.DecodeBufferToPointCloud(a,l);break;default:throw new Error(`Invalid geometry type ${t}`)}if(!h.ok()||!l.ptr)throw new Error(h.error_msg());if(t===e.TRIANGULAR_MESH){const t=3*l.num_faces(),i=4*t,s=e._malloc(i);try{o.GetTrianglesUInt32Array(l,i,s);const r=new Uint32Array(t);r.set(new Uint32Array(e.HEAPF32.buffer,s,t)),n(r)}finally{e._free(s)}}const c=(t,i,n=1)=>{const r=i.num_components(),a=l.num_points(),h=a*r,c=h*Float32Array.BYTES_PER_ELEMENT,d=e._malloc(c);try{o.GetAttributeDataArrayForAllPoints(l,i,e.DT_FLOAT32,c,d);const u=new Float32Array(e.HEAPF32.buffer,d,h);if("color"===t&&3===r){const e=new Float32Array(4*a);for(let t=0,i=0;t{const i=t.data;switch(i.id){case"init":{const t=i.decoder;t.url&&(importScripts(t.url),e=DracoDecoderModule({wasmBinary:t.wasmBinary})),postMessage("done");break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{ol(e,i.dataView,i.attributes,(e=>{postMessage({id:"indices",value:e},[e.buffer])}),((e,t)=>{postMessage({id:e,value:t},[t.buffer])})),postMessage("done")}))}}}Qo.RegisterExtension(rl,(e=>new al(e)));class hl{static get DecoderAvailable(){const e=hl.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 hl._Default||(hl._Default=new hl),hl._Default}constructor(e=hl.DefaultNumWorkers){const t=hl.Configuration.decoder,i=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:Me.GetAbsoluteUrl(t.wasmUrl),wasmBinaryPromise:Me.LoadFileAsync(Me.GetAbsoluteUrl(t.wasmBinaryUrl))}:{url:Me.GetAbsoluteUrl(t.fallbackUrl),wasmBinaryPromise:Promise.resolve(void 0)};e&&"function"==typeof Worker&&"function"==typeof URL?this._workerPoolPromise=i.wasmBinaryPromise.then((t=>{const n=`${ol}(${ll})()`,s=URL.createObjectURL(new Blob([n],{type:"application/javascript"}));return new sr(e,(()=>new Promise(((e,n)=>{const r=new Worker(s),a=e=>{r.removeEventListener("error",a),r.removeEventListener("message",o),n(e)},o=t=>{"done"===t.data&&(r.removeEventListener("error",a),r.removeEventListener("message",o),e(r))};r.addEventListener("error",a),r.addEventListener("message",o),r.postMessage({id:"init",decoder:{url:i.url,wasmBinary:t}})}))))})):this._decoderModulePromise=i.wasmBinaryPromise.then((e=>{if(!i.url)throw new Error("Draco decoder module is not available");return Me.LoadScriptAsync(i.url).then((()=>{return t=e,new Promise((e=>{DracoDecoderModule({wasmBinary:t}).then((t=>{e({module:t})}))}));var t}))}))}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then((e=>{e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise}whenReadyAsync(){return this._workerPoolPromise?this._workerPoolPromise.then((()=>{})):this._decoderModulePromise?this._decoderModulePromise.then((()=>{})):Promise.resolve()}decodeMeshAsync(e,t,i){const n=e instanceof ArrayBuffer?new Uint8Array(e):e;if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((s,r)=>{e.push(((e,a)=>{const o=new Ns,l=t=>{e.removeEventListener("error",l),e.removeEventListener("message",h),r(t),a()},h=t=>{if("done"===t.data)e.removeEventListener("error",l),e.removeEventListener("message",h),s(o),a();else if("indices"===t.data.id)o.indices=t.data.value;else{const e=i&&i[t.data.id]?i[t.data.id]:1;if(1!==e)for(let i=0;i{const s=new Ns;return ol(e.module,n,t,(e=>{s.indices=e}),((e,t)=>{s.set(t,e)}),i),s}));throw new Error("Draco decoder module is not available")}}hl.Configuration={decoder:{wasmUrl:"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://preview.babylonjs.com/draco_decoder_gltf.wasm",fallbackUrl:"https://preview.babylonjs.com/draco_decoder_gltf.js"}},hl.DefaultNumWorkers=hl.GetDefaultNumWorkers(),hl._Default=null;const cl="KHR_draco_mesh_compression";class dl{constructor(e){this.name=cl,this._loader=e,this.enabled=hl.DecoderAvailable&&this._loader.isExtensionUsed(cl)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>{if(null!=t.mode){if(5!==t.mode&&4!==t.mode)throw new Error(`${e}: Unsupported mode ${t.mode}`);if(5===t.mode)throw new Error(`${e}: Mode ${t.mode} is not currently supported`)}const r={},a={},o=(n,o)=>{const l=s.attributes[n];if(void 0===l||void 0===t.attributes[n])return;r[o]=l;const h=qo.Get(`${e}/attributes/${n}`,this._loader.gltf.accessors,t.attributes[n]);if(h.normalized&&5126!==h.componentType){let e=1;switch(h.componentType){case 5120:e=127;break;case 5121:e=255;break;case 5122:e=32767;break;case 5123:e=65535}a[o]=e}i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(o)&&i._delayInfo.push(o)};o("POSITION",Lt.PositionKind),o("NORMAL",Lt.NormalKind),o("TANGENT",Lt.TangentKind),o("TEXCOORD_0",Lt.UVKind),o("TEXCOORD_1",Lt.UV2Kind),o("TEXCOORD_2",Lt.UV3Kind),o("TEXCOORD_3",Lt.UV4Kind),o("TEXCOORD_4",Lt.UV5Kind),o("TEXCOORD_5",Lt.UV6Kind),o("JOINTS_0",Lt.MatricesIndicesKind),o("WEIGHTS_0",Lt.MatricesWeightsKind),o("COLOR_0",Lt.ColorKind);const l=qo.Get(n,this._loader.gltf.bufferViews,s.bufferView);return l._dracoBabylonGeometry||(l._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${l.index}`,l).then((t=>(this.dracoCompression||hl.Default).decodeMeshAsync(t,r,a).then((e=>{const t=new Fs(i.name,this._loader.babylonScene);return e.applyToGeometry(t),t})).catch((t=>{throw new Error(`${e}: ${t.message}`)}))))),l._dracoBabylonGeometry}))}}Qo.RegisterExtension(cl,(e=>new dl(e)));const ul="KHR_lights_punctual";class fl{constructor(e){this.name=ul,this._loader=e,this.enabled=this._loader.isExtensionUsed(ul)}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,qo.Assign(this._lights)}}loadNodeAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>this._loader.loadNodeAsync(e,t,(e=>{let t;const r=qo.Get(n,this._lights,s.light),a=r.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,r.type){case"directional":t=new Qa(a,ze.Backward(),this._loader.babylonScene);break;case"point":t=new Za(a,ze.Zero(),this._loader.babylonScene);break;case"spot":{const e=new Ja(a,ze.Zero(),ze.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(`${n}: Invalid light type (${r.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,r._babylonLight=t,t.falloffType=Ti.FALLOFF_GLTF,t.diffuse=r.color?tt.FromArray(r.color):tt.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),Qo.AddPointerMetadata(t,n),i(e)}))))}}Qo.RegisterExtension(ul,(e=>new fl(e)));const _l="KHR_materials_pbrSpecularGlossiness";class pl{constructor(e){this.name=_l,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(_l)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loadSpecularGlossinessPropertiesAsync(n,t,s,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then((()=>{}))}))}_loadSpecularGlossinessPropertiesAsync(e,t,i,n){if(!(n instanceof Ho))throw new Error(`${e}: Material type not supported`);const s=new Array;return n.metallic=null,n.roughness=null,i.diffuseFactor?(n.albedoColor=tt.FromArray(i.diffuseFactor),n.alpha=i.diffuseFactor[3]):n.albedoColor=tt.White(),n.reflectivityColor=i.specularFactor?tt.FromArray(i.specularFactor):tt.White(),n.microSurface=null==i.glossinessFactor?1:i.glossinessFactor,i.diffuseTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,i.diffuseTexture,(e=>{e.name=`${n.name} (Diffuse)`,n.albedoTexture=e}))),i.specularGlossinessTexture&&(s.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,i.specularGlossinessTexture,(e=>{e.name=`${n.name} (Specular Glossiness)`,n.reflectivityTexture=e,n.reflectivityTexture.hasAlpha=!0}))),n.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(s).then((()=>{}))}}Qo.RegisterExtension(_l,(e=>new pl(e)));const ml="KHR_materials_unlit";class gl{constructor(e){this.name=ml,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(ml)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,(()=>this._loadUnlitPropertiesAsync(e,t,i)))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof Ho))throw new Error(`${e}: Material type not supported`);const n=new Array;i.unlit=!0;const s=t.pbrMetallicRoughness;return s&&(s.baseColorFactor?(i.albedoColor=tt.FromArray(s.baseColorFactor),i.alpha=s.baseColorFactor[3]):i.albedoColor=tt.White(),s.baseColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,s.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(n).then((()=>{}))}}Qo.RegisterExtension(ml,(e=>new gl(e)));const El="KHR_materials_clearcoat";class Tl{constructor(e){this.name=El,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(El)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadClearCoatPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof Ho))throw new Error(`${e}: Material type not supported`);const n=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&&n.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,n.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,n.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(n).then((()=>{}))}}Qo.RegisterExtension(El,(e=>new Tl(e)));const Al="KHR_materials_iridescence";class vl{constructor(e){this.name=Al,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(Al)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadIridescencePropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){var n,s,r,a,o;if(!(i instanceof Ho))throw new Error(`${e}: Material type not supported`);const l=new Array;return i.iridescence.isEnabled=!0,i.iridescence.intensity=null!==(n=t.iridescenceFactor)&&void 0!==n?n:0,i.iridescence.indexOfRefraction=null!==(r=null!==(s=t.iridescenceIor)&&void 0!==s?s:t.iridescenceIOR)&&void 0!==r?r:1.3,i.iridescence.minimumThickness=null!==(a=t.iridescenceThicknessMinimum)&&void 0!==a?a:100,i.iridescence.maximumThickness=null!==(o=t.iridescenceThicknessMaximum)&&void 0!==o?o:400,t.iridescenceTexture&&l.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,(e=>{e.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=e}))),t.iridescenceThicknessTexture&&l.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,(e=>{e.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=e}))),Promise.all(l).then((()=>{}))}}Qo.RegisterExtension(Al,(e=>new vl(e)));const Sl="KHR_materials_emissive_strength";class Rl{constructor(e){this.name=Sl,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(Sl)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then((()=>{this._loadEmissiveProperties(n,s,i)}))))}_loadEmissiveProperties(e,t,i){if(!(i instanceof Ho))throw new Error(`${e}: Material type not supported`);void 0!==t.emissiveStrength&&i.emissiveColor.scaleToRef(t.emissiveStrength,i.emissiveColor)}}Qo.RegisterExtension(Sl,(e=>new Rl(e)));const Cl="KHR_materials_sheen";class xl{constructor(e){this.name=Cl,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Cl)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadSheenPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof Ho))throw new Error(`${e}: Material type not supported`);const n=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,null!=t.sheenColorFactor?i.sheen.color=tt.FromArray(t.sheenColorFactor):i.sheen.color=tt.Black(),t.sheenColorTexture&&n.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,n.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(n).then((()=>{}))}}Qo.RegisterExtension(Cl,(e=>new xl(e)));const Ml="KHR_materials_specular";class Il{constructor(e){this.name=Ml,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ml)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadSpecularPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof Ho))throw new Error(`${e}: Material type not supported`);const n=new Array;return void 0!==t.specularFactor&&(i.metallicF0Factor=t.specularFactor),void 0!==t.specularColorFactor&&(i.metallicReflectanceColor=tt.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,(e=>{e.name=`${i.name} (Specular F0 Strength)`,i.metallicReflectanceTexture=e,i.useOnlyMetallicFromMetallicReflectanceTexture=!0})))),t.specularColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,(e=>{e.name=`${i.name} (Specular F0 Color)`,i.reflectanceTexture=e}))),Promise.all(n).then((()=>{}))}}Qo.RegisterExtension(Ml,(e=>new Il(e)));const bl="KHR_materials_ior";class yl{constructor(e){this.name=bl,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(bl)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadIorPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof Ho))throw new Error(`${e}: Material type not supported`);return void 0!==t.ior?i.indexOfRefraction=t.ior:i.indexOfRefraction=yl._DEFAULT_IOR,Promise.resolve()}}yl._DEFAULT_IOR=1.5,Qo.RegisterExtension(bl,(e=>new yl(e)));const Pl="KHR_materials_variants";class Dl{constructor(e){this.name=Pl,this._loader=e,this.enabled=this._loader.isExtensionUsed(Pl)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return Dl.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 ${Pl} extension`);const n=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)n(e);else n(t);i.lastSelected=t}selectVariant(e,t){return Dl.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 ${Pl} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){return Dl.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 ${Pl} extension`);return t.lastSelected}getLastSelectedVariant(e){return Dl.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){var t,i;return(null===(i=null===(t=null==e?void 0:e._internalMetadata)||void 0===t?void 0:t.gltf)||void 0===i?void 0:i[Pl])||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,n,s,r){return Qo.LoadExtensionAsync(e,s,this.name,((a,o)=>{const l=new Array;return l.push(this._loader._loadMeshPrimitiveAsync(e,t,i,n,s,(t=>{if(r(t),t instanceof Ks){const i=Qo._GetDrawMode(e,s.mode),n=this._loader.rootBabylonMesh,r=n?n._internalMetadata=n._internalMetadata||{}:{},h=r.gltf=r.gltf||{},c=h[Pl]=h[Pl]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:t,material:t.material});for(let e=0;e{for(let i=0;i{const i=e;let s=null,r=i;do{if(r=r.parent,!r)return;s=Dl._GetExtensionMetadata(r)}while(null===s);if(n&&s===Dl._GetExtensionMetadata(n)){r._internalMetadata={};for(const e in n._internalMetadata)r._internalMetadata[e]=n._internalMetadata[e];r._internalMetadata.gltf=[];for(const e in n._internalMetadata.gltf)r._internalMetadata.gltf[e]=n._internalMetadata.gltf[e];r._internalMetadata.gltf[Pl]={lastSelected:null,original:[],variants:{}};for(const e of s.original)r._internalMetadata.gltf[Pl].original.push({mesh:e.mesh,material:e.material});for(const e in s.variants)if(Object.prototype.hasOwnProperty.call(s.variants,e)){r._internalMetadata.gltf[Pl].variants[e]=[];for(const t of s.variants[e])r._internalMetadata.gltf[Pl].variants[e].push({mesh:t.mesh,material:t.material})}s=r._internalMetadata.gltf[Pl]}for(const e of s.original)e.mesh===t&&(e.mesh=i);for(const e of s.variants[a.name])e.mesh===t&&(e.mesh=i)}))}})))}}}))),Promise.all(l).then((([e])=>e))}))}}Qo.RegisterExtension(Pl,(e=>new Dl(e)));class Ol{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:eo.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...Ol._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new s,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 Ho&&e.subSurface.isRefractionEnabled)}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),Me.SetImmediate((()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,this._transparentMeshesCache.push(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 Ho&&(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)}_setupRenderTargets(){var e,t;let i,n;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new Un("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=null!==(t=null===(e=this._options.clearColor)||void 0===e?void 0:e.clone())&&void 0!==t?t: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.onBeforeBindObservable.add((e=>{n=this._scene.environmentIntensity,this._scene.environmentIntensity=1,i=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?e.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(e.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0})),this._opaqueRenderTarget.onAfterUnbindObservable.add((()=>{this._scene.environmentIntensity=n,this._scene.imageProcessingConfiguration._applyByPostProcess=i})),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 Ll="KHR_materials_transmission";class Nl{constructor(e){this.name=Ll,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ll),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>{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(n,t,i,s)),Promise.all(r).then((()=>{}))}))}_loadTransparentPropertiesAsync(e,t,i,n){if(!(i instanceof Ho))throw new Error(`${e}: Material type not supported`);const s=i;if(s.subSurface.isRefractionEnabled=!0,s.subSurface.volumeIndexOfRefraction=1,s.subSurface.useAlbedoToTintRefraction=!0,void 0===n.transmissionFactor)return s.subSurface.refractionIntensity=0,s.subSurface.isRefractionEnabled=!1,Promise.resolve();{s.subSurface.refractionIntensity=n.transmissionFactor;const e=s.getScene();s.subSurface.refractionIntensity&&!e._transmissionHelper&&new Ol({},s.getScene())}return s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=0,n.transmissionTexture?(n.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,n.transmissionTexture,void 0).then((e=>{s.subSurface.refractionIntensityTexture=e,s.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}Qo.RegisterExtension(Ll,(e=>new Nl(e)));const Fl="KHR_materials_translucency";class wl{constructor(e){this.name=Fl,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(Fl),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>{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(n,t,i,s)),Promise.all(r).then((()=>{}))}))}_loadTranslucentPropertiesAsync(e,t,i,n){if(!(i instanceof Ho))throw new Error(`${e}: Material type not supported`);const s=i;return s.subSurface.isTranslucencyEnabled=!0,s.subSurface.volumeIndexOfRefraction=1,s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=0,s.subSurface.useAlbedoToTintTranslucency=!0,void 0===n.translucencyFactor?(s.subSurface.translucencyIntensity=0,s.subSurface.isTranslucencyEnabled=!1,Promise.resolve()):(s.subSurface.translucencyIntensity=n.translucencyFactor,n.translucencyTexture?(n.translucencyTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/translucencyTexture`,n.translucencyTexture).then((e=>{s.subSurface.translucencyIntensityTexture=e}))):Promise.resolve())}}Qo.RegisterExtension(Fl,(e=>new wl(e)));const Bl="KHR_materials_volume";class Ul{constructor(e){this.name=Bl,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(Bl),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>{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(n,t,i,s)),Promise.all(r).then((()=>{}))}))}_loadVolumePropertiesAsync(e,t,i,n){if(!(i instanceof Ho))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!n.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const s=void 0!==n.attenuationDistance?n.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=s,void 0!==n.attenuationColor&&3==n.attenuationColor.length&&i.subSurface.tintColor.copyFromFloats(n.attenuationColor[0],n.attenuationColor[1],n.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=n.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,n.thicknessTexture?(n.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,n.thicknessTexture).then((e=>{i.subSurface.thicknessTexture=e,i.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}Qo.RegisterExtension(Bl,(e=>new Ul(e)));const kl="KHR_mesh_quantization";class Gl{constructor(e){this.name=kl,this.enabled=e.isExtensionUsed(kl)}dispose(){}}Qo.RegisterExtension(kl,(e=>new Gl(e)));const Vl="KHR_texture_basisu";class zl{constructor(e){this.name=Vl,this._loader=e,this.enabled=e.isExtensionUsed(Vl)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=null==t.sampler?Qo.DefaultSampler:qo.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),a=qo.Get(`${n}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,r,a,(e=>{i(e)}),t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}}Qo.RegisterExtension(Vl,(e=>new zl(e)));const Hl="KHR_texture_transform";class Wl{constructor(e){this.name=Hl,this._loader=e,this.enabled=this._loader.isExtensionUsed(Hl)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((n,s)=>this._loader.loadTextureInfoAsync(e,t,(e=>{if(!(e instanceof Ji))throw new Error(`${n}: Texture type not supported`);s.offset&&(e.uOffset=s.offset[0],e.vOffset=s.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,s.rotation&&(e.wAng=-s.rotation),s.scale&&(e.uScale=s.scale[0],e.vScale=s.scale[1]),null!=s.texCoord&&(e.coordinatesIndex=s.texCoord),i(e)}))))}}Qo.RegisterExtension(Hl,(e=>new Wl(e)));const Xl="KHR_xmp_json_ld";class Yl{constructor(e){this.name=Xl,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(Xl)}dispose(){this._loader=null}onLoading(){var e,t,i;if(null===this._loader.rootBabylonMesh)return;const n=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_xmp_json_ld,s=null===(i=null===(t=this._loader.gltf.asset)||void 0===t?void 0:t.extensions)||void 0===i?void 0:i.KHR_xmp_json_ld;if(n&&s){const e=+s.packet;n.packets&&e2)),new eh(Mr.ANIMATIONTYPE_FLOAT,`${e}.vScale`,Ql,(()=>2))],offset:[new eh(Mr.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,jl,(()=>2)),new eh(Mr.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,Ql,(()=>2))],rotation:[new eh(Mr.ANIMATIONTYPE_FLOAT,`${e}.wAng`,ql,(()=>1))]}}Qo.RegisterExtension(Xl,(e=>new Yl(e)));class $l extends Xo{buildAnimations(e,t,i,n,s){s(e._babylonCamera,this._buildAnimation(t,i,n))}}class eh extends Xo{buildAnimations(e,t,i,n,s){for(const r in e._data)s(e._data[r].babylonMaterial,this._buildAnimation(t,i,n))}}class th extends Xo{buildAnimations(e,t,i,n,s){s(e._babylonLight,this._buildAnimation(t,i,n))}}const ih={__array__:{__target__:!0,...Ko}},nh={__array__:{__target__:!0,orthographic:{xmag:[new $l(Mr.ANIMATIONTYPE_FLOAT,"orthoLeft",ql,(()=>1)),new $l(Mr.ANIMATIONTYPE_FLOAT,"orthoRight",Ql,(()=>1))],ymag:[new $l(Mr.ANIMATIONTYPE_FLOAT,"orthoBottom",ql,(()=>1)),new $l(Mr.ANIMATIONTYPE_FLOAT,"orthoTop",Ql,(()=>1))],zfar:[new $l(Mr.ANIMATIONTYPE_FLOAT,"maxZ",jl,(()=>1))],znear:[new $l(Mr.ANIMATIONTYPE_FLOAT,"minZ",jl,(()=>1))]},perspective:{yfov:[new $l(Mr.ANIMATIONTYPE_FLOAT,"fov",jl,(()=>1))],zfar:[new $l(Mr.ANIMATIONTYPE_FLOAT,"maxZ",jl,(()=>1))],znear:[new $l(Mr.ANIMATIONTYPE_FLOAT,"minZ",jl,(()=>1))]}}},sh={nodes:ih,materials:{__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new eh(Mr.ANIMATIONTYPE_COLOR3,"albedoColor",Kl,(()=>4)),new eh(Mr.ANIMATIONTYPE_FLOAT,"alpha",(function(e,t,i,n){return t[i+3]*n}),(()=>4))],metallicFactor:[new eh(Mr.ANIMATIONTYPE_FLOAT,"metallic",jl,(()=>1))],roughnessFactor:[new eh(Mr.ANIMATIONTYPE_FLOAT,"roughness",jl,(()=>1))],baseColorTexture:{extensions:{KHR_texture_transform:Jl("albedoTexture")}}},emissiveFactor:[new eh(Mr.ANIMATIONTYPE_COLOR3,"emissiveColor",Kl,(()=>3))],normalTexture:{scale:[new eh(Mr.ANIMATIONTYPE_FLOAT,"bumpTexture.level",jl,(()=>1))]},occlusionTexture:{strength:[new eh(Mr.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",jl,(()=>1))],extensions:{KHR_texture_transform:Jl("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:Jl("emissiveTexture")}},extensions:{KHR_materials_ior:{ior:[new eh(Mr.ANIMATIONTYPE_FLOAT,"indexOfRefraction",jl,(()=>1))]},KHR_materials_clearcoat:{clearcoatFactor:[new eh(Mr.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",jl,(()=>1))],clearcoatRoughnessFactor:[new eh(Mr.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",jl,(()=>1))]},KHR_materials_sheen:{sheenColorFactor:[new eh(Mr.ANIMATIONTYPE_COLOR3,"sheen.color",Kl,(()=>3))],sheenRoughnessFactor:[new eh(Mr.ANIMATIONTYPE_FLOAT,"sheen.roughness",jl,(()=>1))]},KHR_materials_specular:{specularFactor:[new eh(Mr.ANIMATIONTYPE_FLOAT,"metallicF0Factor",jl,(()=>1))],specularColorFactor:[new eh(Mr.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",Kl,(()=>3))]},KHR_materials_emissive_strength:{emissiveStrength:[new eh(Mr.ANIMATIONTYPE_FLOAT,"emissiveIntensity",jl,(()=>1))]},KHR_materials_transmission:{transmissionFactor:[new eh(Mr.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",jl,(()=>1))]},KHR_materials_volume:{attenuationColor:[new eh(Mr.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",Kl,(()=>3))],attenuationDistance:[new eh(Mr.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",jl,(()=>1))],thicknessFactor:[new eh(Mr.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",jl,(()=>1))]},KHR_materials_iridescence:{iridescenceFactor:[new eh(Mr.ANIMATIONTYPE_FLOAT,"iridescence.intensity",jl,(()=>1))],iridescenceIor:[new eh(Mr.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",jl,(()=>1))],iridescenceThicknessMinimum:[new eh(Mr.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",jl,(()=>1))],iridescenceThicknessMaximum:[new eh(Mr.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",jl,(()=>1))]}}}},cameras:nh,extensions:{KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new th(Mr.ANIMATIONTYPE_COLOR3,"diffuse",Kl,(()=>3))],intensity:[new th(Mr.ANIMATIONTYPE_FLOAT,"intensity",jl,(()=>1))],range:[new th(Mr.ANIMATIONTYPE_FLOAT,"range",jl,(()=>1))],spot:{innerConeAngle:[new th(Mr.ANIMATIONTYPE_FLOAT,"innerAngle",Zl,(()=>1))],outerConeAngle:[new th(Mr.ANIMATIONTYPE_FLOAT,"angle",Zl,(()=>1))]}}}}}},rh="KHR_animation_pointer";class ah{constructor(e){this.name=rh,this._loader=e}get enabled(){return this._loader.isExtensionUsed(rh)}dispose(){this._loader=null}_loadAnimationChannelAsync(e,t,i,n,s){var r;const a=null===(r=n.target.extensions)||void 0===r?void 0:r.KHR_animation_pointer;if(!a)return null;"pointer"!==n.target.path&&c.Warn(`${e}/target/path: Value (${n.target.path}) must be (pointer) when using the ${this.name} extension`),null!=n.target.node&&c.Warn(`${e}/target/node: Value (${n.target.node}) must not be present when using the ${this.name} extension`);const o=`${e}/extensions/${this.name}`,l=a.pointer;if(!l)throw new Error(`${o}: Pointer is missing`);const h=this._parseAnimationPointer(`${o}/pointer`,l);return h?this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,n,h,s):(c.Warn(`${o}/pointer: Invalid pointer (${l}) skipped`),null)}_parseAnimationPointer(e,t){if(!t.startsWith("/"))return c.Warn(`${e}: Value (${t}) must start with a slash`),null;const i=t.split("/");i.shift();let n,s=sh,r=this._loader.gltf;for(const e of i){if(s.__array__)s=s.__array__;else if(s=s[e],!s)return null;r=r&&r[e],s.__target__&&(n=r)}return n&&Array.isArray(s)?{target:n,properties:s}:null}}Qo.RegisterExtension(rh,(e=>new ah(e)));class oh{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new oh(this.frame,this.action,this.onlyOnce)}}class lh{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){var e;if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if((null===(e=tn.audioEngine)||void 0===e?void 0:e.audioContext)&&(this.isPlaying||this.isPaused)){const e=this.isPaused?0:tn.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){var t;this._spatialSound=e,this._spatialSound&&(null===(t=tn.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&tn.audioEngine.audioContext&&this._createSpatialParameters()}constructor(e,t,i,n=null,r){var a,o,l,h,d;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 s,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=ze.Zero(),this._localDirection=new ze(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,lh._SceneComponentInitialization(i),this._readyToPlayCallback=n,this._customAttenuationFunction=(e,t,i,n,s)=>t0&&(n=!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{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&&c.Error("XHR "+e.status+" error on: "+t+"."),c.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}));break}}break;default:e=!1}e?n||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)):c.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){c.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),tn.audioEngine&&!tn.audioEngine.WarnedWebAudioUnsupported&&(c.Error("Web Audio is not supported by your browser."),tn.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){var e;(null===(e=tn.audioEngine)||void 0===e?void 0:e.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))}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){var t;(null===(t=tn.audioEngine)||void 0===t?void 0:t.audioContext)&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){var t;(null===(t=tn.audioEngine)||void 0===t?void 0:t.audioContext)&&tn.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{c.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){var t;(null===(t=tn.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){var t,i,n,s,r,a,o,l,h,c;e&&(this.loop=null!==(t=e.loop)&&void 0!==t?t:this.loop,this.maxDistance=null!==(i=e.maxDistance)&&void 0!==i?i:this.maxDistance,this.useCustomAttenuation=null!==(n=e.useCustomAttenuation)&&void 0!==n?n:this.useCustomAttenuation,this.rolloffFactor=null!==(s=e.rolloffFactor)&&void 0!==s?s:this.rolloffFactor,this.refDistance=null!==(r=e.refDistance)&&void 0!==r?r:this.refDistance,this.distanceModel=null!==(a=e.distanceModel)&&void 0!==a?a:this.distanceModel,this._playbackRate=null!==(o=e.playbackRate)&&void 0!==o?o:this._playbackRate,this._length=null!==(l=e.length)&&void 0!==l?l:void 0,this._setOffset(null!==(h=e.offset)&&void 0!==h?h:void 0),this.setVolume(null!==(c=e.volume)&&void 0!==c?c: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(){var e,t;(null===(e=tn.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&tn.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=null!==(t=this._soundPanner)&&void 0!==t?t:tn.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_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))}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){var e;(null===(e=tn.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(null===(t=tn.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const e=()=>{var t,i;if(null===(t=tn.audioEngine)||void 0===t?void 0:t.unlocked){const t=this._htmlAudioElement.play();void 0!==t&&t.catch((()=>{var t,i;null===(t=tn.audioEngine)||void 0===t||t.lock(),(this.loop||this.autoplay)&&(null===(i=tn.audioEngine)||void 0===i||i.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(null===(i=tn.audioEngine)||void 0===i||i.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const s=()=>{var s,r,a,o;if(null===(s=tn.audioEngine)||void 0===s?void 0:s.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=null===(r=tn.audioEngine)||void 0===r?void 0:r.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()},n=e?(null===(a=tn.audioEngine)||void 0===a?void 0:a.audioContext.currentTime)+e:tn.audioEngine.audioContext.currentTime;const s=((this.isPaused?this.currentTime:0)+(null!==(o=this._offset)&&void 0!==o?o:0))%this._soundSource.buffer.duration;this._soundSource.start(n,s,this.loop?void 0:i)}}};"suspended"===(null===(a=tn.audioEngine)||void 0===a?void 0:a.audioContext.state)?setTimeout((()=>{var e;"suspended"===(null===(e=tn.audioEngine)||void 0===e?void 0:e.audioContext.state)?(tn.audioEngine.lock(),(this.loop||this.autoplay)&&tn.audioEngine.onAudioUnlockedObservable.addOnce((()=>{s()}))):s()}),500):s()}this._startTime=n,this.isPlaying=!0,this.isPaused=!1}catch(e){c.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){var t;if(this.isPlaying){if(this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if((null===(t=tn.audioEngine)||void 0===t?void 0:t.audioContext)&&this._soundSource){const t=e?tn.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.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){var e;this.isPlaying&&(this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(null===(e=tn.audioEngine)||void 0===e?void 0:e.audioContext)&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=tn.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(null===(i=tn.audioEngine)||void 0===i?void 0:i.canUseWebAudio)&&this._soundGain&&(t&&tn.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(tn.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,tn.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,tn.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){var t;if(e.getBoundingInfo){const t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);(null===(t=tn.audioEngine)||void 0===t?void 0:t.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 lh(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.name,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,n){const s=e.name;let r;r=e.url?i+e.url:i+s;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(n){const e=()=>{n._isReadyToPlay?(o._audioBuffer=n.getAudioBuffer(),o._isReadyToPlay=!0,o.autoplay&&o.play(0,o._offset,o._length)):setTimeout(e,300)};o=new lh(s,new ArrayBuffer(0),t,null,a),e()}else o=new lh(s,r,t,(()=>{t.removePendingData(o)}),a),t.addPendingData(o);if(e.position){const t=ze.FromArray(e.position);o.setPosition(t)}if(e.isDirectional&&(o.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=ze.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)}}lh._SceneComponentInitialization=e=>{throw _("AudioSceneComponent")};class hh{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 n=0;for(const e of i)n+=e;const s=n>0?1/n:0;for(let e=0;e{this._onended()}))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAngle{const s=new Array;s.push(this._loader.loadSceneAsync(e,t));for(const e of n.emitters){const t=qo.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`);s.push(this._loadEmitterAsync(`${i}/emitters/${t.index}`,t))}return Promise.all(s).then((()=>{}))}))}loadNodeAsync(e,t,i){return Qo.LoadExtensionAsync(e,t,this.name,((e,n)=>{const s=new Array;return this._loader.loadNodeAsync(e,t,(t=>{for(const i of n.emitters){const n=qo.Get(`${e}/emitters`,this._emitters,i);s.push(this._loadEmitterAsync(`${e}/emitters/${n.index}`,n).then((()=>{for(const e of n._babylonSounds)e.attachToMesh(t),null==n.innerAngle&&null==n.outerAngle||(e.setLocalDirectionToMesh(ze.Forward()),e.setDirectionalCone(2*Me.ToDegrees(null==n.innerAngle?Math.PI:n.innerAngle),2*Me.ToDegrees(null==n.outerAngle?Math.PI:n.outerAngle),0))})))}i(t)})).then((e=>Promise.all(s).then((()=>e))))}))}loadAnimationAsync(e,t){return Qo.LoadExtensionAsync(e,t,this.name,((i,n)=>this._loader.loadAnimationAsync(e,t).then((s=>{const r=new Array;qo.Assign(n.events);for(const a of n.events)r.push(this._loadAnimationEventAsync(`${i}/events/${a.index}`,e,t,a,s));return Promise.all(r).then((()=>s))}))))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const n=qo.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${n.index}`,n)}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}`,n={loop:!1,autoplay:!1,volume:null==t.volume?1:t.volume};for(let s=0;s{const r=t._babylonSounds[s]=new lh(i,e,this._loader.babylonScene,null,n);r.refDistance=t.refDistance||1,r.maxDistance=t.maxDistance||256,r.rolloffFactor=t.rolloffFactor||1,r.distanceModel=t.distanceModel||"exponential"})))}const s=Promise.all(e).then((()=>{const e=t.clips.map((e=>e.weight||1)),i=new hh(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(i.directionalConeInnerAngle=2*Me.ToDegrees(t.innerAngle)),t.outerAngle&&(i.directionalConeOuterAngle=2*Me.ToDegrees(t.outerAngle)),t.volume&&(i.volume=t.volume),t._babylonData.sound=i}));t._babylonData={loaded:s}}return t._babylonData.loaded}_getEventAction(e,t,i,n,s){switch(i){case"play":return e=>{const i=(s||0)+(e-n);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,n,s){if(0==s.targetedAnimations.length)return Promise.resolve();const r=s.targetedAnimations[0],a=n.emitter,o=qo.Get(`/extensions/${this.name}/emitters`,this._emitters,a);return this._loadEmitterAsync(e,o).then((()=>{const t=o._babylonData.sound;if(t){const i=new oh(n.time,this._getEventAction(e,t,n.action,n.time,n.startOffset));r.animation.addEvent(i),s.onAnimationGroupEndObservable.add((()=>{t.stop()})),s.onAnimationGroupPauseObservable.add((()=>{t.pause()}))}}))}}Qo.RegisterExtension(ch,(e=>new dh(e)));const uh="MSFT_lod";class fh{constructor(e){this.name=uh,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new s,this.onMaterialLODsLoadedObservable=new s,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(uh)}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{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{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 Qo.LoadExtensionAsync(e,t,this.name,((e,n)=>{let s;const r=this._getLODs(e,t,this._loader.gltf.nodes,n.ids);this._loader.logOpen(`${e}`);for(let e=0;e{i(e),e.setEnabled(!1)},a=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,n).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?s=a:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(a))}return this._loader.logClose(),s}))}_loadMaterialAsync(e,t,i,n,s){return this._nodeIndexLOD?null:Qo.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{0===e&&s(t)})).then((t=>{if(0!==e){s(t);const i=o[e-1]._data;i[n]&&(this._disposeMaterials([i[n].babylonMaterial]),delete i[n])}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 n=this._nodeIndexLOD-1;return this._nodeSignalLODs[n]=this._nodeSignalLODs[n]||new xs,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const n=this._materialIndexLOD-1;return this._materialSignalLODs[n]=this._materialSignalLODs[n]||new xs,this._materialSignalLODs[n].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}return null}loadBufferAsync(e,t,i,n){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 s=i,r=s+n-1;let a=e[t];return a?(a.start=Math.min(a.start,s),a.end=Math.max(a.end,r)):(a={start:s,end:r,loaded:new xs},e[t]=a),a.loaded.promise.then((e=>new Uint8Array(e.buffer,e.byteOffset+i-a.start,n)))};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,n){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const s=new Array;for(let t=n.length-1;t>=0;t--)if(s.push(qo.Get(`${e}/ids/${n[t]}`,i,n[t])),s.length===this.maxLODsToLoad)return s;return s.push(t),s}_disposeTransformNode(e){const t=new Array,i=e.material;i&&t.push(i);for(const i of e.getChildMeshes())i.material&&t.push(i.material);e.dispose();const n=t.filter((e=>this._loader.babylonScene.meshes.every((t=>t.material!=e))));this._disposeMaterials(n)}_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()}}Qo.RegisterExtension(uh,(e=>new fh(e)));const _h="MSFT_minecraftMesh";class ph{constructor(e){this.name=_h,this._loader=e,this.enabled=this._loader.isExtensionUsed(_h)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Qo.LoadExtraAsync(e,t,this.name,((n,s)=>{if(s){if(!(i instanceof Ho))throw new Error(`${n}: Material type not supported`);const s=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,s}return null}))}}Qo.RegisterExtension(_h,(e=>new ph(e)));const mh="MSFT_sRGBFactors";class gh{constructor(e){this.name=mh,this._loader=e,this.enabled=this._loader.isExtensionUsed(mh)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Qo.LoadExtraAsync(e,t,this.name,((n,s)=>{if(s){if(!(i instanceof Ho))throw new Error(`${n}: Material type not supported`);const s=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),s}return null}))}}Qo.RegisterExtension(mh,(e=>new gh(e)));const Eh="ExtrasAsMetadata";class Th{_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=Eh,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 n=this._loader.createMaterial(e,t,i);return this._assignExtras(n,t),n}}Qo.RegisterExtension(Eh,(e=>new Th(e)));class Ah{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css",this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);const e=!!window.SVGSVGElement,t=new Image;Ah.DefaultLogoUrl?t.src=Ah.DefaultLogoUrl:t.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",t.style.width="150px",t.style.gridColumn="1",t.style.gridRow="1",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.position="absolute";const i=document.createElement("div");i.style.width="300px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const n=new Image;if(Ah.DefaultSpinnerUrl?n.src=Ah.DefaultSpinnerUrl:n.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",n.style.animation="spin1 0.75s infinite linear",n.style.webkitAnimation="spin1 0.75s infinite linear",n.style.transformOrigin="50% 50%",n.style.webkitTransformOrigin="50% 50%",!e){const e={w:16,h:18.5},i={w:30,h:30};t.style.width=`${e.w}vh`,t.style.height=`${e.h}vh`,t.style.left=`calc(50% - ${e.w/2}vh)`,t.style.top=`calc(50% - ${e.h/2}vh)`,n.style.width=`${i.w}vh`,n.style.height=`${i.h}vh`,n.style.left=`calc(50% - ${i.w/2}vh)`,n.style.top=`calc(50% - ${i.h/2}vh)`}i.appendChild(n),this._loadingDiv.appendChild(t),this._loadingDiv.appendChild(i),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)})))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}Ah.DefaultLogoUrl="",Ah.DefaultSpinnerUrl="",tn.DefaultLoadingScreenFactory=e=>new Ah(e);class vh{constructor(){const t=e();t.canvas=document.getElementById("view"),pn.RegisterPlugin(new Ya),this.init().then((function(){t.sceneToRender=t.scenes.get("test")})),window.addEventListener("resize",function(){this.resize()}.bind(this))}async init(){const t=e();if(t.engine=await async function(){try{return vh.createDefaultEngine()}catch(e){return console.log("Standard engine invocation failed. Creating with default engine instead."),vh.createDefaultEngine()}}(),!t.engine)throw"Engine invocation failure.";t.engine.setHardwareScalingLevel(1/window.devicePixelRatio),t.scenes=new Ma,vh.startRenderLoop()}static createDefaultEngine(){return new tn(e().canvas,!1,{powerPreference:"high-performance",preserveDrawingBuffer:!1,stencil:!1,disableWebGL2Support:!0})}static startRenderLoop(){const t=e();t.engine.runRenderLoop((function(){t.sceneToRender&&t.sceneToRender.activeCamera&&t.sceneToRender.render()}))}resize(){const t=e();t.engine.resize();for(const e of t.sceneToRender.cameras)e.onResize&&e.onResize()}}new PerformanceObserver((e=>{e.getEntries().forEach((e=>{if(e.duration>0){const t=document.createElement("div");t.style="position: absolute; top: 0; left: 0; z-index: 10000",t.innerHTML=`Page Load: ${e.duration}ms`,document.body.appendChild(t)}}))})).observe({type:"navigation",buffered:!0});const Sh=new class{constructor(){this.engine=new vh}async run(){}};window.addEventListener("DOMContentLoaded",(e=>{Sh.run()}))})();