(()=>{"use strict";var e={518:(e,t,i)=>{i.d(t,{Z:()=>d});var n=i(81),r=i.n(n),s=i(645),a=i.n(s),o=i(667),l=i.n(o),h=new URL(i(958),i.b),c=a()(r()),u=l()(h);c.push([e.id,".amp-default-skin .vjs-webvr-control {\r\n background-image: url("+u+");\r\n background-size: 20px;\r\n background-repeat: no-repeat;\r\n background-position: center;\r\n}",""]);const d=c},645:e=>{e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var i="",n=void 0!==t[5];return t[4]&&(i+="@supports (".concat(t[4],") {")),t[2]&&(i+="@media ".concat(t[2]," {")),n&&(i+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),i+=e(t),n&&(i+="}"),t[2]&&(i+="}"),t[4]&&(i+="}"),i})).join("")},t.i=function(e,i,n,r,s){"string"==typeof e&&(e=[[null,e,void 0]]);var a={};if(n)for(var o=0;o0?" ".concat(c[5]):""," {").concat(c[1],"}")),c[5]=s),i&&(c[2]?(c[1]="@media ".concat(c[2]," {").concat(c[1],"}"),c[2]=i):c[2]=i),r&&(c[4]?(c[1]="@supports (".concat(c[4],") {").concat(c[1],"}"),c[4]=r):c[4]="".concat(r)),t.push(c))}},t}},667:e=>{e.exports=function(e,t){return t||(t={}),e?(e=String(e.__esModule?e.default:e),/^['"].*['"]$/.test(e)&&(e=e.slice(1,-1)),t.hash&&(e+=t.hash),/["'() \t\n]|(%20)/.test(e)||t.needQuotes?'"'.concat(e.replace(/"/g,'\\"').replace(/\n/g,"\\n"),'"'):e):e}},81:e=>{e.exports=function(e){return e[1]}},379:e=>{var t=[];function i(e){for(var i=-1,n=0;n{var t={};e.exports=function(e,i){var n=function(e){if(void 0===t[e]){var i=document.querySelector(e);if(window.HTMLIFrameElement&&i instanceof window.HTMLIFrameElement)try{i=i.contentDocument.head}catch(e){i=null}t[e]=i}return t[e]}(e);if(!n)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");n.appendChild(i)}},216:e=>{e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}},565:(e,t,i)=>{e.exports=function(e){var t=i.nc;t&&e.setAttribute("nonce",t)}},795:e=>{e.exports=function(e){var t=e.insertStyleElement(e);return{update:function(i){!function(e,t,i){var n="";i.supports&&(n+="@supports (".concat(i.supports,") {")),i.media&&(n+="@media ".concat(i.media," {"));var r=void 0!==i.layer;r&&(n+="@layer".concat(i.layer.length>0?" ".concat(i.layer):""," {")),n+=i.css,r&&(n+="}"),i.media&&(n+="}"),i.supports&&(n+="}");var s=i.sourceMap;s&&"undefined"!=typeof btoa&&(n+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(s))))," */")),t.styleTagTransform(n,e,t.options)}(t,e,i)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}},589:e=>{e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}},958:e=>{e.exports="data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A"}},t={};function i(n){var r=t[n];if(void 0!==r)return r.exports;var s=t[n]={id:n,exports:{}};return e[n](s,s.exports,i),s.exports}i.m=e,i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.b=document.baseURI||self.location.href,i.nc=void 0,(()=>{class e{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 t{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1}}class n{constructor(t){this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._eventState=new e(0),t&&(this._onObserverAdded=t)}static FromPromise(e,t){const i=new n;return e.then((e=>{i.notifyObservers(e)})).catch((e=>{if(!t)throw e;t.notifyObservers(e)})),i}get observers(){return this._observers}add(e,i=-1,n=!1,r=null,s=!1){if(!e)return null;const a=new t(e,i,r);return a.unregisterOnNextCall=s,n?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),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,r){if(!this._observers.length)return!0;const s=this._eventState;s.mask=t,s.target=i,s.currentTarget=n,s.skipNextObservers=!1,s.lastReturnValue=e,s.userInfo=r;for(const i of this._observers)if(!i._willBeUnregistered&&(i.mask&t&&(i.unregisterOnNextCall&&this._deferUnregister(i),i.scope?s.lastReturnValue=i.callback.apply(i.scope,[e,s]):s.lastReturnValue=i.callback(e,s)),s.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(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=new Array,this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0}clone(){const e=new n;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}}class r{constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}setParameters(e=1,t=1,i=1,n=1,r=2,s=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=n,this.samplingMode=r,this._comparisonFunction=s,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}var s,a;(a=s||(s={}))[a.Unknown=0]="Unknown",a[a.Url=1]="Url",a[a.Temp=2]="Temp",a[a.Raw=3]="Raw",a[a.Dynamic=4]="Dynamic",a[a.RenderTarget=5]="RenderTarget",a[a.MultiRenderTarget=6]="MultiRenderTarget",a[a.Cube=7]="Cube",a[a.CubeRaw=8]="CubeRaw",a[a.CubePrefiltered=9]="CubePrefiltered",a[a.Raw3D=10]="Raw3D",a[a.Raw2DArray=11]="Raw2DArray",a[a.DepthStencil=12]="DepthStencil",a[a.CubeRawRGBD=13]="CubeRawRGBD",a[a.Depth=14]="Depth";class o extends r{constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new n,this.onErrorObservable=new n,this.onRebuildCallback=null,this.width=0,this.height=0,this.depth=0,this.baseWidth=0,this.baseHeight=0,this.baseDepth=0,this.invertY=!1,this._invertVScale=!1,this._associatedChannel=-1,this._source=s.Unknown,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._hardwareTexture=null,this._maxLodLevel=null,this._references=1,this._gammaSpace=null,this._engine=e,this._source=t,this._uniqueId=o._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}get useMipMaps(){return this.generateMipMaps}set useMipMaps(e){this.generateMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){var e;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){const e=this.onRebuildCallback(this),t=t=>{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let t;switch(this.source){case s.Temp:break;case s.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 s.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 s.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 s.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 s.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 s.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 s.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 s.CubeRawRGBD:return;case s.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 r=n.indexOf(this);-1!==r&&n.splice(r,1),r=n.indexOf(e),-1===r&&n.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null)}}function l(){return"undefined"!=typeof window}function h(){return"undefined"!=typeof navigator}function c(){return"undefined"!=typeof document}function u(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}o._Counter=0;const d={IsWindowObjectExist:l,IsNavigatorAvailable:h,IsDocumentAvailable:c,GetDOMTextContent:u};class f{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}function _(e){return`${e} needs to be imported before as it contains a side-effect required by your code.`}f.Instances=new Array,f._LastCreatedScene=null,f.UseFallbackTexture=!0,f.FallbackTexture="";class p{static _CheckLimit(e,t){let i=p._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},p._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){var i;const n=p._LogLimitOutputs[e];if(!n||!p.MessageLimitReached)return;const r=this._Levels[t];n.current===n.limit&&p[r.name](p.MessageLimitReached.replace(/%LIMIT%/g,""+n.limit).replace(/%TYPE%/g,null!==(i=r.name)&&void 0!==i?i:""))}static _AddLogEntry(e){p._LogCache=e+p._LogCache,p.OnNewCacheEntry&&p.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&&!p._CheckLimit(t,i))return;const n=p._FormatMessage(t),r=this._Levels[e];r.logFunc&&r.logFunc("BJS - "+n);const s=`
${n}

`;p._AddLogEntry(s),p._GenerateLimitMessage(t,e)}static get LogCache(){return p._LogCache}static ClearLogCache(){p._LogCache="",p._LogLimitOutputs={},p.errorsCount=0}static set LogLevels(e){p.Log=p._LogDisabled,p.Warn=p._LogDisabled,p.Error=p._LogDisabled,[p.MessageLogLevel,p.WarningLogLevel,p.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];p[e.name]=p._LogEnabled.bind(p,t)}}))}}p.NoneLogLevel=0,p.MessageLogLevel=1,p.WarningLogLevel=2,p.ErrorLogLevel=4,p.AllLogLevel=7,p.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",p._LogCache="",p._LogLimitOutputs={},p._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],p.errorsCount=0,p.Log=p._LogEnabled.bind(p,p.MessageLogLevel),p.Warn=p._LogEnabled.bind(p,p.WarningLogLevel),p.Error=p._LogEnabled.bind(p,p.ErrorLogLevel);class m{constructor(){this.children=[]}isValid(e){return!0}process(e,t){var i,n,r,s,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",u=t.isFragment&&(null===(r=t.processor)||void 0===r?void 0:r.varyingFragmentKeywordName)?null===(s=t.processor)||void 0===s?void 0:s.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(u)?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 g{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex{l=l.trim(),""!==l&&(t.push(l),l="")},r=e=>{iT._Stack[i],a=()=>-1===i?"!!INVALID EXPRESSION!!":T._Stack[i--];let o=0,l="";for(;o1){for(n();-1!==i&&T._OperatorPriority[s()]>=T._OperatorPriority[c];)t.push(a());r(c),o++}else l+=h;o++}for(n();-1!==i;)"("===s()?a():t.push(a());return t}}T._OperatorPriority={")":0,"(":1,"||":2,"&&":3},T._Stack=["","","","","","","","","","","","","","","","","","","",""];class C extends T{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 R extends T{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}}class A extends T{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}}class b extends T{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),r=parseInt(this.testValue);switch(this.operand){case">":i=n>r;break;case"<":i=n=":i=n>=r;break;case"==":i=n===r}return i}}var S;!function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(S||(S={}));const I=/defined\s*?\((.+?)\)/g,x=/defined\s*?\[(.+?)\]/g,y=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g;class M{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,n){var r;(null===(r=t.processor)||void 0===r?void 0:r.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const r=this._ProcessShaderConversion(e,t,n);i(r,e)}))}static PreProcess(e,t,i,n){var r;(null===(r=t.processor)||void 0===r?void 0:r.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const r=this._ApplyPreProcessing(e,t,n);i(r,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 C(t[1].trim(),"!"===e[0]);const i=["==",">=","<=","<",">"];let n="",r=0;for(n of i)if(r=e.indexOf(n),r>-1)break;if(-1===r)return new C(e);const s=e.substring(0,r).trim(),a=e.substring(r+n.length).trim();return new b(s,n,a)}static _BuildSubExpression(e){e=e.replace(I,"defined[$1]");const t=T.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 r="&&"==e?new A:new R;"string"==typeof t&&(t=t.replace(x,"defined($1)")),"string"==typeof n&&(n=n.replace(x,"defined($1)")),r.leftOperand="string"==typeof n?this._ExtractOperation(n):n,r.rightOperand="string"==typeof t?this._ExtractOperation(t):t,i.push(r)}let n=i[i.length-1];return"string"==typeof n&&(n=n.replace(x,"defined($1)")),"string"==typeof n?this._ExtractOperation(n):n}static _BuildExpression(e,t){const i=new E,n=e.substring(0,t);let r=e.substring(t);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),i.testExpression="#ifdef"===n?new C(r):"#ifndef"===n?new C(r,!0):this._BuildSubExpression(r),i}static _MoveCursorWithinIf(e,t,i){let n=e.currentLine;for(;this._MoveCursor(e,i);){n=e.currentLine;const r=n.substring(0,5).toLowerCase();if("#else"===r){const i=new m;return t.children.push(i),void this._MoveCursor(e,i)}if("#elif"===r){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 v;t.children.push(n);const r=this._BuildExpression(i,6);n.children.push(r),this._MoveCursorWithinIf(e,n,r);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const n=new v;t.children.push(n);const r=this._BuildExpression(i,7);n.children.push(r),this._MoveCursorWithinIf(e,n,r);break}case"#if":{const n=new v,r=this._BuildExpression(i,3);t.children.push(n),n.children.push(r),this._MoveCursorWithinIf(e,n,r);break}}else{const e=new m;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 m,r=new g;return r.lineIndex=-1,r.lines=e.split("\n"),this._MoveCursor(r,n),n.process(t,i)}static _PreparePreProcessors(e,t){var i;const n=e.defines,r={};for(const e of n){const t=e.replace("#define","").replace(";","").trim().split(" ");r[t[0]]=t.length>1?t[1]:""}return(null===(i=e.processor)||void 0===i?void 0:i.shaderLanguage)===S.GLSL&&(r.GL_ES="true"),r.__VERSION__=e.version,r[e.platformName]="true",t._getGlobalDefines(r),r}static _ProcessShaderConversion(e,t,i){let n=this._ProcessPrecision(e,t);if(!t.processor)return n;if(t.processor.shaderLanguage===S.GLSL&&-1!==n.indexOf("#version 3")&&(n=n.replace("#version 300 es",""),!t.processor.parseGLES3))return n;const r=t.defines,s=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(n=t.processor.preProcessor(n,r,t.isFragment,t.processingContext)),n=this._EvaluatePreProcessors(n,s,t),t.processor.postProcessor&&(n=t.processor.postProcessor(n,r,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}static _ApplyPreProcessing(e,t,i){var n,r;let s=e;const a=t.defines,o=this._PreparePreProcessors(t,i);return(null===(n=t.processor)||void 0===n?void 0:n.preProcessor)&&(s=t.processor.preProcessor(s,a,t.isFragment,t.processingContext)),s=this._EvaluatePreProcessors(s,o,t),(null===(r=t.processor)||void 0===r?void 0:r.postProcessor)&&(s=t.processor.postProcessor(s,a,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}static _ProcessIncludes(e,t,i){let n=y.exec(e),r=new String(e),s=!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 M._FileToolsLoadFile(e,(e=>{t.includesShadersStore[a]=e,this._ProcessIncludes(r,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)}r=r.replace(n[0],e),s=s||e.indexOf("#include<")>=0||e.indexOf("#include <")>=0}n=y.exec(e)}s?this._ProcessIncludes(r.toString(),t,i):i(r)}static _FileToolsLoadFile(e,t,i,n,r,s){throw _("FileTools")}}class P{static GetShadersRepository(e=S.GLSL){return e===S.GLSL?P.ShadersRepository:P.ShadersRepositoryWGSL}static GetShadersStore(e=S.GLSL){return e===S.GLSL?P.ShadersStore:P.ShadersStoreWGSL}static GetIncludesShadersStore(e=S.GLSL){return e===S.GLSL?P.IncludesShadersStore:P.IncludesShadersStoreWGSL}}P.ShadersRepository="src/Shaders/",P.ShadersStore={},P.IncludesShadersStore={},P.ShadersRepositoryWGSL="src/ShadersWGSL/",P.ShadersStoreWGSL={},P.IncludesShadersStoreWGSL={};class O{constructor(e,t,i,r=null,s,a=null,o=null,h=null,c=null,u,d="",f=S.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 n,this.onErrorObservable=new n,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=d;let v,E,T=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!==_?_:S.GLSL,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t{if(A[0]&&A[1]){R.isFragment=!0;const[t,i]=A;M.Process(i,R,((i,n)=>{this._fragmentSourceCodeBeforeMigration=n,T&&(i=T("fragment",i));const r=M.Finalize(t,i,R);R=null,this._useFinalCode(r.vertexCode,r.fragmentCode,e)}),this._engine)}};this._loadShader(v,"Vertex","",(e=>{M.Initialize(R),M.Process(e,R,((t,i)=>{this._rawVertexSourceCode=e,this._vertexSourceCodeBeforeMigration=i,T&&(t=T("vertex",t)),A[0]=t,b()}),this._engine)})),this._loadShader(E,"Fragment","Pixel",(e=>{this._rawFragmentSourceCode=e,A[1]=e,b()}));const I=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]||I(t.slice(0,-1)+e).bind(this)})):this[t]=this[t]||I(t).bind(this)}))}static get ShadersRepository(){return P.ShadersRepository}static set ShadersRepository(e){P.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new n),this._onBindObservable}_useFinalCode(e,t,i){if(i){const n=i.vertexElement||i.vertex||i.spectorName||i,r=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===S.WGSL?"//":"")+"#define SHADER_NAME vertex:"+n+"\n"+e,this._fragmentSourceCode=(this._shaderLanguage===S.WGSL?"//":"")+"#define SHADER_NAME fragment:"+r+"\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(u(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 r=P.GetShadersStore(this._shaderLanguage);if(r[e+t+"Shader"])return void n(r[e+t+"Shader"]);if(i&&r[e+i+"Shader"])return void n(r[e+i+"Shader"]);let s;s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:P.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(s+"."+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&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${n[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){var i,n,r;this._compilationError=e.message;const s=this._attributesNames,a=this._fallbacks;if(p.Error("Unable to compile effect:"),p.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),p.Error("Attributes: "+s.map((function(e){return" "+e}))),p.Error("Defines:\r\n"+this.defines),O.LogShaderCodeOnCompilationError){let e=null,t=null,s=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getVertexShaderCode())&&([s,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),s&&(p.Error("Vertex code:"),p.Error(s))),(null===(n=this._pipelineContext)||void 0===n?void 0:n._getFragmentShaderCode())&&([s,t]=this._getShaderCodeAndErrorLine(null===(r=this._pipelineContext)||void 0===r?void 0:r._getFragmentShaderCode(),this._compilationError,!0),s&&(p.Error("Fragment code:"),p.Error(s))),e&&p.Error(e),t&&p.Error(t)}p.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,p.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{const n=V.includes(i.substring(3))&&"FloatN";if(n){const r=this[`_cache${n}`];return function(){const n=this.engine[i];t.apply(this,arguments),r.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,r,s,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{s[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,r){let s=this._valueCache[arguments[0]];if(!s||s.length!==arguments.length-1)return s=Array.prototype.slice.call(arguments,1),this._valueCache[arguments[0]]=s,!0;let a=!1;for(let e=0;e{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&c()&&"ontouchend"in document},this._checkForMobile(),l()&&window.addEventListener("resize",this._checkForMobile);const e=navigator.userAgent;for(const t of K.ExceptionList){const n=t.key,r=t.targets;if(new RegExp(n).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,n=t.captureConstraint,r=new RegExp(i).exec(e);if(r&&r.length>0&&parseInt(r[r.length-1])>=n)continue}for(const e of r)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,p.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(this._initGLContext.bind(this))},s.addEventListener("webglcontextlost",this._onContextLost,!1),s.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=s.getContext("webgl2",i)||s.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(!s)throw new Error("The provided canvas is null or undefined.");try{this._gl=s.getContext("webgl",i)||s.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);const a=l()&&window.devicePixelRatio||1,o=i.limitDeviceRatio||a;this._hardwareScalingLevel=r?1/Math.min(o,a):1,this._lastDevicePixelRatio=a,this.resize(),this._isStencilEnable=!!i.stencil,this._initGLContext(),this._initFeatures();for(let e=0;e1?new w:new L,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);const h=`Babylon.js v${K.Version}`;console.log(h+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",h)}static get NpmPackage(){return"babylonjs@5.44.0"}static get Version(){return"5.44.0"}get description(){let e=this.name+this.webGLVersion;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return O.ShadersRepository}static set ShadersRepository(e){O.ShadersRepository=e}_getShaderProcessor(e){return this._shaderProcessor}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,this._depthCullingState.depthFunc=e?518:515)}get frameId(){return this._frameId}get supportsUniformBuffers(){return this.webGLVersion>1&&!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}get useExactSrgbConversions(){return this._useExactSrgbConversions}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 K._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}_restoreEngineAfterContextLost(e){setTimeout((async()=>{var t;this._dummyFramebuffer=null;const i=this._depthCullingState.depthTest,n=this._depthCullingState.depthFunc,r=this._depthCullingState.depthMask,s=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=r,this._stencilState.stencilTest=s,p.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}),0)}_sharedInit(e,t,i){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()}O.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")),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?256: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.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 l()?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 K.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 r=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=r;let s=0;t&&e&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),s|=this._gl.COLOR_BUFFER_BIT),i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),s|=this._gl.DEPTH_BUFFER_BIT),n&&(this._gl.clearStencil(0),s|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(s)}_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(),r=i||this.getRenderHeight(),s=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(s*n,a*r,n*e.width,r*e.height)}beginFrame(){}endFrame(){this._badOS&&this.flushFramebuffer(),this._frameId++}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const e=l()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}l()?(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,r,s=0,a=0){var o,l,h,c,u;const d=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(d._MSAAFramebuffer?d._MSAAFramebuffer:d._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,s,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,s);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,s,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,s):f.framebufferTexture2D(f.FRAMEBUFFER,i,f.TEXTURE_2D,null===(u=_._hardwareTexture)||void 0===u?void 0:u.underlyingResource,s)}this._cachedViewport&&!r?this.setViewport(this._cachedViewport,i,n):(i||(i=e.width,s&&(i/=Math.pow(2,s))),n||(n=e.height,s&&(n/=Math.pow(2,s))),this._viewport(0,0,i,n)),this.wipeCaches()}setState(e,t=0,i,n=!1,r,s,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:r)||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=s}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 r=e;this._currentRenderTarget=null;const s=this._gl;if(r._MSAAFramebuffer){if(e.isMulti)return void this.unBindMultiColorAttachmentFramebuffer(e,t,i);s.bindFramebuffer(s.READ_FRAMEBUFFER,r._MSAAFramebuffer),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,r._framebuffer),s.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,s.COLOR_BUFFER_BIT,s.NEAREST)}!(null===(n=e.texture)||void 0===n?void 0:n.generateMipMaps)||t||e.isCube||this.generateMipmaps(e.texture),i&&(r._MSAAFramebuffer&&this._bindUnboundFramebuffer(r._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 U(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 U(i);if(!i)throw new Error("Unable to create index buffer");this.bindIndexBuffer(n);const r=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),n.references=1,n.is32Bits=4===r.BYTES_PER_ELEMENT,n}_normalizeIndexData(e){if(2===e.BYTES_PER_ELEMENT)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let t=0;t=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,r=this._gl.getUniformBlockIndex(n,t);this._gl.uniformBlockBinding(n,r,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,r,s,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!==r&&(o.normalized=r,l=!0),o.stride!==s&&(o.stride=s,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=r,o.stride=s,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,s,a):this._gl.vertexAttribPointer(t,i,n,r,s,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 r=0;r=0){const t=n[r];let a=null;if(i&&(a=i[t]),a||(a=e[t]),!a)continue;this._gl.enableVertexAttribArray(s),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[s]=!0);const o=a.getBuffer();o&&(this._vertexAttribPointer(o,s,a.getSize(),a.type,a.normalized,a.byteStride,a.byteOffset),a.getIsInstanced()&&(this._gl.vertexAttribDivisor(s,a.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(s),this._currentInstanceBuffers.push(o))))}}}recordVertexArrayObject(e,t,i,n){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,n),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,n,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const t=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let s=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,s)),s+=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,r,s)}inlineShaderCode(e){return e}createPipelineContext(e){const t=new k;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,i,n,r=null){const s=n.createProgram();if(e.program=s,!s)throw new Error("Unable to create program");return n.attachShader(s,t),n.attachShader(s,i),n.linkProgram(s),e.context=n,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),s}_finalizePipelineContext(e){const t=e.context,i=e.vertexShader,n=e.fragmentShader,r=e.program;if(!t.getProgramParameter(r,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 s=t.getProgramInfoLog(r);if(s)throw e.programLinkError=s,new Error(s)}if(this.validateShaderPrograms&&(t.validateProgram(r),!t.getProgramParameter(r,t.VALIDATE_STATUS))){const i=t.getProgramInfoLog(r);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,r,s,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!==l||this._caps.textureFloatLinearFiltering)&&(2!==l||this._caps.textureHalfFloatLinearFiltering)||(h=1),1!==l||this._caps.textureFloat||(l=0,p.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const f=this._gl,_=new o(this,n),m=e.width||e,g=e.height||e,v=e.layers||0,E=this._getSamplingParameters(h,a),T=0!==v?f.TEXTURE_2D_ARRAY:f.TEXTURE_2D,C=this._getRGBABufferInternalSizedFormat(l,c,u),R=this._getInternalFormat(c),A=this._getWebGLTextureType(l);return this._bindTextureDirectly(T,_),0!==v?(_.is2DArray=!0,f.texImage3D(T,0,C,m,g,v,0,R,A,null)):f.texImage2D(T,0,C,m,g,0,R,A,null),f.texParameteri(T,f.TEXTURE_MAG_FILTER,E.mag),f.texParameteri(T,f.TEXTURE_MIN_FILTER,E.min),f.texParameteri(T,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(T,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),a&&this._gl.generateMipmap(T),this._bindTextureDirectly(T,null),_._useSRGBBuffer=u,_.baseWidth=m,_.baseHeight=g,_.width=m,_.height=g,_.depth=v,_.isReady=!0,_.samples=d,_.generateMipMaps=a,_.samplingMode=h,_.type=l,_.format=c,this._internalTexturesCache.push(_),_}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,n,r=3,a=null,l=null,h,c,u=null,d=null,_=null,m=null,g,v,E){const T="data:"===(e=e||"").substr(0,5),C="blob:"===e.substr(0,5),R=T&&-1!==e.indexOf(";base64,"),A=d||new o(this,s.Url),b=e;!this._transformTextureUrl||R||d||u||(e=this._transformTextureUrl(e)),b!==e&&(A._originalUrl=b);const S=e.lastIndexOf(".");let I=m||(S>-1?e.substring(S).toLowerCase():""),x=null;I.indexOf("?")>-1&&(I=I.split("?")[0]);for(const e of K._TextureLoaders)if(e.canLoad(I,g)){x=e;break}n&&n.addPendingData(A),A.url=e,A.generateMipMaps=!t,A.samplingMode=r,A.invertY=i,A._useSRGBBuffer=this._getUseSRGBBuffer(!!E,t),this._doNotHandleContextLost||(A._buffer=u);let y=null;a&&!d&&(y=A.onLoadedObservable.add(a)),d||this._internalTexturesCache.push(A);const M=(i,s)=>{n&&n.removePendingData(A),e===b?(y&&A.onLoadedObservable.remove(y),f.UseFallbackTexture&&this._createTextureBase(f.FallbackTexture,t,A.invertY,n,r,null,l,h,c,u,A),i=(i||"Unknown error")+(f.UseFallbackTexture?" - Fallback texture was used":""),A.onErrorObservable.notifyObservers({message:i,exception:s}),l&&l(i,s)):(p.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,A.invertY,n,r,a,l,h,c,u,A,_,m,g,v,E))};if(x){const t=e=>{x.loadData(e,A,((e,t,i,s,a,o)=>{o?M("TextureLoader failed to load data"):h(A,I,n,{width:e,height:t},A.invertY,!i,s,(()=>(a(),!1)),r)}),v)};u?u instanceof ArrayBuffer?t(new Uint8Array(u)):ArrayBuffer.isView(u)?t(u):l&&l("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)=>{M("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{C&&!this._doNotHandleContextLost&&(A._buffer=e),h(A,I,n,e,A.invertY,t,!1,c,r)};!T||R?u&&("string"==typeof u.decoding||u.close)?i(u):K._FileToolsLoadImage(e,i,M,n?n.offlineProvider:null,g,A.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof u||u instanceof ArrayBuffer||ArrayBuffer.isView(u)||u instanceof Blob?K._FileToolsLoadImage(u,i,M,n?n.offlineProvider:null,g,A.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):u&&i(u)}return A}createTexture(e,t,i,n,r=3,a=null,l=null,h=null,c=null,u=null,d=null,f,_,p,m){return this._createTextureBase(e,t,i,n,r,a,l,this._prepareWebGLTexture.bind(this),((e,t,i,r,a,l)=>{const h=this._gl,c=i.width===e&&i.height===t,d=u?this._getInternalFormat(u,a._useSRGBBuffer):".jpg"!==r||a._useSRGBBuffer?a._useSRGBBuffer?h.SRGB8_ALPHA8:h.RGBA:h.RGB;let f=u?this._getInternalFormat(u):".jpg"!==r||a._useSRGBBuffer?h.RGBA:h.RGB;if(a._useSRGBBuffer&&1===this.webGLVersion&&(f=d),c)return h.texImage2D(h.TEXTURE_2D,0,d,f,h.UNSIGNED_BYTE,i),!1;const _=this._caps.maxTextureSize;if(i.width>_||i.height>_||!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),h.texImage2D(h.TEXTURE_2D,0,d,f,h.UNSIGNED_BYTE,this._workingCanvas),a.width=e,a.height=t,1));{const e=new o(this,s.Temp);this._bindTextureDirectly(h.TEXTURE_2D,e,!0),h.texImage2D(h.TEXTURE_2D,0,d,f,h.UNSIGNED_BYTE,i),this._rescaleTexture(e,a,n,d,(()=>{this._releaseTexture(e),this._bindTextureDirectly(h.TEXTURE_2D,a,!0),l()}))}return!0}),h,c,u,d,f,_,m)}static _FileToolsLoadImage(e,t,i,n,r,s){throw _("FileTools")}_rescaleTexture(e,t,i,n,r){}createRawTexture(e,t,i,n,r,s,a,o=null,l=0,h=0,c=!1){throw _("Engine.RawTexture")}createRawCubeTexture(e,t,i,n,r,s,a,o=null){throw _("Engine.RawTexture")}createRawTexture3D(e,t,i,n,r,s,a,o,l=null,h=0){throw _("Engine.RawTexture")}createRawTexture2DArray(e,t,i,n,r,s,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),r=this._getSamplingParameters(e,t.generateMipMaps||i);this._setTextureParameterInteger(n,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(n,this._gl.TEXTURE_MIN_FILTER,r.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 r=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==n&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(n),e),e._cachedWrapR=n),this._bindTextureDirectly(r,null)}_setupDepthStencilTexture(e,t,i,n,r,s=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=s,e.generateMipMaps=!1,e.samplingMode=n?2:1,e.type=0,e._comparisonFunction=r;const h=this._gl,c=this._getTextureTarget(e),u=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(c,h.TEXTURE_MAG_FILTER,u.mag),h.texParameteri(c,h.TEXTURE_MIN_FILTER,u.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===r?(h.texParameteri(c,h.TEXTURE_COMPARE_FUNC,515),h.texParameteri(c,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(c,h.TEXTURE_COMPARE_FUNC,r),h.texParameteri(c,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,n,r,s=0,a=0){const o=this._gl;let l=o.TEXTURE_2D;if(e.isCube&&(l=o.TEXTURE_CUBE_MAP_POSITIVE_X+s),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,r)}_uploadDataToTextureDirectly(e,t,i=0,n=0,r,s=!1){const a=this._gl,o=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===r?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=a.TEXTURE_2D;e.isCube&&(c=a.TEXTURE_CUBE_MAP_POSITIVE_X+i);const u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),f=s?e.width:Math.pow(2,Math.max(u-n,0)),_=s?e.height:Math.pow(2,Math.max(d-n,0));a.texImage2D(c,n,h,f,_,0,l,o,t)}updateTextureData(e,t,i,n,r,s,a=0,o=0,l=!1){const h=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,f=h.TEXTURE_2D;e.isCube&&(f=h.TEXTURE_CUBE_MAP_POSITIVE_X+a,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(f,o,i,n,r,s,u,c,t),l&&this._gl.generateMipmap(f),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,n=0){const r=this._gl,s=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(s,e,!0),this._uploadDataToTextureDirectly(e,t,i,n),this._bindTextureDirectly(s,null,!0)}_prepareWebGLTextureContinuation(e,t,i,n,r){const s=this._gl;if(!s)return;const a=this._getSamplingParameters(r,!i);s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,a.mag),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,a.min),i||n||s.generateMipmap(s.TEXTURE_2D),this._bindTextureDirectly(s.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,n,r,s,a,o,l=3){const h=this.getCaps().maxTextureSize,c=Math.min(h,this.needPOTTextures?K.GetExponentOfTwo(n.width,h):n.width),u=Math.min(h,this.needPOTTextures?K.GetExponentOfTwo(n.height,h):n.height),d=this._gl;d&&(e._hardwareTexture?(this._bindTextureDirectly(d.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),e.baseWidth=n.width,e.baseHeight=n.height,e.width=c,e.height=u,e.isReady=!0,o(c,u,n,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,s,a,l)}))||this._prepareWebGLTextureContinuation(e,i,s,a,l)):i&&i.removePendingData(e))}_setupFramebufferDepthAttachments(e,t,i,n,r=1){const s=this._gl;if(e&&t)return this._createRenderBuffer(i,n,r,s.DEPTH_STENCIL,s.DEPTH24_STENCIL8,s.DEPTH_STENCIL_ATTACHMENT);if(t){let e=s.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=s.DEPTH_COMPONENT32F),this._createRenderBuffer(i,n,r,e,e,s.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,n,r,s.STENCIL_INDEX8,s.STENCIL_INDEX8,s.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,n,r,s,a=!0){const o=this._gl.createRenderbuffer();return this._updateRenderBuffer(o,e,t,i,n,r,s,a)}_updateRenderBuffer(e,t,i,n,r,s,a,o=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),n>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,n,s,t,i):l.renderbufferStorage(l.RENDERBUFFER,r,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!==(s=null===(r=null==t?void 0:t._hardwareTexture)||void 0===r?void 0:r.underlyingResource)&&void 0!==s?s: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,r=""){if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let s;s=n?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&s&&(s._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===s&&(i||this._bindSamplerUniformToChannel(s._associatedChannel,e),a=!1),this._activeChannel=e;const o=this._getTextureTarget(s);if(a&&this._bindTextureDirectly(o,s,i),s&&!s.isMultiview){if(s.isCube&&s._cachedCoordinatesMode!==t.coordinatesMode){s._cachedCoordinatesMode=t.coordinatesMode;const e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}s._cachedWrapU!==t.wrapU&&(s._cachedWrapU=t.wrapU,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),s)),s._cachedWrapV!==t.wrapV&&(s._cachedWrapV=t.wrapV,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),s)),s.is3D&&s._cachedWrapR!==t.wrapR&&(s._cachedWrapR=t.wrapR,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),s)),this._setAnisotropicLevel(o,s,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.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={},l()&&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,O.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 r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);const s=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&s===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,r=new Uint8Array(4);t.readPixels(0,0,1,1,e,n,r),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(n),t.deleteFramebuffer(r),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,r,s){const a=K._FileToolsLoadFile(e,t,i,n,r,s);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}static _FileToolsLoadFile(e,t,i,n,r,s){throw _("FileTools")}readPixels(e,t,i,n,r=!0,s=!0){const a=r?4:3,o=r?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(n*i*a);return s&&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=K.CeilingPOT(e),i=K.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let n;switch(i){case 1:n=K.FloorPOT(e);break;case 2:n=K.NearestPOT(e);break;default:n=K.CeilingPOT(e)}return Math.min(n,t)}static QueueNewFrame(e,t){if(l()){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:c()?document:null}}K.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"]}],K._TextureLoaders=[],K.CollisionsEpsilon=.001,K._IsSupported=null,K._HasMajorPerformanceCaveat=null;class q{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new Q(e)}sampleFrame(e=H.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 Q{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}}class j{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}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}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){j.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){j.Enabled&&(this._startMonitoringTime=H.Now)}endMonitoring(e=!0){if(!j.Enabled)return;e&&this.fetchNewFrame();const t=H.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=H.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}j.Enabled=!0,K.prototype.setAlphaConstants=function(e,t,i,n){this._alphaState.setAlphaBlendConstants(e,t,i,n)},K.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}},K.prototype.getAlphaMode=function(){return this._alphaMode},K.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}},K.prototype.getAlphaEquation=function(){return this._alphaEquation},K.prototype._readTexturePixelsSync=function(e,t,i,n=-1,r=0,s=null,a=!0,o=!1,l=0,h=0){var c,u;const d=this._gl;if(!d)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=d.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}d.bindFramebuffer(d.FRAMEBUFFER,this._dummyFramebuffer),n>-1?d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_CUBE_MAP_POSITIVE_X+n,null===(c=e._hardwareTexture)||void 0===c?void 0:c.underlyingResource,r):d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,r);let f=void 0!==e.type?this._getWebGLTextureType(e.type):d.UNSIGNED_BYTE;return o?s||(s=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 r=(ArrayBuffer,new Uint8Array(t));return n&&r.set(new Uint8Array(n)),r}(e.type,4*t*i)):f===d.UNSIGNED_BYTE?(s||(s=new Uint8Array(4*t*i)),f=d.UNSIGNED_BYTE):(s||(s=new Float32Array(4*t*i)),f=d.FLOAT),a&&this.flushFramebuffer(),d.readPixels(l,h,t,i,d.RGBA,f,s),d.bindFramebuffer(d.FRAMEBUFFER,this._currentFramebuffer),s},K.prototype._readTexturePixels=function(e,t,i,n=-1,r=0,s=null,a=!0,o=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,n,r,s,a,o,l,h))},K.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()},K.prototype.updateDynamicVertexBuffer=function(e,t,i,n){this.bindArrayBuffer(e),void 0===i&&(i=0);const r=t.byteLength||t.length;void 0===n||n>=r&&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 Z extends K{constructor(e,t,i,r=!1){if(super(e,t,i,r),this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.scenes=new Array,this._virtualScenes=new Array,this.onNewSceneAddedObservable=new n,this.postProcesses=new Array,this.isPointerLock=!1,this.onResizeObservable=new n,this.onCanvasBlurObservable=new n,this.onCanvasFocusObservable=new n,this.onCanvasPointerOutObservable=new n,this.onBeginFrameObservable=new n,this.customAnimationFrameRequester=null,this.onEndFrameObservable=new n,this.onBeforeShaderCompilationObservable=new n,this.onAfterShaderCompilationObservable=new n,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this._fps=60,this._deltaTime=0,this._drawCalls=new j,this.canvasTabIndex=1,this.disablePerformanceMonitorInBackground=!1,this._performanceMonitor=new q,this._compatibilityMode=!0,this.currentRenderPassId=0,this._renderPassNames=["main"],Z.Instances.push(this),e){if(this._features.supportRenderPasses=!0,i=this._creationOptions,e.getContext){const t=e;this._sharedInit(t,!!i.doNotHandleTouchAction,i.audioEngine),c()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&t&&Z._RequestPointerlock(t)},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=()=>{this.isPointerLock=document.pointerLockElement===t},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1),!Z.audioEngine&&i.audioEngine&&Z.AudioEngineFactory&&(Z.audioEngine=Z.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination()))),this._connectVREvents(),this.enableOfflineSupport=void 0!==Z.OfflineProviderFactory,this._deterministicLockstep=!!i.deterministicLockstep,this._lockstepMaxSteps=i.lockstepMaxSteps||0,this._timeStep=i.timeStep||1/60}this._prepareVRComponent(),i.autoEnableWebVR&&this.initWebVR()}}static get NpmPackage(){return K.NpmPackage}static get Version(){return K.Version}static get Instances(){return f.Instances}static get LastCreatedEngine(){return f.LastCreatedEngine}static get LastCreatedScene(){return f.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise(((i,n)=>{const r=new Image;r.onload=()=>{r.decode().then((()=>{this.createImageBitmap(r,t).then((e=>{i(e)}))}))},r.onerror=()=>{n(`Error loading image ${r.src}`)},r.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 n=this.getHostWindow();n&&"function"==typeof n.addEventListener&&(n.addEventListener("blur",this._onBlur),n.addEventListener("focus",this._onFocus)),e.addEventListener("pointerout",this._onCanvasPointerOut),t||this._disableTouchAction(),!Z.audioEngine&&i&&Z.AudioEngineFactory&&(Z.audioEngine=Z.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination()))}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 r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,n),r}scissorClear(e,t,i,n,r){this.enableScissor(e,t,i,n),this.clear(r,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,n){const r=this._gl;r.enable(r.SCISSOR_TEST),r.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,r)=>{this._loadFile(e,(e=>{n(e)}),void 0,t,i,((e,t)=>{r(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 r=null;t&&(t._textures.data[t._currentRenderTextureInd]?r=t._textures.data[t._currentRenderTextureInd]:t._forcedOutputTexture&&(r=t._forcedOutputTexture)),this._bindTexture(e,null!==(n=null==r?void 0:r.texture)&&void 0!==n?n:null,i)}setTextureFromPostProcessOutput(e,t,i){var n,r;this._bindTexture(e,null!==(r=null===(n=null==t?void 0:t._outputTexture)||void 0===n?void 0:n.texture)&&void 0!==r?r: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&&Z._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&Z._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&Z._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){Z._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&&r){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(s,r),e.transformFeedback=t}return n.linkProgram(s),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=n,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),s}_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=++Z._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],s,!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(s),s.dispose(),r&&r()})))}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){const t=new z(e,this._gl),i=new o(this,s.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}_uploadImageToTexture(e,t,i=0,n=0){const r=this._gl,s=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,a),l=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=r.TEXTURE_2D;e.isCube&&(h=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(h,n,o,a,s,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void p.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 U(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(((r,s)=>{const a=()=>{const o=n.clientWaitSync(e,t,0);o!=n.WAIT_FAILED?o!=n.TIMEOUT_EXPIRED?r():setTimeout(a,i):s()};a()}))}_readPixelsAsync(e,t,i,n,r,s,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,r,s,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===Z.Instances.length&&Z.audioEngine&&(Z.audioEngine.dispose(),Z.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)),c()&&(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=Z.Instances.indexOf(this);t>=0&&Z.Instances.splice(t,1),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(!l())return;const e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!l())return;const e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=Z.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){e.requestPointerLock&&(e.requestPointerLock(),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 r=0,s=0;try{s=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",r=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(n)}return{ascent:r,height:s,descent:s-r}}}Z.ALPHA_DISABLE=0,Z.ALPHA_ADD=1,Z.ALPHA_COMBINE=2,Z.ALPHA_SUBTRACT=3,Z.ALPHA_MULTIPLY=4,Z.ALPHA_MAXIMIZED=5,Z.ALPHA_ONEONE=6,Z.ALPHA_PREMULTIPLIED=7,Z.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Z.ALPHA_INTERPOLATE=9,Z.ALPHA_SCREENMODE=10,Z.DELAYLOADSTATE_NONE=0,Z.DELAYLOADSTATE_LOADED=1,Z.DELAYLOADSTATE_LOADING=2,Z.DELAYLOADSTATE_NOTLOADED=4,Z.NEVER=512,Z.ALWAYS=519,Z.LESS=513,Z.EQUAL=514,Z.LEQUAL=515,Z.GREATER=516,Z.GEQUAL=518,Z.NOTEQUAL=517,Z.KEEP=7680,Z.REPLACE=7681,Z.INCR=7682,Z.DECR=7683,Z.INVERT=5386,Z.INCR_WRAP=34055,Z.DECR_WRAP=34056,Z.TEXTURE_CLAMP_ADDRESSMODE=0,Z.TEXTURE_WRAP_ADDRESSMODE=1,Z.TEXTURE_MIRROR_ADDRESSMODE=2,Z.TEXTUREFORMAT_ALPHA=0,Z.TEXTUREFORMAT_LUMINANCE=1,Z.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Z.TEXTUREFORMAT_RGB=4,Z.TEXTUREFORMAT_RGBA=5,Z.TEXTUREFORMAT_RED=6,Z.TEXTUREFORMAT_R=6,Z.TEXTUREFORMAT_RG=7,Z.TEXTUREFORMAT_RED_INTEGER=8,Z.TEXTUREFORMAT_R_INTEGER=8,Z.TEXTUREFORMAT_RG_INTEGER=9,Z.TEXTUREFORMAT_RGB_INTEGER=10,Z.TEXTUREFORMAT_RGBA_INTEGER=11,Z.TEXTURETYPE_UNSIGNED_BYTE=0,Z.TEXTURETYPE_UNSIGNED_INT=0,Z.TEXTURETYPE_FLOAT=1,Z.TEXTURETYPE_HALF_FLOAT=2,Z.TEXTURETYPE_BYTE=3,Z.TEXTURETYPE_SHORT=4,Z.TEXTURETYPE_UNSIGNED_SHORT=5,Z.TEXTURETYPE_INT=6,Z.TEXTURETYPE_UNSIGNED_INTEGER=7,Z.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Z.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Z.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Z.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Z.TEXTURETYPE_UNSIGNED_INT_24_8=12,Z.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Z.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Z.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Z.TEXTURE_NEAREST_SAMPLINGMODE=1,Z.TEXTURE_BILINEAR_SAMPLINGMODE=2,Z.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Z.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Z.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Z.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Z.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Z.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Z.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Z.TEXTURE_NEAREST_LINEAR=7,Z.TEXTURE_NEAREST_NEAREST=1,Z.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Z.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Z.TEXTURE_LINEAR_LINEAR=2,Z.TEXTURE_LINEAR_NEAREST=12,Z.TEXTURE_EXPLICIT_MODE=0,Z.TEXTURE_SPHERICAL_MODE=1,Z.TEXTURE_PLANAR_MODE=2,Z.TEXTURE_CUBIC_MODE=3,Z.TEXTURE_PROJECTION_MODE=4,Z.TEXTURE_SKYBOX_MODE=5,Z.TEXTURE_INVCUBIC_MODE=6,Z.TEXTURE_EQUIRECTANGULAR_MODE=7,Z.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Z.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Z.SCALEMODE_FLOOR=1,Z.SCALEMODE_NEAREST=2,Z.SCALEMODE_CEILING=3,Z._RescalePostProcessFactory=null,Z._RenderPassIdCounter=0;const J=(e,t)=>e?e.getClassName&&"Mesh"===e.getClassName()?null:e.getClassName&&"SubMesh"===e.getClassName()?e.clone(t):e.clone?e.clone():null:null;class ${static DeepCopy(e,t,i,n){const r=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const s of r){if("_"===s[0]&&(!n||-1===n.indexOf(s)))continue;if(s.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(s))continue;const r=e[s],a=typeof r;if("function"!==a)try{if("object"===a)if(r instanceof Array){if(t[s]=[],r.length>0)if("object"==typeof r[0])for(let e=0;e(e.__proto__=t,e));const ne=3e3;class re extends ie{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",ie._setPrototypeOf(this,re.prototype)}}const se=e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,n,r,s,a,o,l,h="",c=0;const u=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|r>>6,l=63&r,isNaN(n)?o=l=64:isNaN(r)&&(l=64),h+=t.charAt(s)+t.charAt(a)+t.charAt(o)+t.charAt(l);return h},ae=e=>atob(e);class oe{static SetImmediate(e){l()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}const le=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class he extends re{constructor(e,t){super(e,4e3),this.name="LoadFileError",ie._setPrototypeOf(this,he.prototype),t instanceof ee?this.request=t:this.file=t}}class ce extends re{constructor(e,t){super(e,4001),this.request=t,this.name="RequestFileError",ie._setPrototypeOf(this,ce.prototype)}}class ue extends re{constructor(e,t){super(e,4002),this.file=t,this.name="ReadFileError",ie._setPrototypeOf(this,ue.prototype)}}const de={DefaultRetryStrategy:class{static ExponentialBackoff(e=3,t=500){return(i,n,r)=>0!==n.status||r>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,r)*t}}.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e},fe=e=>e.replace(/#/gm,"%23"),_e=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&de.CorsBehavior)if("string"==typeof de.CorsBehavior||de.CorsBehavior instanceof String)t.crossOrigin=de.CorsBehavior;else{const i=de.CorsBehavior(e);i&&(t.crossOrigin=i)}},pe=(e,t,i,n,r="",s)=>{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:r})),l=!0):o=`data:${r};base64,`+se(e):e instanceof Blob?(o=URL.createObjectURL(e),l=!0):(o=fe(e),o=de.PreprocessUrl(e));const h=f.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 ge(o,(n=>{h.createImageBitmap(new Blob([n],{type:r}),{premultiplyAlpha:"none",...s}).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 u=new Image;_e(o,u);const d=[],_=()=>{d.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),d.length=0};d.push({target:u,name:"load",handler:()=>{_(),t(u),l&&u.src&&URL.revokeObjectURL(u.src)}}),d.push({target:u,name:"error",handler:e=>{_(),c(e),l&&u.src&&URL.revokeObjectURL(u.src)}}),d.push({target:document,name:"securitypolicyviolation",handler:e=>{_();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);f.UseFallbackTexture=!1,c(t),l&&u.src&&URL.revokeObjectURL(u.src),u.src=""}}),d.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const p="blob:"===o.substring(0,5),m="data:"===o.substring(0,5),g=()=>{p||m?u.src=o:ge(o,((e,t,i)=>{const n=new Blob([e],{type:!r&&i?i:r}),s=URL.createObjectURL(n);l=!0,u.src=s}),void 0,n||void 0,!0,((e,t)=>{c(t)}))};if(!p&&!m&&n&&n.enableTexturesOffline)n.open((()=>{n&&n.loadImage(o,u)}),g);else{if(-1!==o.indexOf("file:")){const e=decodeURIComponent(o.substring(5).toLowerCase());if(te.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(te.FilesToLoad[e])}catch(i){t=URL.createObjectURL(te.FilesToLoad[e])}u.src=t,l=!0}catch(e){u.src=""}return u}}g()}return u},me=(e,t,i,r,s)=>{const a=new FileReader,o={onCompleteObservable:new n,abort:()=>a.abort()};return a.onloadend=()=>o.onCompleteObservable.notifyObservers(o),s&&(a.onerror=()=>{s(new ue(`Unable to read ${e.name}`,e))}),a.onload=e=>{t(e.target.result)},i&&(a.onprogress=i),r?a.readAsArrayBuffer(e):a.readAsText(e),o},ge=(e,t,i,r,s,a,o)=>{if(e.name)return me(e,t,i,s,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=te.FilesToLoad[e];if(n)return me(n,t,i,s,a?e=>a(void 0,new he(e.message,e.file)):void 0)}const{match:h,type:c}=Ce(l);if(h){const e={onCompleteObservable:new n,abort:()=>()=>{}};try{const e=s?Re(l):Ae(l);t(e,void 0,c)}catch(e){a?a(void 0,e):p.Error(e.message||"Failed to parse the Data URL")}return oe.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return ve(l,((e,i)=>{t(e,null==i?void 0:i.responseURL,null==i?void 0:i.getResponseHeader("content-type"))}),i,r,s,a?e=>{a(e.request,new he(e.message,e.request))}:void 0,o)},ve=(e,t,i,r,s,a,o)=>{e=fe(e),e=de.PreprocessUrl(e);const h=de.BaseUrl+e;let c=!1;const u={onCompleteObservable:new n,abort:()=>c=!0},d=()=>{let e,n=new ee,r=null;const d=()=>{n&&(i&&n.removeEventListener("progress",i),e&&n.removeEventListener("readystatechange",e),n.removeEventListener("loadend",f))};let f=()=>{d(),u.onCompleteObservable.notifyObservers(u),u.onCompleteObservable.clear(),i=void 0,e=null,f=null,a=void 0,o=void 0,t=void 0};u.abort=()=>{c=!0,f&&f(),n&&n.readyState!==(XMLHttpRequest.DONE||4)&&n.abort(),null!==r&&(clearTimeout(r),r=null),n=null};const _=e=>{const t=e.message||"Unknown error";a&&n?a(new ce(t,n)):p.Error(t)},m=u=>{if(n){if(n.open("GET",h),o)try{o(n)}catch(e){return void _(e)}s&&(n.responseType="arraybuffer"),i&&n.addEventListener("progress",i),f&&n.addEventListener("loadend",f),e=()=>{if(!c&&n&&n.readyState===(XMLHttpRequest.DONE||4)){if(e&&n.removeEventListener("readystatechange",e),n.status>=200&&n.status<300||0===n.status&&(!l()||Ee())){try{t&&t(s?n.response:n.responseText,n)}catch(e){_(e)}return}const i=de.DefaultRetryStrategy;if(i){const e=i(h,n,u);if(-1!==e)return d(),n=new ee,void(r=setTimeout((()=>m(u+1)),e))}const o=new ce("Error status: "+n.status+" "+n.statusText+" - Unable to load "+h,n);a&&a(o)}},n.addEventListener("readystatechange",e),n.send()}};m(0)};if(r&&r.enableSceneOffline){const n=e=>{e&&e.status>400?a&&a(e):d()},o=()=>{r&&r.loadFile(de.BaseUrl+e,(e=>{!c&&t&&t(e),u.onCompleteObservable.notifyObservers(u)}),i?e=>{!c&&i&&i(e)}:void 0,n,s)};r.open(o,n)}else d();return u},Ee=()=>"undefined"!=typeof location&&"file:"===location.protocol,Te=e=>le.test(e),Ce=e=>{const t=le.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function Re(e){return(e=>{const t=ae(e),i=t.length,n=new Uint8Array(new ArrayBuffer(i));for(let e=0;eae(e.split(",")[1]);let be;K._FileToolsLoadImage=pe,K._FileToolsLoadFile=ge,M._FileToolsLoadFile=ge,((e,t,i,n,r,s,a,o,l,h)=>{be={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:n,IsFileURL:r,LoadFile:s,LoadImage:a,ReadFile:o,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(be,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(be,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(be,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(be,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})})(Re,Ae,de,Te,Ee,ge,pe,me,ve,_e);const Se={};function Ie(e,t){Se[e]=t}function xe(e){return Se[e]}class ye{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=xe(e);if(t)return t;p.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)}))}ye.RegisteredExternalClasses={};class Pe{static get BaseUrl(){return de.BaseUrl}static set BaseUrl(e){de.BaseUrl=e}static get DefaultRetryStrategy(){return de.DefaultRetryStrategy}static set DefaultRetryStrategy(e){de.DefaultRetryStrategy=e}static get CorsBehavior(){return de.CorsBehavior}static set CorsBehavior(e){de.CorsBehavior=e}static get UseFallbackTexture(){return f.UseFallbackTexture}static set UseFallbackTexture(e){f.UseFallbackTexture=e}static get RegisteredExternalClasses(){return ye.RegisteredExternalClasses}static set RegisteredExternalClasses(e){ye.RegisteredExternalClasses=e}static get fallbackTexture(){return f.FallbackTexture}static set fallbackTexture(e){f.FallbackTexture=e}static FetchToRef(e,t,i,n,r,s){const a=4*((Math.abs(e)*i%i|0)+(Math.abs(t)*n%n|0)*i);s.r=r[a]/255,s.g=r[a+1]/255,s.b=r[a+2]/255,s.a=r[a+3]/255}static Mix(e,t,i){return e*(1-i)+t*i}static Instantiate(e){return ye.Instantiate(e)}static SetImmediate(e){oe.SetImmediate(e)}static IsExponentOfTwo(e){let t=1;do{t*=2}while(t{ge(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(!l())return void(null==i||i(`Cannot load script '${e}' outside of a window or a worker`));const r=document.getElementsByTagName("head")[0],s=document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("src",e),n&&(s.id=n),s.onload=()=>{t&&t()},s.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},r.appendChild(s)}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 r=new FileReader,s={onCompleteObservable:new n,abort:()=>r.abort()};return r.onloadend=()=>{s.onCompleteObservable.notifyObservers(s)},r.onload=e=>{t(e.target.result)},r.onprogress=i,r.readAsDataURL(e),s}static ReadFile(e,t,i,n,r){return me(e,t,i,n,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,n){$.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]),r=n.length,s=new Uint8Array(r);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,r="image/png"){throw _("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,n="image/png"){throw _("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,n,r="image/png",s=1,a=!1,o){throw _("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,n="image/png",r=1,s=!1,a){throw _("ScreenshotTools")}static RandomId(){return Me()}static IsBase64(e){return Te(e)}static DecodeBase64(e){return Re(e)}static get errorsCount(){return p.errorsCount}static Log(e){p.Log(e)}static Warn(e){p.Warn(e)}static Error(e){p.Error(e)}static get LogCache(){return p.LogCache}static ClearLogCache(){p.ClearLogCache()}static set LogLevels(e){p.LogLevels=e}static set PerformanceLogLevel(e){return(e&Pe.PerformanceUserMarkLogLevel)===Pe.PerformanceUserMarkLogLevel?(Pe.StartPerformanceCounter=Pe._StartUserMark,void(Pe.EndPerformanceCounter=Pe._EndUserMark)):(e&Pe.PerformanceConsoleLogLevel)===Pe.PerformanceConsoleLogLevel?(Pe.StartPerformanceCounter=Pe._StartPerformanceConsole,void(Pe.EndPerformanceCounter=Pe._EndPerformanceConsole)):(Pe.StartPerformanceCounter=Pe._StartPerformanceCounterDisabled,void(Pe.EndPerformanceCounter=Pe._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Pe._Performance){if(!l())return;Pe._Performance=window.performance}t&&Pe._Performance.mark&&Pe._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&Pe._Performance.mark&&(Pe._Performance.mark(e+"-End"),Pe._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Pe._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Pe._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return H.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 r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,n=r.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!!h()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}Pe.UseCustomRequestHeaders=!1,Pe.CustomRequestHeaders=ee.CustomRequestHeaders,Pe._TmpFloatArray=new Float32Array(1),Pe.GetDOMTextContent=u,Pe.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.")},Pe.NoneLogLevel=p.NoneLogLevel,Pe.MessageLogLevel=p.MessageLogLevel,Pe.WarningLogLevel=p.WarningLogLevel,Pe.ErrorLogLevel=p.ErrorLogLevel,Pe.AllLogLevel=p.AllLogLevel,Pe.IsWindowObjectExist=l,Pe.PerformanceNoneLogLevel=0,Pe.PerformanceUserMarkLogLevel=1,Pe.PerformanceConsoleLogLevel=2,Pe.StartPerformanceCounter=Pe._StartPerformanceCounterDisabled,Pe.EndPerformanceCounter=Pe._EndPerformanceCounterDisabled;class Oe{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{r&&r()?n.breakLoop():setTimeout((()=>{for(let s=0;s=e)break;if(i(a),r&&r()){n.breakLoop();break}}n.executeNext()}),s)}),n)}}f.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 De{constructor(e){this.length=0,this.data=new Array(e),this._id=De._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)}}De._GlobalId=0;class Ne extends De{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 Le{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),Le._HandleParenthesisContent(e,t)))):Le._HandleParenthesisContent(e,t))||"false"!==e&&Le.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 r=Le._SimplifyNegation(n[e].trim());const s=r.split("&&");if(s.length>1)for(let e=0;e(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}class we{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>we.HasTags(e),e.addTags=t=>we.AddTagsTo(e,t),e.removeTags=t=>we.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>we.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){we._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(we.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!we.HasTags(e))return;const i=t.split(" ");for(const t in i)we._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?we.HasTags(e):Le.Eval(t,(t=>we.HasTags(e)&&e._tags[t])))}}class Be{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=Be.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=Be.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let n=Be.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+Be.Sign(t-e)*i,n}static MoveTowardsAngle(e,t,i){const n=Be.DeltaAngle(e,t);let r=0;return-i180&&(n-=360),e+n*Be.Clamp(i)}static InverseLerp(e,t,i){let n=0;return n=e!=t?Be.Clamp((i-e)/(t-e)):0,n}static Hermite(e,t,i,n,r){const s=r*r,a=r*s;return e*(2*a-3*s+1)+i*(-2*a+3*s)+t*(a-2*s+r)+n*(a-s)}static Hermite1stDerivative(e,t,i,n,r){const s=r*r;return 6*(s-r)*e+(3*s-4*r+1)*t+6*(-s+r)*i+(3*s-2*r)*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-Be.TwoPi*Math.floor((e+Math.PI)/Be.TwoPi)}static HCF(e,t){const i=e%t;return 0===i?t:Be.HCF(t,i)}}Be.TwoPi=2*Math.PI;const Ue=1/2.2,Ve=2.2,ke=(Math.sqrt(5),.001);class Ge{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 r=function(){const n=e.length,s=r.previous.apply(e,arguments);return i(t,n),s};return n.next=r,r.previous=n,e[t]=r,()=>{const i=r.previous;if(!i)return;const n=r.next;n?(i.next=n,n.previous=i):(i.next=void 0,e[t]=i),r.next=void 0,r.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{null==e||e()}))}}const We=e=>parseInt(e.toString().replace(/\W/g,""));class He{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=We(this.x);return e=397*e^We(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return He.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&&Be.WithinEpsilon(this.x,e.x,t)&&Be.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 He.NormalizeToRef(this,this),this}clone(){return new this.constructor(this.x,this.y)}static Zero(){return new He(0,0)}static One(){return new He(1,1)}static get ZeroReadOnly(){return He._ZeroReadOnly}static FromArray(e,t=0){return new He(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,r){const s=r*r,a=r*s,o=.5*(2*t.x+(-e.x+i.x)*r+(2*e.x-5*t.x+4*i.x-n.x)*s+(-e.x+3*t.x-3*i.x+n.x)*a),l=.5*(2*t.y+(-e.y+i.y)*r+(2*e.y-5*t.y+4*i.y-n.y)*s+(-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:r,r=rt.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 He.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){const n=t.m,r=e.x*n[0]+e.y*n[4]+n[12],s=e.x*n[1]+e.y*n[5]+n[13];return i.x=r,i.y=s,i}static PointInTriangle(e,t,i,n){const r=.5*(-i.y*n.x+t.y*(-i.x+n.x)+t.x*(i.y-n.y)+i.x*n.y),s=r<0?-1:1,a=(t.y*n.x-t.x*n.y+(n.y-t.y)*e.x+(t.x-n.x)*e.y)*s,o=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*s;return a>0&&o>0&&a+o<2*r*s}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;return i*i+n*n}static Center(e,t){const i=new e.constructor;return He.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=He.DistanceSquared(t,i);if(0===n)return He.Distance(e,t);const r=i.subtract(t),s=Math.max(0,Math.min(1,He.Dot(e.subtract(t),r)/n)),a=t.add(r.multiplyByFloats(s,s));return He.Distance(e,a)}}He._ZeroReadOnly=He.Zero();class Ye{constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}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}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=We(this._x);return e=397*e^We(this._y),e=397*e^We(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 Ye.FromArrayToRef(e,t,this),this}toQuaternion(){return qe.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}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}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}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}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 r=t*Math.sin(i)*Math.cos(n),s=t*Math.cos(i),a=t*Math.sin(i)*Math.sin(n);return e.set(r,s,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,r=e.w*this.z+e.x*this.y-e.y*this.x,s=-e.x*this.x-e.y*this.y-e.z*this.z;return t.x=i*e.w+s*-e.x+n*-e.z-r*-e.y,t.y=n*e.w+s*-e.y+r*-e.x-i*-e.z,t.z=r*e.w+s*-e.z+i*-e.y-n*-e.x,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,r=e.d,s=je.Vector3[0];this.subtractToRef(t,s),s.normalize();const a=Ye.Dot(s,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(!Be.WithinEpsilon(t,i,e))return!0;const n=Math.abs(this._z);return!Be.WithinEpsilon(t,n,e)||!Be.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())||(je.Vector3[0].copyFrom(this),["x","y","z"].forEach(((t,i)=>{this[t]=je.Vector3[0][e[i]]}))),this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(je.Matrix[0]),Ye.TransformCoordinatesToRef(this,je.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,je.Vector3[0]),je.Vector3[0].rotateByQuaternionToRef(e,je.Vector3[0]),t.addToRef(je.Vector3[0],i),i}cross(e){const t=new this.constructor;return Ye.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}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.x=this.y=this.z=e,this}static GetClipFactor(e,t,i,n){const r=Ye.Dot(e,i)-n;return r/(r-(Ye.Dot(t,i)-n))}static GetAngleBetweenVectors(e,t,i){const n=e.normalizeToRef(je.Vector3[1]),r=t.normalizeToRef(je.Vector3[2]);let s=Ye.Dot(n,r);s=Be.Clamp(s,-1,1);const a=Math.acos(s),o=je.Vector3[3];return Ye.CrossToRef(n,r,o),Ye.Dot(o,i)>0?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(s)}static GetAngleBetweenVectorsOnPlane(e,t,i){je.Vector3[0].copyFrom(e);const n=je.Vector3[0];je.Vector3[1].copyFrom(t);const r=je.Vector3[1];je.Vector3[2].copyFrom(i);const s=je.Vector3[2],a=je.Vector3[3],o=je.Vector3[4];n.normalize(),r.normalize(),s.normalize(),Ye.CrossToRef(s,n,a),Ye.CrossToRef(a,s,o);const l=Math.atan2(Ye.Dot(r,a),Ye.Dot(r,o));return Be.NormalizeRadians(l)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const n=Ze.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}static PitchYawRollToMoveBetweenPoints(e,t){const i=Ye.Zero();return Ye.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,n){i=Be.Clamp(i,0,1);const r=je.Vector3[0],s=je.Vector3[1];r.copyFrom(e);const a=r.length();r.normalizeFromLength(a),s.copyFrom(t);const o=s.length();s.normalizeFromLength(o);const l=Ye.Dot(r,s);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 r.scaleInPlace(h),s.scaleInPlace(c),n.copyFrom(r).addInPlace(s),n.scaleInPlace(Be.Lerp(a,o,i)),n}static SmoothToRef(e,t,i,n,r){return Ye.SlerpToRef(e,t,0===n?1:i/n,r),r}static FromArray(e,t=0){return new Ye(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return Ye.FromArray(e,t)}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i}static FromFloatArrayToRef(e,t,i){return Ye.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,n){return n.copyFromFloats(e,t,i),n}static Zero(){return new Ye(0,0,0)}static One(){return new Ye(1,1,1)}static Up(){return new Ye(0,1,0)}static get UpReadOnly(){return Ye._UpReadOnly}static get DownReadOnly(){return Ye._DownReadOnly}static get RightReadOnly(){return Ye._RightReadOnly}static get LeftReadOnly(){return Ye._LeftReadOnly}static get LeftHandedForwardReadOnly(){return Ye._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return Ye._RightHandedForwardReadOnly}static get ZeroReadOnly(){return Ye._ZeroReadOnly}static Down(){return new Ye(0,-1,0)}static Forward(e=!1){return new Ye(0,0,e?-1:1)}static Backward(e=!1){return new Ye(0,0,e?1:-1)}static Right(){return new Ye(1,0,0)}static Left(){return new Ye(-1,0,0)}static TransformCoordinates(e,t){const i=Ye.Zero();return Ye.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return Ye.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,n,r){const s=n.m,a=e*s[0]+t*s[4]+i*s[8]+s[12],o=e*s[1]+t*s[5]+i*s[9]+s[13],l=e*s[2]+t*s[6]+i*s[10]+s[14],h=1/(e*s[3]+t*s[7]+i*s[11]+s[15]);return r.x=a*h,r.y=o*h,r.z=l*h,r}static TransformNormal(e,t){const i=Ye.Zero();return Ye.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,r){const s=n.m;return r.x=e*s[0]+t*s[4]+i*s[8],r.y=e*s[1]+t*s[5]+i*s[9],r.z=e*s[2]+t*s[6]+i*s[10],r}static CatmullRom(e,t,i,n,r){const s=r*r,a=r*s,o=.5*(2*t._x+(-e._x+i._x)*r+(2*e._x-5*t._x+4*i._x-n._x)*s+(-e._x+3*t._x-3*i._x+n._x)*a),l=.5*(2*t._y+(-e._y+i._y)*r+(2*e._y-5*t._y+4*i._y-n._y)*s+(-e._y+3*t._y-3*i._y+n._y)*a),h=.5*(2*t._z+(-e._z+i._z)*r+(2*e._z-5*t._z+4*i._z-n._z)*s+(-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 Ye.ClampToRef(e,t,i,n),n}static ClampToRef(e,t,i,n){let r=e._x;r=r>i._x?i._x:r,r=ri._y?i._y:s,s=si._z?i._z:a,a=a0&&S<0?(x.copyFrom(s),y=t,M=i):S>0&&I<0?(x.copyFrom(o),y=i,M=n):(x.copyFrom(a).scaleInPlace(-1),y=n,M=t);const P=je.Vector3[9],O=je.Vector3[4];if(y.subtractToRef(g,C),M.subtractToRef(g,P),Ye.CrossToRef(C,P,O),!(Ye.Dot(O,l)<0))return r.copyFrom(g),Math.abs(_*p);const D=je.Vector3[5];Ye.CrossToRef(x,O,D),D.normalize();const N=je.Vector3[9];N.copyFrom(y).subtractInPlace(g);const F=N.length();if(Fthis.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 Ye(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 Ke(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 Ke.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,n,r){return r.x=e,r.y=t,r.z=i,r.w=n,r}static Zero(){return new Ke(0,0,0,0)}static One(){return new Ke(1,1,1,1)}static get ZeroReadOnly(){return Ke._ZeroReadOnly}static Normalize(e){const t=Ke.Zero();return Ke.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(Ke.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,n=e.y-t.y,r=e.z-t.z,s=e.w-t.w;return i*i+n*n+r*r+s*s}static Center(e,t){return Ke.CenterToRef(e,t,Ke.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=Ke.Zero();return Ke.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return Ke.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,n,r){const s=n.m,a=e*s[0]+t*s[4]+i*s[8]+s[12],o=e*s[1]+t*s[5]+i*s[9]+s[13],l=e*s[2]+t*s[6]+i*s[10]+s[14],h=e*s[3]+t*s[7]+i*s[11]+s[15];return r.x=a,r.y=o,r.z=l,r.w=h,r}static TransformNormal(e,t){const i=new e.constructor;return Ke.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){const n=t.m,r=e.x*n[0]+e.y*n[4]+e.z*n[8],s=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=r,i.y=s,i.z=a,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,n,r,s){const a=r.m;return s.x=e*a[0]+t*a[4]+i*a[8],s.y=e*a[1]+t*a[5]+i*a[9],s.z=e*a[2]+t*a[6]+i*a[10],s.w=n,s}static FromVector3(e,t=0){return new Ke(e._x,e._y,e._z,t)}}Ke._ZeroReadOnly=Ke.Zero();class qe{constructor(e=0,t=0,i=0,n=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=n}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}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=We(this._x);return e=397*e^We(this._y),e=397*e^We(this._z),e=397*e^We(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&&Be.WithinEpsilon(this._x,e._x,t)&&Be.WithinEpsilon(this._y,e._y,t)&&Be.WithinEpsilon(this._z,e._z,t)&&Be.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}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)}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}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}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}scaleInPlace(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,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}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,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,s=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,n,r,s),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}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=Ye.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,n=this._y,r=this._w,s=n*t-i*r,a=.4999999;if(s<-a)e.y=2*Math.atan2(n,r),e.x=Math.PI/2,e.z=0;else if(s>a)e.y=2*Math.atan2(n,r),e.x=-Math.PI/2,e.z=0;else{const a=r*r,o=t*t,l=i*i,h=n*n;e.z=Math.atan2(2*(i*n+t*r),-o-l+h+a),e.x=Math.asin(-2*s),e.y=Math.atan2(2*(t*i+n*r),o-l-h+a)}return e}toRotationMatrix(e){return Qe.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return qe.FromRotationMatrixToRef(e,this),this}static FromRotationMatrix(e){const t=new qe;return qe.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,n=i[0],r=i[4],s=i[8],a=i[1],o=i[5],l=i[9],h=i[2],c=i[6],u=i[10],d=n+o+u;let f;return d>0?(f=.5/Math.sqrt(d+1),t.w=.25/f,t.x=(c-l)*f,t.y=(s-h)*f,t.z=(a-r)*f):n>o&&n>u?(f=2*Math.sqrt(1+n-o-u),t.w=(c-l)/f,t.x=.25*f,t.y=(r+a)/f,t.z=(s+h)/f):o>u?(f=2*Math.sqrt(1+o-n-u),t.w=(s-h)/f,t.x=(r+a)/f,t.y=.25*f,t.z=(l+c)/f):(f=2*Math.sqrt(1+u-n-o),t.w=(a-r)/f,t.x=(s+h)/f,t.y=(l+c)/f,t.z=.25*f),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=qe.Dot(e,t);return 1-n*n<=i}static SmoothToRef(e,t,i,n,r){let s=0===n?1:i/n;return s=Be.Clamp(s,0,1),qe.SlerpToRef(e,t,s,r),r}static Zero(){return new qe(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 qe(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 qe.RotationAxisToRef(e,t,new qe)}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}static FromArray(e,t){return t||(t=0),new qe(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 FromEulerAngles(e,t,i){const n=new qe;return qe.RotationYawPitchRollToRef(t,e,i,n),n}static FromEulerAnglesToRef(e,t,i,n){return qe.RotationYawPitchRollToRef(t,e,i,n),n}static FromEulerVector(e){const t=new qe;return qe.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return qe.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i){const n=Ye.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):(Ye.CrossToRef(e,t,Ze.Vector3[0]),i.set(Ze.Vector3[0].x,Ze.Vector3[0].y,Ze.Vector3[0].z,n)),i.normalize()}static RotationYawPitchRoll(e,t,i){const n=new qe;return qe.RotationYawPitchRollToRef(e,t,i,n),n}static RotationYawPitchRollToRef(e,t,i,n){const r=.5*i,s=.5*t,a=.5*e,o=Math.sin(r),l=Math.cos(r),h=Math.sin(s),c=Math.cos(s),u=Math.sin(a),d=Math.cos(a);return n.x=d*h*l+u*c*o,n.y=u*c*l-d*h*o,n.z=d*c*o-u*h*l,n.w=d*c*l+u*h*o,n}static RotationAlphaBetaGamma(e,t,i){const n=new qe;return qe.RotationAlphaBetaGammaToRef(e,t,i,n),n}static RotationAlphaBetaGammaToRef(e,t,i,n){const r=.5*(i+e),s=.5*(i-e),a=.5*t;return n.x=Math.cos(s)*Math.sin(a),n.y=Math.sin(s)*Math.sin(a),n.z=Math.sin(r)*Math.cos(a),n.w=Math.cos(r)*Math.cos(a),n}static RotationQuaternionFromAxis(e,t,i){const n=new qe(0,0,0,0);return qe.RotationQuaternionFromAxisToRef(e,t,i,n),n}static RotationQuaternionFromAxisToRef(e,t,i,n){const r=je.Matrix[0];return Qe.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),r),qe.FromRotationMatrixToRef(r,n),n}static FromLookDirectionLH(e,t){const i=new qe;return qe.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const n=je.Matrix[0];return Qe.LookDirectionLHToRef(e,t,n),qe.FromRotationMatrixToRef(n,i),i}static FromLookDirectionRH(e,t){const i=new qe;return qe.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const n=je.Matrix[0];return Qe.LookDirectionRHToRef(e,t,n),qe.FromRotationMatrixToRef(n,i)}static Slerp(e,t,i){const n=qe.Identity();return qe.SlerpToRef(e,t,i,n),n}static SlerpToRef(e,t,i,n){let r,s,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)s=1-i,r=o?-i:i;else{const e=Math.acos(a),t=1/Math.sin(e);s=Math.sin((1-i)*e)*t,r=o?-Math.sin(i*e)*t:Math.sin(i*e)*t}return n.x=s*e._x+r*t._x,n.y=s*e._y+r*t._y,n.z=s*e._z+r*t._z,n.w=s*e._w+r*t._w,n}static Hermite(e,t,i,n,r){const s=r*r,a=r*s,o=2*a-3*s+1,l=-2*a+3*s,h=a-2*s+r,c=a-s,u=e._x*o+i._x*l+t._x*h+n._x*c,d=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(u,d,f,_)}static Hermite1stDerivative(e,t,i,n,r){const s=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,n,r,s),s}static Hermite1stDerivativeToRef(e,t,i,n,r,s){const a=r*r;return s.x=6*(a-r)*e.x+(3*a-4*r+1)*t.x+6*(-a+r)*i.x+(3*a-2*r)*n.x,s.y=6*(a-r)*e.y+(3*a-4*r+1)*t.y+6*(-a+r)*i.y+(3*a-2*r)*n.y,s.z=6*(a-r)*e.z+(3*a-4*r+1)*t.z+6*(-a+r)*i.z+(3*a-2*r)*n.z,s.w=6*(a-r)*e.w+(3*a-4*r+1)*t.w+6*(-a+r)*i.w+(3*a-2*r)*n.w,s}}class Qe{constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,G.MatrixTrackPrecisionChange&&G.MatrixTrackedMatrices.push(this),this._m=new G.MatrixCurrentType(16),this.markAsUpdated()}static get Use64Bits(){return G.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=Qe._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}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],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],h=e[8],c=e[9],u=e[10],d=e[11],f=e[12],_=e[13],p=e[14],m=e[15],g=u*m-p*d,v=c*m-_*d,E=c*p-_*u,T=h*m-f*d,C=h*p-u*f,R=h*_-f*c;return t*+(a*g-o*v+l*E)+i*-(s*g-o*T+l*C)+n*+(s*v-a*T+l*R)+r*-(s*E-a*C+o*R)}toArray(){return this._m}asArray(){return this._m}invert(){return this.invertToRef(this),this}reset(){return Qe.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,r=e.m;for(let e=0;e<16;e++)n[e]=i[e]+r[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 Qe.IdentityToRef(e),e;const t=this._m,i=t[0],n=t[1],r=t[2],s=t[3],a=t[4],o=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],f=t[11],_=t[12],p=t[13],m=t[14],g=t[15],v=d*g-m*f,E=u*g-p*f,T=u*m-p*d,C=c*g-_*f,R=c*m-d*_,A=c*p-_*u,b=+(o*v-l*E+h*T),S=-(a*v-l*C+h*R),I=+(a*E-o*C+h*A),x=-(a*T-o*R+l*A),y=i*b+n*S+r*I+s*x;if(0===y)return e.copyFrom(this),e;const M=1/y,P=l*g-m*h,O=o*g-p*h,D=o*m-p*l,N=a*g-_*h,F=a*m-_*l,L=a*p-_*o,w=l*f-d*h,B=o*f-u*h,U=o*d-u*l,V=a*f-c*h,k=a*d-c*l,G=a*u-c*o,z=-(n*v-r*E+s*T),X=+(i*v-r*C+s*R),W=-(i*E-n*C+s*A),H=+(i*T-n*R+r*A),Y=+(n*P-r*O+s*D),K=-(i*P-r*N+s*F),q=+(i*O-n*N+s*L),Q=-(i*D-n*F+r*L),j=-(n*w-r*B+s*U),Z=+(i*w-r*V+s*k),J=-(i*B-n*V+s*G),$=+(i*U-n*k+r*G);return Qe.FromValuesToRef(b*M,z*M,Y*M,j*M,S*M,X*M,K*M,Z*M,I*M,W*M,q*M,J*M,x*M,H*M,Q*M,$*M,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 Ye(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 Qe.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,r=e.m,s=n[0],a=n[1],o=n[2],l=n[3],h=n[4],c=n[5],u=n[6],d=n[7],f=n[8],_=n[9],p=n[10],m=n[11],g=n[12],v=n[13],E=n[14],T=n[15],C=r[0],R=r[1],A=r[2],b=r[3],S=r[4],I=r[5],x=r[6],y=r[7],M=r[8],P=r[9],O=r[10],D=r[11],N=r[12],F=r[13],L=r[14],w=r[15];return t[i]=s*C+a*S+o*M+l*N,t[i+1]=s*R+a*I+o*P+l*F,t[i+2]=s*A+a*x+o*O+l*L,t[i+3]=s*b+a*y+o*D+l*w,t[i+4]=h*C+c*S+u*M+d*N,t[i+5]=h*R+c*I+u*P+d*F,t[i+6]=h*A+c*x+u*O+d*L,t[i+7]=h*b+c*y+u*D+d*w,t[i+8]=f*C+_*S+p*M+m*N,t[i+9]=f*R+_*I+p*P+m*F,t[i+10]=f*A+_*x+p*O+m*L,t[i+11]=f*b+_*y+p*D+m*w,t[i+12]=g*C+v*S+E*M+T*N,t[i+13]=g*R+v*I+E*P+T*F,t[i+14]=g*A+v*x+E*O+T*L,t[i+15]=g*b+v*y+E*D+T*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=We(this._m[0]);for(let t=1;t<16;t++)e=397*e^We(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new qe,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 r=this._m;if(i&&i.copyFromFloats(r[12],r[13],r[14]),(e=e||je.Vector3[0]).x=Math.sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]),e.y=Math.sqrt(r[4]*r[4]+r[5]*r[5]+r[6]*r[6]),e.z=Math.sqrt(r[8]*r[8]+r[9]*r[9]+r[10]*r[10]),n){const t=n.scaling.x<0?-1:1,i=n.scaling.y<0?-1:1,r=n.scaling.z<0?-1:1;e.x*=t,e.y*=i,e.z*=r}else this.determinant()<=0&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const i=1/e._x,n=1/e._y,s=1/e._z;Qe.FromValuesToRef(r[0]*i,r[1]*i,r[2]*i,0,r[4]*n,r[5]*n,r[6]*n,0,r[8]*s,r[9]*s,r[10]*s,0,0,0,0,1,je.Matrix[0]),qe.FromRotationMatrixToRef(je.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new Ke(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 Qe.TransposeToRef(this,e),e}transposeToRef(e){return Qe.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,n,r){if(e<0||e>3)return this;const s=4*e;return this._m[s+0]=t,this._m[s+1]=i,this._m[s+2]=n,this._m[s+3]=r,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=je.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return Qe.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=je.Vector3[0];if(!this.decompose(t))return Qe.IdentityToRef(e),e;const i=this._m,n=1/t._x,r=1/t._y,s=1/t._z;return Qe.FromValuesToRef(i[0]*n,i[1]*n,i[2]*n,0,i[4]*r,i[5]*r,i[6]*r,0,i[8]*s,i[9]*s,i[10]*s,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 Qe;return Qe.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 r=0;r<16;r++)n._m[r]=e[r+t]*i;return n.markAsUpdated(),n}static get IdentityReadOnly(){return Qe._IdentityReadOnly}static FromValuesToRef(e,t,i,n,r,s,a,o,l,h,c,u,d,f,_,p,m){const g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=n,g[4]=r,g[5]=s,g[6]=a,g[7]=o,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=f,g[14]=_,g[15]=p,m.markAsUpdated()}static FromValues(e,t,i,n,r,s,a,o,l,h,c,u,d,f,_,p){const m=new Qe,g=m._m;return g[0]=e,g[1]=t,g[2]=i,g[3]=n,g[4]=r,g[5]=s,g[6]=a,g[7]=o,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=f,g[14]=_,g[15]=p,m.markAsUpdated(),m}static Compose(e,t,i){const n=new Qe;return Qe.ComposeToRef(e,t,i,n),n}static ComposeToRef(e,t,i,n){const r=n._m,s=t._x,a=t._y,o=t._z,l=t._w,h=s+s,c=a+a,u=o+o,d=s*h,f=s*c,_=s*u,p=a*c,m=a*u,g=o*u,v=l*h,E=l*c,T=l*u,C=e._x,R=e._y,A=e._z;return r[0]=(1-(p+g))*C,r[1]=(f+T)*C,r[2]=(_-E)*C,r[3]=0,r[4]=(f-T)*R,r[5]=(1-(d+g))*R,r[6]=(m+v)*R,r[7]=0,r[8]=(_+E)*A,r[9]=(m-v)*A,r[10]=(1-(d+p))*A,r[11]=0,r[12]=i._x,r[13]=i._y,r[14]=i._z,r[15]=1,n.markAsUpdated(),n}static Identity(){const e=Qe.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 Qe.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=Qe.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 Qe;return Qe.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 Qe.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 Qe;return Qe.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),n=Math.cos(e);return Qe.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 Qe;return Qe.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),n=Math.cos(e);return Qe.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 Qe;return Qe.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const n=Math.sin(-t),r=Math.cos(-t),s=1-r;e.normalize();const a=i._m;return a[0]=e._x*e._x*s+r,a[1]=e._x*e._y*s-e._z*n,a[2]=e._x*e._z*s+e._y*n,a[3]=0,a[4]=e._y*e._x*s+e._z*n,a[5]=e._y*e._y*s+r,a[6]=e._y*e._z*s-e._x*n,a[7]=0,a[8]=e._z*e._x*s-e._y*n,a[9]=e._z*e._y*s+e._x*n,a[10]=e._z*e._z*s+r,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=Ye.Dot(t,e),r=i._m;if(n<-.999)r[0]=-1,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=-1,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=1,r[11]=0;else{const i=Ye.Cross(t,e),s=1/(1+n);r[0]=i._x*i._x*s+n,r[1]=i._y*i._x*s-i._z,r[2]=i._z*i._x*s+i._y,r[3]=0,r[4]=i._x*i._y*s+i._z,r[5]=i._y*i._y*s+n,r[6]=i._z*i._y*s-i._x,r[7]=0,r[8]=i._x*i._z*s-i._y,r[9]=i._y*i._z*s+i._x,r[10]=i._z*i._z*s+n,r[11]=0}return r[12]=0,r[13]=0,r[14]=0,r[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const n=new Qe;return Qe.RotationYawPitchRollToRef(e,t,i,n),n}static RotationYawPitchRollToRef(e,t,i,n){return qe.RotationYawPitchRollToRef(e,t,i,je.Quaternion[0]),je.Quaternion[0].toRotationMatrix(n),n}static Scaling(e,t,i){const n=new Qe;return Qe.ScalingToRef(e,t,i,n),n}static ScalingToRef(e,t,i,n){return Qe.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 Qe;return Qe.TranslationToRef(e,t,i,n),n}static TranslationToRef(e,t,i,n){return Qe.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 Qe.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){const r=n._m,s=e.m,a=t.m;for(let e=0;e<16;e++)r[e]=s[e]*(1-i)+a[e]*i;return n.markAsUpdated(),n}static DecomposeLerp(e,t,i){const n=new e.constructor;return Qe.DecomposeLerpToRef(e,t,i,n),n}static DecomposeLerpToRef(e,t,i,n){const r=je.Vector3[0],s=je.Quaternion[0],a=je.Vector3[1];e.decompose(r,s,a);const o=je.Vector3[2],l=je.Quaternion[1],h=je.Vector3[3];t.decompose(o,l,h);const c=je.Vector3[4];Ye.LerpToRef(r,o,i,c);const u=je.Quaternion[2];qe.SlerpToRef(s,l,i,u);const d=je.Vector3[5];return Ye.LerpToRef(a,h,i,d),Qe.ComposeToRef(c,u,d,n),n}static LookAtLH(e,t,i){const n=new Qe;return Qe.LookAtLHToRef(e,t,i,n),n}static LookAtLHToRef(e,t,i,n){const r=je.Vector3[0],s=je.Vector3[1],a=je.Vector3[2];t.subtractToRef(e,a),a.normalize(),Ye.CrossToRef(i,a,r);const o=r.lengthSquared();0===o?r.x=1:r.normalizeFromLength(Math.sqrt(o)),Ye.CrossToRef(a,r,s),s.normalize();const l=-Ye.Dot(r,e),h=-Ye.Dot(s,e),c=-Ye.Dot(a,e);Qe.FromValuesToRef(r._x,s._x,a._x,0,r._y,s._y,a._y,0,r._z,s._z,a._z,0,l,h,c,1,n)}static LookAtRH(e,t,i){const n=new Qe;return Qe.LookAtRHToRef(e,t,i,n),n}static LookAtRHToRef(e,t,i,n){const r=je.Vector3[0],s=je.Vector3[1],a=je.Vector3[2];e.subtractToRef(t,a),a.normalize(),Ye.CrossToRef(i,a,r);const o=r.lengthSquared();0===o?r.x=1:r.normalizeFromLength(Math.sqrt(o)),Ye.CrossToRef(a,r,s),s.normalize();const l=-Ye.Dot(r,e),h=-Ye.Dot(s,e),c=-Ye.Dot(a,e);return Qe.FromValuesToRef(r._x,s._x,a._x,0,r._y,s._y,a._y,0,r._z,s._z,a._z,0,l,h,c,1,n),n}static LookDirectionLH(e,t){const i=new Qe;return Qe.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const n=je.Vector3[0];n.copyFrom(e),n.scaleInPlace(-1);const r=je.Vector3[1];return Ye.CrossToRef(t,n,r),Qe.FromValuesToRef(r._x,r._y,r._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 Qe;return Qe.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const n=je.Vector3[2];return Ye.CrossToRef(t,e,n),Qe.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,r){const s=new Qe;return Qe.OrthoLHToRef(e,t,i,n,s,r),s}static OrthoLHToRef(e,t,i,n,r,s){const a=2/e,o=2/t,l=2/(n-i),h=-(n+i)/(n-i);return Qe.FromValuesToRef(a,0,0,0,0,o,0,0,0,0,l,0,0,0,h,1,r),s&&r.multiplyToRef(Je,r),r._updateIdentityStatus(1===a&&1===o&&1===l&&0===h),r}static OrthoOffCenterLH(e,t,i,n,r,s,a){const o=new Qe;return Qe.OrthoOffCenterLHToRef(e,t,i,n,r,s,o,a),o}static OrthoOffCenterLHToRef(e,t,i,n,r,s,a,o){const l=2/(t-e),h=2/(n-i),c=2/(s-r),u=-(s+r)/(s-r),d=(e+t)/(e-t),f=(n+i)/(i-n);return Qe.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,0,d,f,u,1,a),o&&a.multiplyToRef(Je,a),a.markAsUpdated(),a}static OrthoOffCenterRH(e,t,i,n,r,s,a){const o=new Qe;return Qe.OrthoOffCenterRHToRef(e,t,i,n,r,s,o,a),o}static OrthoOffCenterRHToRef(e,t,i,n,r,s,a,o){return Qe.OrthoOffCenterLHToRef(e,t,i,n,r,s,a,o),a._m[10]*=-1,a}static PerspectiveLH(e,t,i,n,r,s=0){const a=new Qe,o=2*i/e,l=2*i/t,h=(n+i)/(n-i),c=-2*n*i/(n-i),u=Math.tan(s);return Qe.FromValuesToRef(o,0,0,0,0,l,0,u,0,0,h,1,0,0,c,0,a),r&&a.multiplyToRef(Je,a),a._updateIdentityStatus(!1),a}static PerspectiveFovLH(e,t,i,n,r,s=0,a=!1){const o=new Qe;return Qe.PerspectiveFovLHToRef(e,t,i,n,o,!0,r,s,a),o}static PerspectiveFovLHToRef(e,t,i,n,r,s=!0,a,o=0,l=!1){const h=i,c=n,u=1/Math.tan(.5*e),d=s?u/t:u,f=s?u:u*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 Qe.FromValuesToRef(d,0,0,0,0,f,0,m,0,0,_,1,0,0,p,0,r),a&&r.multiplyToRef(Je,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,n,r,s=!0,a,o=0){const l=1/Math.tan(.5*e),h=s?l/t:l,c=s?l:l*t,u=Math.tan(o);return Qe.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,1,0,0,1,0,r),a&&r.multiplyToRef(Je,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,n,r,s=0,a=!1){const o=new Qe;return Qe.PerspectiveFovRHToRef(e,t,i,n,o,!0,r,s,a),o}static PerspectiveFovRHToRef(e,t,i,n,r,s=!0,a,o=0,l=!1){const h=i,c=n,u=1/Math.tan(.5*e),d=s?u/t:u,f=s?u:u*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 Qe.FromValuesToRef(d,0,0,0,0,f,0,m,0,0,_,-1,0,0,p,0,r),a&&r.multiplyToRef(Je,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,n,r,s=!0,a,o=0){const l=1/Math.tan(.5*e),h=s?l/t:l,c=s?l:l*t,u=Math.tan(o);return Qe.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,-1,0,0,-1,0,r),a&&r.multiplyToRef(Je,r),r._updateIdentityStatus(!1),r}static PerspectiveFovWebVRToRef(e,t,i,n,r=!1,s,a=0){const o=r?-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),u=Math.tan(e.rightDegrees*Math.PI/180),d=2/(c+u),f=2/(l+h),_=Math.tan(a),p=n._m;return p[0]=d,p[1]=p[2]=p[3]=p[4]=0,p[5]=f,p[6]=0,p[7]=_,p[8]=(c-u)*d*.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),s&&n.multiplyToRef(Je,n),n.markAsUpdated(),n}static GetFinalMatrix(e,t,i,n,r,s){const a=e.width,o=e.height,l=e.x,h=e.y,c=Qe.FromValues(a/2,0,0,0,0,-o/2,0,0,0,0,s-r,0,l+a/2,o/2+h,r,1),u=new t.constructor;return t.multiplyToRef(i,u),u.multiplyToRef(n,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return G.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 G.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new e.constructor;return Qe.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 Qe;return Qe.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,n=e.normal.y,r=e.normal.z,s=-2*i,a=-2*n,o=-2*r;return Qe.FromValuesToRef(s*i+1,a*i,o*i,0,s*n,a*n+1,o*n,0,s*r,a*r,o*r+1,0,s*e.d,a*e.d,o*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,n){return Qe.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,r=e._z*e._z,s=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+r),t._m[1]=2*(s+a),t._m[2]=2*(o-l),t._m[3]=0,t._m[4]=2*(s-a),t._m[5]=1-2*(r+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}}Qe._UpdateFlagSeed=0,Qe._IdentityReadOnly=Qe.Identity();class je{}je.Vector3=Ge.BuildTuple(11,Ye.Zero),je.Matrix=Ge.BuildTuple(2,Qe.Identity),je.Quaternion=Ge.BuildTuple(3,qe.Zero);class Ze{}Ze.Vector2=Ge.BuildTuple(3,He.Zero),Ze.Vector3=Ge.BuildTuple(13,Ye.Zero),Ze.Vector4=Ge.BuildTuple(3,Ke.Zero),Ze.Quaternion=Ge.BuildTuple(2,qe.Zero),Ze.Matrix=Ge.BuildTuple(8,Qe.Identity),Ie("BABYLON.Vector2",He),Ie("BABYLON.Vector3",Ye),Ie("BABYLON.Vector4",Ke),Ie("BABYLON.Matrix",Qe);const Je=Qe.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class $e{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 r in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,r)&&this._BabylonFileParsers[r](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 et(e,t,i,n){var r,s=arguments.length,a=s<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--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,i,a):r(t,i))||a);return s>3&&a&&Object.defineProperty(t,i,a),a}$e._BabylonFileParsers={},$e._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=Be.Clamp(this.r,e,t),i.g=Be.Clamp(this.g,e,t),i.b=Be.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"#"+Be.ToHex(e)+Be.ToHex(t)+Be.ToHex(i)}toLinearSpace(){const e=new tt;return this.toLinearSpaceToRef(e),e}toHSV(){const e=new tt;return this.toHSVToRef(e),e}toHSVToRef(e){const t=this.r,i=this.g,n=this.b,r=Math.max(t,i,n),s=Math.min(t,i,n);let a=0,o=0;const l=r,h=r-s;0!==r&&(o=h/r),r!=s&&(r==t?(a=(i-n)/h,i=0&&s<=1?(o=r,l=a):s>=1&&s<=2?(o=a,l=r):s>=2&&s<=3?(l=r,h=a):s>=3&&s<=4?(l=a,h=r):s>=4&&s<=5?(o=a,h=r):s>=5&&s<=6&&(o=r,h=a);const c=i-r;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,r){const s=r*r,a=r*s,o=2*a-3*s+1,l=-2*a+3*s,h=a-2*s+r,c=a-s,u=e.r*o+i.r*l+t.r*h+n.r*c,d=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(u,d,f)}static Hermite1stDerivative(e,t,i,n,r){const s=tt.Black();return this.Hermite1stDerivativeToRef(e,t,i,n,r,s),s}static Hermite1stDerivativeToRef(e,t,i,n,r,s){const a=r*r;s.r=6*(a-r)*e.r+(3*a-4*r+1)*t.r+6*(-a+r)*i.r+(3*a-2*r)*n.r,s.g=6*(a-r)*e.g+(3*a-4*r+1)*t.g+6*(-a+r)*i.g+(3*a-2*r)*n.g,s.b=6*(a-r)*e.b+(3*a-4*r+1)*t.b+6*(-a+r)*i.b+(3*a-2*r)*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=Be.Clamp(this.r,e,t),i.g=Be.Clamp(this.g,e,t),i.b=Be.Clamp(this.b,e,t),i.a=Be.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"#"+Be.ToHex(t)+Be.ToHex(i)+Be.ToHex(n);const r=Math.round(255*this.a);return"#"+Be.ToHex(t)+Be.ToHex(i)+Be.ToHex(n)+Be.ToHex(r)}toLinearSpace(){const e=new it;return this.toLinearSpaceToRef(e),e}toLinearSpaceToRef(e){return e.r=Math.pow(this.r,Ve),e.g=Math.pow(this.g,Ve),e.b=Math.pow(this.b,Ve),e.a=this.a,this}toGammaSpace(){const e=new it;return this.toGammaSpaceToRef(e),e}toGammaSpaceToRef(e){return e.r=Math.pow(this.r,Ue),e.g=Math.pow(this.g,Ue),e.b=Math.pow(this.b,Ue),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),r=9===e.length?parseInt(e.substring(7,9),16):255;return it.FromInts(t,i,n,r)}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,r){const s=r*r,a=r*s,o=2*a-3*s+1,l=-2*a+3*s,h=a-2*s+r,c=a-s,u=e.r*o+i.r*l+t.r*h+n.r*c,d=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(u,d,f,_)}static Hermite1stDerivative(e,t,i,n,r){const s=new it;return this.Hermite1stDerivativeToRef(e,t,i,n,r,s),s}static Hermite1stDerivativeToRef(e,t,i,n,r,s){const a=r*r;s.r=6*(a-r)*e.r+(3*a-4*r+1)*t.r+6*(-a+r)*i.r+(3*a-2*r)*n.r,s.g=6*(a-r)*e.g+(3*a-4*r+1)*t.g+6*(-a+r)*i.g+(3*a-2*r)*n.g,s.b=6*(a-r)*e.b+(3*a-4*r+1)*t.b+6*(-a+r)*i.b+(3*a-2*r)*n.b,s.a=6*(a-r)*e.a+(3*a-4*r+1)*t.a+6*(-a+r)*i.a+(3*a-2*r)*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))),Ie("BABYLON.Color3",tt),Ie("BABYLON.Color4",it);const rt={},st={},at=function(e,t,i){const n=e();we&&we.AddTagsTo(n,t.tags);const r=ot(n);for(const e in r){const s=r[e],a=t[e],o=s.type;if(null!=a&&("uniqueId"!==e||Et.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(st[t])return st[t];st[t]={};const i=st[t];let n=e,r=t;for(;r;){const e=rt[r];for(const t in e)i[t]=e[t];let t,s=!1;do{if(t=Object.getPrototypeOf(n),!t.getClassName){s=!0;break}if(t.getClassName()!==r)break;n=t}while(t);if(s)break;r=t.getClassName(),n=t}return i}function lt(e,t){return(i,n)=>{const r=function(e){const t=e.getClassName();return rt[t]||(rt[t]={}),rt[t]}(i);r[n]||(r[n]={type:e,sourceName:t})}}function ht(e,t=null){return function(e,t=null){return(i,n)=>{const r=t||"_"+n;Object.defineProperty(i,n,{get:function(){return this[r]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[r]!==t&&(this[r]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function ct(e){return lt(0,e)}function ut(e){return lt(1,e)}function dt(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(6,e)}function gt(e){return lt(8,e)}function vt(e){return lt(9,e)}class Et{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{let s=r;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];s=n?(...t)=>n(...t)?e(...t):r(...t):e}return e[t]=s,s(...i)}}Et.AllowLoadingUniqueId=!1,Et._ImageProcessingConfigurationParser=e=>{throw _("ImageProcessingConfiguration")},Et._FresnelParametersParser=e=>{throw _("FresnelParameters")},Et._ColorCurvesParser=e=>{throw _("ColorCurves")},Et._TextureParser=(e,t,i)=>{throw _("Texture")},Tt.filter=function(e){return(t,i,n)=>Tt(t,i,n,e)};class Ct{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,r,s;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===(s=null===(r=this._externalProperties)||void 0===r?void 0:r[e])||void 0===s?void 0:s.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 Rt),this)}serialize(){return Et.Serialize(this)}static Parse(e){return Et.Parse((()=>new Rt),e,null,null)}}et([ct()],Rt.prototype,"_globalHue",void 0),et([ct()],Rt.prototype,"_globalDensity",void 0),et([ct()],Rt.prototype,"_globalSaturation",void 0),et([ct()],Rt.prototype,"_globalExposure",void 0),et([ct()],Rt.prototype,"_highlightsHue",void 0),et([ct()],Rt.prototype,"_highlightsDensity",void 0),et([ct()],Rt.prototype,"_highlightsSaturation",void 0),et([ct()],Rt.prototype,"_highlightsExposure",void 0),et([ct()],Rt.prototype,"_midtonesHue",void 0),et([ct()],Rt.prototype,"_midtonesDensity",void 0),et([ct()],Rt.prototype,"_midtonesSaturation",void 0),et([ct()],Rt.prototype,"_midtonesExposure",void 0),Et._ColorCurvesParser=Rt.Parse;class At extends Ct{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 bt{constructor(){this.colorCurves=new Rt,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=bt.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=bt.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new n}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&&Rt.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===bt._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType===bt.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&&Rt.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 r=null!=t?t:n/i;let s=Math.tan(.5*this.vignetteCameraFov),a=s*r;const o=Math.sqrt(a*s);a=Pe.Mix(a,o,this.vignetteStretch),s=Pe.Mix(s,o,this.vignetteStretch),e.setFloat4("vignetteSettings1",a,s,-a*this.vignetteCenterX,-s*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 Et.Clone((()=>new bt),this)}serialize(){return Et.Serialize(this)}static Parse(e){const t=Et.Parse((()=>new bt),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 St,It,xt,yt,Mt,Pt,Ot,Dt;bt.TONEMAPPING_STANDARD=0,bt.TONEMAPPING_ACES=1,bt._VIGNETTEMODE_MULTIPLY=0,bt._VIGNETTEMODE_OPAQUE=1,et([lt(7,undefined)],bt.prototype,"colorCurves",void 0),et([ct()],bt.prototype,"_colorCurvesEnabled",void 0),et([ut("colorGradingTexture")],bt.prototype,"_colorGradingTexture",void 0),et([ct()],bt.prototype,"_colorGradingEnabled",void 0),et([ct()],bt.prototype,"_colorGradingWithGreenDepth",void 0),et([ct()],bt.prototype,"_colorGradingBGR",void 0),et([ct()],bt.prototype,"_exposure",void 0),et([ct()],bt.prototype,"_toneMappingEnabled",void 0),et([ct()],bt.prototype,"_toneMappingType",void 0),et([ct()],bt.prototype,"_contrast",void 0),et([ct()],bt.prototype,"vignetteStretch",void 0),et([ct()],bt.prototype,"vignetteCenterX",void 0),et([ct()],bt.prototype,"vignetteCenterY",void 0),et([ct()],bt.prototype,"vignetteWeight",void 0),et([gt()],bt.prototype,"vignetteColor",void 0),et([ct()],bt.prototype,"vignetteCameraFov",void 0),et([ct()],bt.prototype,"_vignetteBlendMode",void 0),et([ct()],bt.prototype,"_vignetteEnabled",void 0),et([ct()],bt.prototype,"_ditheringEnabled",void 0),et([ct()],bt.prototype,"_ditheringIntensity",void 0),et([ct()],bt.prototype,"_skipFinalColorClamp",void 0),et([ct()],bt.prototype,"_applyByPostProcess",void 0),et([ct()],bt.prototype,"_isEnabled",void 0),Et._ImageProcessingConfigurationParser=bt.Parse,K.prototype.createUniformBuffer=function(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");const i=new U(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},K.prototype.createDynamicUniformBuffer=function(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");const i=new U(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},K.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)},K.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},K.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},K.prototype.bindUniformBlock=function(e,t,i){const n=e.program,r=this._gl.getUniformBlockIndex(n,t);4294967295!==r&&this._gl.uniformBlockBinding(n,r,i)};class Nt{constructor(e,t,i,n,r=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,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&&(Nt._UpdatedUbosInFrame[this._name]||(Nt._UpdatedUbosInFrame[this._name]=0),Nt._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 p.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!==r){if(i instanceof Array){const e=this.byteOffset/4;return i.slice(e,e+r)}if(i instanceof ArrayBuffer)return new Float32Array(i,this.byteOffset,r);{let e=i.byteOffset+this.byteOffset;if(t){const t=new Float32Array(r),n=new Float32Array(i.buffer,e,r);return t.set(n),t}const n=e%4;return n&&(e=Math.max(0,e-n)),new Float32Array(i.buffer,e,r)}}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,r,s,a,o){if(e instanceof Array){let r=t/4;const a=i/4;for(let t=0;t{let i=e.getWorldMatrix();e.nonUniformScaling&&(Ze.Matrix[0].copyFrom(i),i=Ze.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(Ze.Matrix[1]),i=Ze.Matrix[1]),Ye.TransformNormalToRef(t,i,t)};if(e&&r(this.pickedMesh,n),this.ray){const t=Ze.Vector3[0].copyFrom(n);e||r(this.pickedMesh,t),Ye.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=He.FromArray(t,2*e[3*this.faceId]),n=He.FromArray(t,2*e[3*this.faceId+1]),r=He.FromArray(t,2*e[3*this.faceId+2]);return i=i.scale(this.bu),n=n.scale(this.bv),r=r.scale(1-this.bu-this.bv),new He(i.x+n.x+r.x,i.y+n.y+r.y)}}class Bt{constructor(e,t,i,n,r,s){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=n,this.sourceEvent=r,this.additionalData=s}static CreateNew(e,t,i){const n=e.getScene();return new Bt(e,n.pointerX,n.pointerY,n.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,n){return new Bt(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,n)}static CreateNewFromScene(e,t){return new Bt(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,n){return new Bt(e,t.x,t.y,null,i,n)}}class Ut{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,r=0,s=!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 qt.Triggers)if(Object.prototype.hasOwnProperty.call(qt.Triggers,t)&&parseInt(t)===e)return!0;return!1}}qt.Triggers={};class Qt{}Qt.KEYDOWN=1,Qt.KEYUP=2;class jt{constructor(e,t){this.type=e,this.event=t}}class Zt extends jt{constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}}!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"}(St||(St={})),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"}(It||(It={})),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"}(yt||(yt={})),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"}(Mt||(Mt={})),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"}(Pt||(Pt={})),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"}(Ot||(Ot={})),function(e){e[e.PointerMove=0]="PointerMove",e[e.PointerDown=1]="PointerDown",e[e.PointerUp=2]="PointerUp"}(Dt||(Dt={}));class Jt{}Jt.DOM_DELTA_PIXEL=0,Jt.DOM_DELTA_LINE=1,Jt.DOM_DELTA_PAGE=2;class $t{static CreateDeviceEvent(e,t,i,n,r,s){switch(e){case St.Keyboard:return this._CreateKeyboardEvent(i,n,r,s);case St.Mouse:if(i===It.MouseWheelX||i===It.MouseWheelY||i===It.MouseWheelZ)return this._CreateWheelEvent(e,t,i,n,r,s);case St.Touch:return this._CreatePointerEvent(e,t,i,n,r,s);default:throw`Unable to generate event for device ${St[e]}`}}static _CreatePointerEvent(e,t,i,n,r,s){const a=this._CreateMouseEvent(e,t,i,n,r,s);return e===St.Mouse?(a.deviceType=St.Mouse,a.pointerId=1,a.pointerType="mouse"):(a.deviceType=St.Touch,a.pointerId=t,a.pointerType="touch"),i===It.Move?a.type="pointermove":i>=It.LeftClick&&i<=It.RightClick&&(a.type=1===n?"pointerdown":"pointerup",a.button=i-2),a}static _CreateWheelEvent(e,t,i,n,r,s){const a=this._CreateMouseEvent(e,t,i,n,r,s);switch(a.type="wheel",a.deltaMode=Jt.DOM_DELTA_PIXEL,a.deltaX=0,a.deltaY=0,a.deltaZ=0,i){case It.MouseWheelX:a.deltaX=n;break;case It.MouseWheelY:a.deltaY=n;break;case It.MouseWheelZ:a.deltaZ=n}return a}static _CreateMouseEvent(e,t,i,n,r,s){const a=this._CreateEvent(s),o=r.pollInput(e,t,It.Horizontal),l=r.pollInput(e,t,It.Vertical);return s?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-s.getBoundingClientRect().x,a.offsetY=a.movementY-s.getBoundingClientRect().y):(a.movementX=r.pollInput(e,t,xt.DeltaHorizontal),a.movementY=r.pollInput(e,t,xt.DeltaVertical),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,r),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 r=this._CreateEvent(n);return this._CheckNonCharacterKeys(r,i),r.deviceType=St.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=1===t?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(St.Keyboard),n=i&&1===t.pollInput(St.Keyboard,0,18),r=i&&1===t.pollInput(St.Keyboard,0,17),s=i&&(1===t.pollInput(St.Keyboard,0,91)||1===t.pollInput(St.Keyboard,0,92)||1===t.pollInput(St.Keyboard,0,93)),a=i&&1===t.pollInput(St.Keyboard,0,16);e.altKey=n,e.ctrlKey=r,e.metaKey=s,e.shiftKey=a}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class ei{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,n,r)=>{const s=$t.CreateDeviceEvent(e,t,n,r,this);i(e,t,s)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===St.Mouse||e===St.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const ti=Object.keys(It).length/2;class ii{constructor(e,t,i,n){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Pe.IsSafari(),this._usingMacOS=/(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=d.IsNavigatorAvailable()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=Pe.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 ${St[e]}`;e>=St.DualShock&&e<=St.DualSense&&this._updateDevice(e,t,i);const r=n[i];if(void 0===r)throw`Unable to find input ${i} for device ${St[e]} in slot ${t}`;return i===It.Move&&Pe.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=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(St.Keyboard,0,255));const t=this._inputs[St.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(St.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(St.Keyboard,0,255));const t=this._inputs[St.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=$t.CreateDeviceEvent(St.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(St.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(St.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[St.Keyboard][0];for(let t=0;t{const t=this._getPointerType(e),i=t===St.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 r=e;r.inputIndex=It.Move,n[It.Horizontal]=e.clientX,n[It.Vertical]=e.clientY,this._onInputChanged(t,i,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,n[e.button+2]=n[e.button+2]?0:1,this._onInputChanged(t,i,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===St.Mouse?0:e.pointerId;if(t===St.Touch){const t=this._activeTouchIds.indexOf(-1);if(!(t>=0))return void Pe.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===St.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const n=this._inputs[t][i];if(n){const r=n[It.Horizontal],s=n[It.Vertical];if(t===St.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[It.Horizontal]=e.clientX,n[It.Vertical]=e.clientY,n[e.button+2]=1;const a=e;a.inputIndex=e.button+2,this._onInputChanged(t,i,a),r===e.clientX&&s===e.clientY||(a.inputIndex=It.Move,this._onInputChanged(t,i,a))}},this._pointerUpEvent=e=>{var t,i,n,r,s;const a=this._getPointerType(e),o=a===St.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(a===St.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[It.Horizontal],h=l[It.Vertical];l[It.Horizontal]=e.clientX,l[It.Vertical]=e.clientY,l[e.button+2]=0;const c=e;t===e.clientX&&h===e.clientY||(c.inputIndex=It.Move,this._onInputChanged(a,o,c)),c.inputIndex=e.button+2,a===St.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===(s=(r=this._elementToAttachTo).hasPointerCapture)||void 0===s?void 0:s.call(r,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(a,o,c),a===St.Touch&&this._onDeviceDisconnected(a,o)}},this._pointerCancelEvent=e=>{var t,i,n,r;if("mouse"===e.pointerType){const e=this._inputs[St.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=It.LeftClick;t<=It.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=$t.CreateDeviceEvent(St.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(St.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);(null===(r=(n=this._elementToAttachTo).hasPointerCapture)||void 0===r?void 0:r.call(n,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[St.Touch][t][It.LeftClick]=0;const i=$t.CreateDeviceEvent(St.Touch,t,It.LeftClick,0,this,this._elementToAttachTo);this._onInputChanged(St.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(St.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,r;if(this.isDeviceAvailable(St.Mouse)){const i=this._inputs[St.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=It.LeftClick;e<=It.BrowserForward;e++)if(1===i[e]){i[e]=0;const t=$t.CreateDeviceEvent(St.Mouse,0,e,0,this,this._elementToAttachTo);this._onInputChanged(St.Mouse,0,t)}}if(this.isDeviceAvailable(St.Touch)){const e=this._inputs[St.Touch];for(let t=0;t{const t=St.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,ti));const i=this._inputs[t][0];if(i){i[It.MouseWheelX]=e.deltaX||0,i[It.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[It.MouseWheelZ]=e.deltaZ||0;const n=e;0!==i[It.MouseWheelX]&&(n.inputIndex=It.MouseWheelX,this._onInputChanged(t,0,n)),0!==i[It.MouseWheelY]&&(n.inputIndex=It.MouseWheelY,this._onInputChanged(t,0,n)),0!==i[It.MouseWheelZ]&&(n.inputIndex=It.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(St.Mouse)){const e=this._inputs[St.Mouse][0];e[It.MouseWheelX]=0,e[It.MouseWheelY]=0,e[It.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 r=this._inputs[e][t];i>=n.buttons.length?r[i]=n.axes[i-n.buttons.length].valueOf():r[i]=n.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?St.DualSense:St.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?St.Xbox:-1!==e.indexOf("057e")?St.Switch:St.Generic}_getPointerType(e){let t=St.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=St.Touch),t}}class ni{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new n,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class ri{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(St).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 ni(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)},r=(e,t,i)=>{if(i)for(const n of this._registeredManagers)n._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new ei(i,n,r):this._deviceInputSystem=new ii(e,i,n,r)}dispose(){this._deviceInputSystem.dispose()}}class si{constructor(e){const t=Object.keys(St).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new ri(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new n((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new n,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}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)):[]}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 r=null===(i=this._devices[e])||void 0===i?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(r),(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,r;null===(r=null===(n=this._devices[e])||void 0===n?void 0:n[t])||void 0===r||r.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case St.Keyboard:case St.Mouse:this._firstDevice[e]=0;break;case St.Touch:case St.DualSense:case St.DualShock:case St.Xbox:case St.Switch:case St.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i=It.MouseWheelX&&t.inputIndex<=It.MouseWheelZ?Wt.POINTERWHEEL:Wt.POINTERMOVE;let a;i.onPointerMove&&(e=e||this._pickMove(t.pointerId),i.onPointerMove(t,e,s)),e?(a=new Kt(s,t,e),this._setRayOnPointerInfo(e,t)):(a=new Kt(s,t,null,this),this._movePointerInfo=a),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(a,s)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,Qe.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,r=new Yt(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,e.originMesh&&(r.nearInteractionPickingInfo=e)),n.onPrePointerObservable.notifyObservers(r,i),!!r.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,e),!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,e)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=It.Move,this._checkPrePointerObservable(e,i,Wt.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,Wt.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,Bt.CreateNew(e.pickedMesh,t)),t.button){case 0:n.processTrigger(2,Bt.CreateNew(e.pickedMesh,t));break;case 1:n.processTrigger(4,Bt.CreateNew(e.pickedMesh,t));break;case 2:n.processTrigger(3,Bt.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>oi.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,n.processTrigger(8,Bt.CreateNew(e.pickedMesh,t)))}),oi.LongPressDelay)}}else for(const n of i._pointerDownStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let n;const r=Wt.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),n=new Kt(r,t,e),this._setRayOnPointerInfo(e,t)):n=new Kt(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(n,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const n=new PointerEvent("pointerup",t);n.inputIndex=It.Move;const r=new ai;i?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,n,Wt.POINTERUP)||this._processPointerUp(e,n,r)}_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=Wt.POINTERPICK,r=new Kt(i,t,e);this._setRayOnPointerInfo(e,t),n.onPointerObservable.notifyObservers(r,i)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,Bt.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,Bt.CreateNew(e.pickedMesh,t,e));const n=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&n&&n.processTrigger(6,Bt.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const r of n._pointerUpStage)e=r.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,Bt.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new Kt(Wt.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),n.onPointerObservable.notifyObservers(r,Wt.POINTERUP),n.onPointerUp&&n.onPointerUp(t,e,Wt.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=Wt.POINTERTAP:i.doubleClick&&(r=Wt.POINTERDOUBLETAP),r){const i=new Kt(r,t,e);n.onPointerObservable.hasObservers()&&n.onPointerObservable.hasSpecificMask(r)&&n.onPointerObservable.notifyObservers(i,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,n=null){const r=this._scene,s=r.getEngine();n||(n=s.getInputElement()),this._alreadyAttached&&this.detachControl(),n&&(this._alreadyAttachedTo=n),this._deviceSourceManager=new si(s),this._initActionManager=e=>{if(!this._meshPickProceed){const t=r.skipPointerUpPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,!1,r.cameraToUseForPointers);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{(Date.now()-this._previousStartingPointerTime>oi.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,i(t,this._currentPickResult))},this._initClickEvent=(e,t,i,n)=>{const r=new ai;this._currentPickResult=null;let s=null,a=e.hasSpecificMask(Wt.POINTERPICK)||t.hasSpecificMask(Wt.POINTERPICK)||e.hasSpecificMask(Wt.POINTERTAP)||t.hasSpecificMask(Wt.POINTERTAP)||e.hasSpecificMask(Wt.POINTERDOUBLETAP)||t.hasSpecificMask(Wt.POINTERDOUBLETAP);!a&&qt&&(s=this._initActionManager(s,r),s&&(a=s.hasPickTriggers));let o=!1;if(a){const a=i.button;if(r.hasSwiped=this._isPointerSwiping(),!r.hasSwiped){let i=!oi.ExclusiveDoubleClickMode;i||(i=!e.hasSpecificMask(Wt.POINTERDOUBLETAP)&&!t.hasSpecificMask(Wt.POINTERDOUBLETAP),i&&!qt.HasSpecificTrigger(6)&&(s=this._initActionManager(s,r),s&&(i=!s.hasSpecificTrigger(6)))),i?(Date.now()-this._previousStartingPointerTime>oi.DoubleClickDelay||a!==this._previousButtonPressed)&&(r.singleClick=!0,n(r,this._currentPickResult),o=!0):(this._previousDelayedSimpleClickTimeout=this._delayedSimpleClickTimeout,this._delayedSimpleClickTimeout=window.setTimeout(this._delayedSimpleClick.bind(this,a,r,n),oi.DoubleClickDelay));let l=e.hasSpecificMask(Wt.POINTERDOUBLETAP)||t.hasSpecificMask(Wt.POINTERDOUBLETAP);!l&&qt.HasSpecificTrigger(6)&&(s=this._initActionManager(s,r),s&&(l=s.hasSpecificTrigger(6))),l&&(a===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)>oi.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>oi.DragMovementThreshold),this._checkPrePointerObservable(null,e,e.inputIndex>=It.MouseWheelX&&e.inputIndex<=It.MouseWheelZ?Wt.POINTERWHEEL:Wt.POINTERMOVE))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking)return void this._processPointerMove(new wt,e);r.pointerMovePredicate||(r.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!r.cameraToUseForPointers||0!=(r.cameraToUseForPointers.layerMask&e.layerMask)));const t=r._registeredActions>0?this._pickMove(e.pointerId):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,void 0===e.pointerId&&(e.pointerId=0),this._updatePointerPosition(e),-1===this._swipeButtonPressed&&(this._swipeButtonPressed=e.button),r.preventDefaultOnPointerDown&&n&&(e.preventDefault(),n.focus()),this._startingPointerPosition.x=this._pointerX,this._startingPointerPosition.y=this._pointerY,this._startingPointerTime=Date.now(),this._checkPrePointerObservable(null,e,Wt.POINTERDOWN))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;let t;this._pointerCaptures[e.pointerId]=!0,r.pointerDownPredicate||(r.pointerDownPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||0!=(r.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,t=r.skipPointerDownPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerDown?new wt:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,!1,r.cameraToUseForPointers),this._processPointerDown(t,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),r.preventDefaultOnPointerUp&&n&&(e.preventDefault(),n.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,e,((t,i)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,Wt.POINTERUP))return void(this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1));t.hasSwiped||(t.singleClick&&r.onPrePointerObservable.hasSpecificMask(Wt.POINTERTAP)&&this._checkPrePointerObservable(null,e,Wt.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&r.onPrePointerObservable.hasSpecificMask(Wt.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,Wt.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]=!1,(r.cameraToUseForPointers||r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||0!=(r.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(qt&&qt.HasTriggers||this._checkForPicking()||r.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._onKeyDown=e=>{const t=Qt.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const i=new Zt(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new jt(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(14,Bt.CreateNewFromScene(r,e))},this._onKeyUp=e=>{const t=Qt.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const i=new Zt(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new jt(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(15,Bt.CreateNewFromScene(r,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((n=>{n.deviceType===St.Mouse?n.onInputChangedObservable.add((r=>{r.inputIndex===It.LeftClick||r.inputIndex===It.MiddleClick||r.inputIndex===It.RightClick||r.inputIndex===It.BrowserBack||r.inputIndex===It.BrowserForward?t&&1===n.getInput(r.inputIndex)?this._onPointerDown(r):e&&0===n.getInput(r.inputIndex)&&this._onPointerUp(r):i&&(r.inputIndex===It.Move?this._onPointerMove(r):r.inputIndex!==It.MouseWheelX&&r.inputIndex!==It.MouseWheelY&&r.inputIndex!==It.MouseWheelZ||this._onPointerMove(r))})):n.deviceType===St.Touch?n.onInputChangedObservable.add((r=>{r.inputIndex===It.LeftClick&&(t&&1===n.getInput(r.inputIndex)?(this._onPointerDown(r),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===n.getInput(r.inputIndex)&&(this._onPointerUp(r),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&r.inputIndex===It.Move&&this._onPointerMove(r)})):n.deviceType===St.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){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const n=this._meshUnderPointerId[t];let r;n&&(r=n._getActionManagerForTrigger(10),r&&r.processTrigger(10,Bt.CreateNew(n,void 0,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,r=e._getActionManagerForTrigger(9),r&&r.processTrigger(9,Bt.CreateNew(e,void 0,{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]}}oi.DragMovementThreshold=10,oi.LongPressDelay=500,oi.DoubleClickDelay=300,oi.ExclusiveDoubleClickMode=!1;class li{constructor(e,t,i,n){this.normal=new Ye(e,t,i),this.d=n}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new li(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=li._TmpMatrix;e.invertToRef(t);const i=t.m,n=this.normal.x,r=this.normal.y,s=this.normal.z,a=this.d,o=n*i[0]+r*i[1]+s*i[2]+a*i[3],l=n*i[4]+r*i[5]+s*i[6]+a*i[7],h=n*i[8]+r*i[9]+s*i[10]+a*i[11],c=n*i[12]+r*i[13]+s*i[14]+a*i[15];return new li(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,r=t.y-e.y,s=t.z-e.z,a=i.x-e.x,o=i.y-e.y,l=i.z-e.z,h=r*l-s*o,c=s*a-n*l,u=n*o-r*a,d=Math.sqrt(h*h+c*c+u*u);let f;return f=0!==d?1/d:0,this.normal.x=h*f,this.normal.y=c*f,this.normal.z=u*f,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return Ye.Dot(this.normal,e)<=t}signedDistanceTo(e){return Ye.Dot(e,this.normal)+this.d}static FromArray(e){return new li(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const n=new li(0,0,0,0);return n.copyFromPoints(e,t,i),n}static FromPositionAndNormal(e,t){const i=new li(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 Ye.Dot(i,t)+n}}li._TmpMatrix=Qe.Identity();class hi{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new li(0,0,0,0));return hi.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){hi.GetNearPlaneToRef(e,t[0]),hi.GetFarPlaneToRef(e,t[1]),hi.GetLeftPlaneToRef(e,t[2]),hi.GetRightPlaneToRef(e,t[3]),hi.GetTopPlaneToRef(e,t[4]),hi.GetBottomPlaneToRef(e,t[5])}}class ci{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}ci._UniqueIdCounter=1;class ui{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}var di,fi,_i,pi;ui.FALLOFF_DEFAULT=0,ui.FALLOFF_PHYSICAL=1,ui.FALLOFF_GLTF=2,ui.FALLOFF_STANDARD=3,ui.LIGHTMAP_DEFAULT=0,ui.LIGHTMAP_SPECULAR=1,ui.LIGHTMAP_SHADOWSONLY=2,ui.INTENSITYMODE_AUTOMATIC=0,ui.INTENSITYMODE_LUMINOUSPOWER=1,ui.INTENSITYMODE_LUMINOUSINTENSITY=2,ui.INTENSITYMODE_ILLUMINANCE=3,ui.INTENSITYMODE_LUMINANCE=4,ui.LIGHTTYPEID_POINTLIGHT=0,ui.LIGHTTYPEID_DIRECTIONALLIGHT=1,ui.LIGHTTYPEID_SPOTLIGHT=2,ui.LIGHTTYPEID_HEMISPHERICLIGHT=3,function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(di||(di={}));class mi extends $e{constructor(e,t){super(),this._inputManager=new oi(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._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 n,this._onDisposeObserver=null,this.onBeforeRenderObservable=new n,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new n,this.onAfterRenderCameraObservable=new n,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new n,this.onAfterAnimationsObservable=new n,this.onBeforeDrawPhaseObservable=new n,this.onAfterDrawPhaseObservable=new n,this.onReadyObservable=new n,this.onBeforeCameraRenderObservable=new n,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new n,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new n,this.onAfterActiveMeshesEvaluationObservable=new n,this.onBeforeParticlesRenderingObservable=new n,this.onAfterParticlesRenderingObservable=new n,this.onDataLoadedObservable=new n,this.onNewCameraAddedObservable=new n,this.onCameraRemovedObservable=new n,this.onNewLightAddedObservable=new n,this.onLightRemovedObservable=new n,this.onNewGeometryAddedObservable=new n,this.onGeometryRemovedObservable=new n,this.onNewTransformNodeAddedObservable=new n,this.onTransformNodeRemovedObservable=new n,this.onNewMeshAddedObservable=new n,this.onMeshRemovedObservable=new n,this.onNewSkeletonAddedObservable=new n,this.onSkeletonRemovedObservable=new n,this.onNewMaterialAddedObservable=new n,this.onNewMultiMaterialAddedObservable=new n,this.onMaterialRemovedObservable=new n,this.onMultiMaterialRemovedObservable=new n,this.onNewTextureAddedObservable=new n,this.onTextureRemovedObservable=new n,this.onBeforeRenderTargetsRenderObservable=new n,this.onAfterRenderTargetsRenderObservable=new n,this.onBeforeStepObservable=new n,this.onAfterStepObservable=new n,this.onActiveCameraChanged=new n,this.onActiveCamerasChanged=new n,this.onBeforeRenderingGroupObservable=new n,this.onAfterRenderingGroupObservable=new n,this.onMeshImportedObservable=new n,this.onAnimationFileImportedObservable=new n,this._registeredForLateAnimationBindings=new Ne(256),this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1,this.onPrePointerObservable=new n,this.onPointerObservable=new n,this.onPreKeyboardObservable=new n,this.onKeyboardObservable=new n,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=mi.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 Ye(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 Ne(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new j,this._activeIndices=new j,this._activeParticles=new j,this._activeBones=new j,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 De(256),this._processedMaterials=new De(256),this._renderTargets=new Ne(256),this._materialsRenderTargets=new Ne(256),this._activeParticleSystems=new De(256),this._activeSkeletons=new Ne(32),this._softwareSkinnedMeshes=new Ne(32),this._activeAnimatables=new Array,this._transformMatrix=Qe.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=Xt.Create(),this._beforeClearStage=Xt.Create(),this._beforeRenderTargetClearStage=Xt.Create(),this._gatherRenderTargetsStage=Xt.Create(),this._gatherActiveCameraRenderTargetsStage=Xt.Create(),this._isReadyForMeshStage=Xt.Create(),this._beforeEvaluateActiveMeshStage=Xt.Create(),this._evaluateSubMeshStage=Xt.Create(),this._preActiveMeshStage=Xt.Create(),this._cameraDrawRenderTargetStage=Xt.Create(),this._beforeCameraDrawStage=Xt.Create(),this._beforeRenderTargetDrawStage=Xt.Create(),this._beforeRenderingGroupDrawStage=Xt.Create(),this._beforeRenderingMeshStage=Xt.Create(),this._afterRenderingMeshStage=Xt.Create(),this._afterRenderingGroupDrawStage=Xt.Create(),this._afterCameraDrawStage=Xt.Create(),this._afterCameraPostProcessStage=Xt.Create(),this._afterRenderTargetDrawStage=Xt.Create(),this._afterRenderTargetPostProcessStage=Xt.Create(),this._afterRenderStage=Xt.Create(),this._pointerMoveStage=Xt.Create(),this._pointerDownStage=Xt.Create(),this._pointerUpStage=Xt.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||f.LastCreatedEngine,i.virtual?this._engine._virtualScenes.push(this):(f._LastCreatedScene=this,this._engine.scenes.push(this)),this._uid=null,this._renderingManager=new Gt(this),Ut&&(this.postProcessManager=new Ut(this)),l()&&this.attachControl(),this._createUbo(),bt&&(this._imageProcessingConfiguration=new bt),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,t&&t.virtual||this._engine.onNewSceneAddedObservable.notifyObservers(this)}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}}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 oi.DragMovementThreshold}static set DragMovementThreshold(e){oi.DragMovementThreshold=e}static get LongPressDelay(){return oi.LongPressDelay}static set LongPressDelay(e){oi.LongPressDelay=e}static get DoubleClickDelay(){return oi.DoubleClickDelay}static set DoubleClickDelay(e){oi.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return oi.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){oi.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){var n;const r=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:null!==(n=this.activeCamera.globalPosition)&&void 0!==n?n:this.activeCamera.devicePosition,s=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return Ze.Vector4[0].set(r.x,r.y,r.z,s?-1:1),e&&(i?e.setFloat3(t,Ze.Vector4[0].x,Ze.Vector4[0].y,Ze.Vector4[0].z):e.setVector4(t,Ze.Vector4[0])),Ze.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=Xe(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=mi.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=mi.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}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(r,s)||(n=!1);if(!e)continue;const a=r.material||this.defaultMaterial;if(a)if(a._storeEffectOnSubMeshes)for(const e of r.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=H.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?hi.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=hi.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 Nt(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 ci.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 r=this.getCameraById(e);if(r)return r;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 r=this.getCameraByName(e);if(r)return r;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=r,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),r=n.length;i=i||1===r;for(let s=0;s0&&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){Pe.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!==(s=null!==(r=null===(n=e.outputRenderTarget)||void 0===n?void 0:n.renderPassId)&&void 0!==r?r:e.renderPassId)&&void 0!==s?s: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(Bt.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(s,1))}}}}_advancePhysicsEngineStep(e){}_animate(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(mi.MinDeltaTime,Math.min(this._engine.getDeltaTime(),mi.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let n=0;const r=this._engine.getLockstepMaxSteps();let s=Math.floor(e/t);for(s=Math.min(s,r);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!==(r=null==a?void 0:a.renderPassId)&&void 0!==r?r: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),f._LastCreatedScene===this&&(this._engine.scenes.length>0?f._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:f._LastCreatedScene=null),i=this._engine._virtualScenes.indexOf(this),i>-1&&this._engine._virtualScenes.splice(i,1),this._engine.wipeCaches(!0),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(),r=n.boundingBox.minimumWorld,s=n.boundingBox.maximumWorld;Ye.CheckExtends(r,t,i),Ye.CheckExtends(s,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,n,r=!1){throw _("Ray")}createPickingRayToRef(e,t,i,n,r,s=!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,r,s){return new wt}pickWithBoundingInfo(e,t,i,n,r){return new wt}pickWithRay(e,t,i,n){throw _("Ray")}multiPick(e,t,i,n,r){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 r in e){const s=e[r];we&&we.MatchesQuery(s,t)&&(n.push(s),i(s))}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,r,s,a){const o=ge(e,t,i,n?this.offlineProvider:void 0,r,s,a);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}_loadFileAsync(e,t,i,n,r){return new Promise(((s,a)=>{this._loadFile(e,(e=>{s(e)}),t,i,n,((e,t)=>{a(t)}),r)}))}_requestFile(e,t,i,n,r,s,a){const o=ve(e,t,i,n?this.offlineProvider:void 0,r,s,a);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}_requestFileAsync(e,t,i,n,r){return new Promise(((s,a)=>{this._requestFile(e,(e=>{s(e)}),t,i,n,(e=>{a(e)}),r)}))}_readFile(e,t,i,n,r){const s=me(e,t,i,n,r);return this._activeRequests.push(s),s.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),s}_readFileAsync(e,t,i){return new Promise(((n,r)=>{this._readFile(e,(e=>{n(e)}),t,i,(e=>{r(e)}))}))}getPerfCollector(){throw _("performanceViewerSceneExtension")}}mi.FOGMODE_NONE=0,mi.FOGMODE_EXP=1,mi.FOGMODE_EXP2=2,mi.FOGMODE_LINEAR=3,mi.MinDeltaTime=1,mi.MaxDeltaTime=1e3,mi.prototype.setActiveCameraByID=function(e){return this.setActiveCameraById(e)},mi.prototype.getLastMaterialByID=function(e){return this.getLastMaterialById(e)},mi.prototype.getMaterialByID=function(e){return this.getMaterialById(e)},mi.prototype.getTextureByUniqueID=function(e){return this.getTextureByUniqueId(e)},mi.prototype.getCameraByID=function(e){return this.getCameraById(e)},mi.prototype.getCameraByUniqueID=function(e){return this.getCameraByUniqueId(e)},mi.prototype.getBoneByID=function(e){return this.getBoneById(e)},mi.prototype.getLightByID=function(e){return this.getLightById(e)},mi.prototype.getLightByUniqueID=function(e){return this.getLightByUniqueId(e)},mi.prototype.getParticleSystemByID=function(e){return this.getParticleSystemById(e)},mi.prototype.getGeometryByID=function(e){return this.getGeometryById(e)},mi.prototype.getMeshByID=function(e){return this.getMeshById(e)},mi.prototype.getMeshesByID=function(e){return this.getMeshesById(e)},mi.prototype.getTransformNodeByID=function(e){return this.getTransformNodeById(e)},mi.prototype.getTransformNodeByUniqueID=function(e){return this.getTransformNodeByUniqueId(e)},mi.prototype.getTransformNodesByID=function(e){return this.getTransformNodesById(e)},mi.prototype.getMeshByUniqueID=function(e){return this.getMeshByUniqueId(e)},mi.prototype.getLastMeshByID=function(e){return this.getLastMeshById(e)},mi.prototype.getLastEntryByID=function(e){return this.getLastEntryById(e)},mi.prototype.getNodeByID=function(e){return this.getNodeById(e)},mi.prototype.getLastSkeletonByID=function(e){return this.getLastSkeletonById(e)},function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(fi||(fi={}));class gi{}gi.X=new Ye(1,0,0),gi.Y=new Ye(0,1,0),gi.Z=new Ye(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(_i||(_i={})),function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(pi||(pi={}));class vi{constructor(e){this._length=0,this._points=e,this._length=this._computeLength(e)}static CreateQuadraticBezier(e,t,i,n){n=n>2?n:3;const r=new Array,s=(e,t,i,n)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*n;for(let a=0;a<=n;a++)r.push(new Ye(s(a/n,e.x,t.x,i.x),s(a/n,e.y,t.y,i.y),s(a/n,e.z,t.z,i.z)));return new vi(r)}static CreateCubicBezier(e,t,i,n,r){r=r>3?r:4;const s=new Array,a=(e,t,i,n,r)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*n+e*e*e*r;for(let o=0;o<=r;o++)s.push(new Ye(a(o/r,e.x,t.x,i.x,n.x),a(o/r,e.y,t.y,i.y,n.y),a(o/r,e.z,t.z,i.z,n.z)));return new vi(s)}static CreateHermiteSpline(e,t,i,n,r){const s=new Array,a=1/r;for(let o=0;o<=r;o++)s.push(Ye.Hermite(e,t,i,n,o*a));return new vi(s)}static CreateCatmullRomSpline(e,t,i){const n=new Array,r=1/t;let s=0;if(i){const i=e.length;for(let a=0;ae.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=Me()),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}getScene(){return this._scene}_getEngine(){return this._engine}checkTransformsAreIdentical(e){return null!==e}getTextureMatrix(){return Qe.IdentityReadOnly}getReflectionTextureMatrix(){return Qe.IdentityReadOnly}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,n,r,s){const a=this._getEngine();if(!a)return null;const o=a._getUseSRGBBuffer(!!r,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=Et.Serialize(this);return Et.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 Ai(e,t,i=!1){const n=t.width,r=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 s=document.createElement("canvas");s.width=n,s.height=r;const a=s.getContext("2d");if(!a)return null;const o=a.createImageData(n,r);if(o.data.set(e),a.putImageData(o,0,0),i){const e=document.createElement("canvas");e.width=n,e.height=r;const t=e.getContext("2d");return t?(t.translate(0,r),t.scale(1,-1),t.drawImage(s,0,0),e.toDataURL("image/png")):null}return s.toDataURL("image/png")}Ri.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,et([ct()],Ri.prototype,"uniqueId",void 0),et([ct()],Ri.prototype,"name",void 0),et([ct()],Ri.prototype,"metadata",void 0),et([ct("hasAlpha")],Ri.prototype,"_hasAlpha",void 0),et([ct("getAlphaFromRGB")],Ri.prototype,"_getAlphaFromRGB",void 0),et([ct()],Ri.prototype,"level",void 0),et([ct("coordinatesIndex")],Ri.prototype,"_coordinatesIndex",void 0),et([ct()],Ri.prototype,"optimizeUVAllocation",void 0),et([ct("coordinatesMode")],Ri.prototype,"_coordinatesMode",void 0),et([ct()],Ri.prototype,"wrapU",null),et([ct()],Ri.prototype,"wrapV",null),et([ct()],Ri.prototype,"wrapR",void 0),et([ct()],Ri.prototype,"anisotropicFilteringLevel",void 0),et([ct()],Ri.prototype,"isCube",null),et([ct()],Ri.prototype,"is3D",null),et([ct()],Ri.prototype,"is2DArray",null),et([ct()],Ri.prototype,"gammaSpace",null),et([ct()],Ri.prototype,"invertZ",void 0),et([ct()],Ri.prototype,"lodLevelInAlpha",void 0),et([ct()],Ri.prototype,"lodGenerationOffset",null),et([ct()],Ri.prototype,"lodGenerationScale",null),et([ct()],Ri.prototype,"linearSpecularLOD",null),et([ut()],Ri.prototype,"irradianceTexture",null),et([ct()],Ri.prototype,"isRenderTarget",void 0);class bi{}bi.UseOpenGLOrientationForUV=!1;class Si extends Ri{constructor(e,t,i,r,s=Si.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=null,h=!1,c,u,d,f,_){var p,m,g,v,E,T,C,R,A;let b;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 n,this._isBlocking=!0,this.name=e||"",this.url=e;let S=!1,I=null;"object"==typeof i&&null!==i?(b=null!==(p=i.noMipmap)&&void 0!==p&&p,r=null!==(m=i.invertY)&&void 0!==m?m:!bi.UseOpenGLOrientationForUV,s=null!==(g=i.samplingMode)&&void 0!==g?g:Si.TRILINEAR_SAMPLINGMODE,a=null!==(v=i.onLoad)&&void 0!==v?v:null,o=null!==(E=i.onError)&&void 0!==E?E:null,l=null!==(T=i.buffer)&&void 0!==T?T:null,h=null!==(C=i.deleteBuffer)&&void 0!==C&&C,c=i.format,u=i.mimeType,d=i.loaderOptions,f=i.creationFlags,S=null!==(R=i.useSRGBBuffer)&&void 0!==R&&R,I=null!==(A=i.internalTexture)&&void 0!==A?A:null):b=!!i,this._noMipmap=b,this._invertY=void 0===r?!bi.UseOpenGLOrientationForUV:r,this._initialSamplingMode=s,this._buffer=l,this._deleteBuffer=h,this._mimeType=u,this._loaderOptions=d,this._creationFlags=f,this._useSRGBBuffer=S,this._forcedExtension=_,c&&(this._format=c);const x=this.getScene(),y=this._getEngine();if(!y)return;y.onBeforeTextureInitObservable.notifyObservers(this);const M=()=>{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&&x&&x.resetCachedMaterial()},P=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},o&&o(e,t),Si.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!I)return this._delayedOnLoad=M,void(this._delayedOnError=P);if(this._texture=null!=I?I:this._getFromCache(this.url,b,s,this._invertY,S),this._texture)if(this._texture.isReady)oe.SetImmediate((()=>M()));else{const e=this._texture.onLoadedObservable.add(M);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(x&&x.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=M,this._delayedOnError=P;else{try{this._texture=y.createTexture(this.url,b,this._invertY,x,s,M,P,this._buffer,void 0,this._format,this._forcedExtension,u,d,f,S)}catch(e){throw P("error loading",e),e}h&&(this._buffer=null)}}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}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?oe.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,Ye.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=Qe.Zero(),this._rowGenerationMatrix=new Qe,this._t0=Ye.Zero(),this._t1=Ye.Zero(),this._t2=Ye.Zero()),Qe.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(Qe.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,Ze.Matrix[0]),Qe.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,Ze.Matrix[1]),Qe.ScalingToRef(this._cachedUScale,this._cachedVScale,0,Ze.Matrix[2]),Qe.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,Ze.Matrix[3]),Ze.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(Ze.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(Ze.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(Ze.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),Qe.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!==Si.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=Qe.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=Qe.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 Si.PLANAR_MODE:Qe.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 Si.PROJECTION_MODE:{Qe.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:Qe.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 Et.Clone((()=>new Si(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){var e,t;const i=this.name;Si.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const n=super.serialize(Si._SerializeInternalTextureUniqueId);return n?((Si.SerializeBuffers||Si.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,"+se(this._buffer):(Si.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 r=e._readPixelsSync(t,i);return r?Ai(r,e.getSize(),n.invertY):null}(this):async function(e,t=0,i=0){const n=e.getInternalTexture();if(!n)return null;const r=await e.readPixels(t,i);return r?Ai(r,e.getSize(),n.invertY):null}(this))),n.invertY=this._invertY,n.samplingMode=this.samplingMode,n._creationFlags=this._creationFlags,n._useSRGBBuffer=this._useSRGBBuffer,Si._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=ye.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 Si._CubeTextureParser(e,t,i);const n=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!n)return null;let r;if(n){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}const s=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=Si._CreateMirror(e.name,e.renderTargetSize,t,l);return i._waitingRenderList=e.renderList,i.mirrorPlane=li.FromArray(e.mirrorPlane),s(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{s(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:")||Si.UseSerializedUrlIfAny)&&(a=e.url);const o={noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{s(n)},internalTexture:r};n=new Si(a,t,o)}return n}}),e,t);return a}static CreateFromBase64String(e,t,i,n,r,s=Si.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=5,h){return new Si("data:"+t,i,n,r,s,a,o,e,!1,l,void 0,void 0,h)}static LoadFromDataString(e,t,i,n=!1,r,s=!0,a=Si.TRILINEAR_SAMPLINGMODE,o=null,l=null,h=5,c){return"data:"!==e.substr(0,5)&&(e="data:"+e),new Si(e,i,r,s,a,o,l,t,n,h,void 0,void 0,c)}}function Ii(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}Si.SerializeBuffers=!0,Si.ForceSerializeBuffers=!1,Si.OnTextureLoadErrorObservable=new n,Si._SerializeInternalTextureUniqueId=!1,Si._CubeTextureParser=(e,t,i)=>{throw _("CubeTexture")},Si._CreateMirror=(e,t,i,n)=>{throw _("MirrorTexture")},Si._CreateRenderTargetTexture=(e,t,i,n,r)=>{throw _("RenderTargetTexture")},Si.NEAREST_SAMPLINGMODE=1,Si.NEAREST_NEAREST_MIPLINEAR=8,Si.BILINEAR_SAMPLINGMODE=2,Si.LINEAR_LINEAR_MIPNEAREST=11,Si.TRILINEAR_SAMPLINGMODE=3,Si.LINEAR_LINEAR_MIPLINEAR=3,Si.NEAREST_NEAREST_MIPNEAREST=4,Si.NEAREST_LINEAR_MIPNEAREST=5,Si.NEAREST_LINEAR_MIPLINEAR=6,Si.NEAREST_LINEAR=7,Si.NEAREST_NEAREST=1,Si.LINEAR_NEAREST_MIPNEAREST=9,Si.LINEAR_NEAREST_MIPLINEAR=10,Si.LINEAR_LINEAR=2,Si.LINEAR_NEAREST=12,Si.EXPLICIT_MODE=0,Si.SPHERICAL_MODE=1,Si.PLANAR_MODE=2,Si.CUBIC_MODE=3,Si.PROJECTION_MODE=4,Si.SKYBOX_MODE=5,Si.INVCUBIC_MODE=6,Si.EQUIRECTANGULAR_MODE=7,Si.FIXED_EQUIRECTANGULAR_MODE=8,Si.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Si.CLAMP_ADDRESSMODE=0,Si.WRAP_ADDRESSMODE=1,Si.MIRROR_ADDRESSMODE=2,Si.UseSerializedUrlIfAny=!1,et([ct()],Si.prototype,"url",void 0),et([ct()],Si.prototype,"uOffset",void 0),et([ct()],Si.prototype,"vOffset",void 0),et([ct()],Si.prototype,"uScale",void 0),et([ct()],Si.prototype,"vScale",void 0),et([ct()],Si.prototype,"uAng",void 0),et([ct()],Si.prototype,"vAng",void 0),et([ct()],Si.prototype,"wAng",void 0),et([ct()],Si.prototype,"uRotationCenter",void 0),et([ct()],Si.prototype,"vRotationCenter",void 0),et([ct()],Si.prototype,"wRotationCenter",void 0),et([ct()],Si.prototype,"homogeneousRotationInUVTransform",void 0),et([ct()],Si.prototype,"isBlocking",null),Ie("BABYLON.Texture",Si),Et._TextureParser=Si.Parse,K.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;const n=this._getInternalFormat(e.format),r=this._getRGBABufferInternalSizedFormat(0,e.format),s=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,n,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,n,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);const t=e._workingCanvas.getContext("2d");if(!t)throw new Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,n,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),s||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},K.prototype.createDynamicTexture=function(e,t,i,n){const r=new o(this,s.Dynamic);return r.baseWidth=e,r.baseHeight=t,i&&(e=this.needPOTTextures?K.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?K.GetExponentOfTwo(t,this._caps.maxTextureSize):t),r.width=e,r.height=t,r.isReady=!1,r.generateMipMaps=i,r.samplingMode=n,this.updateTextureSamplingMode(n,r),this._internalTexturesCache.push(r),r},K.prototype.updateDynamicTexture=function(e,t,i,n=!1,r,s=!1,a=!1){if(!e)return;const o=this._gl,l=o.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,s);this._unpackFlipY(void 0===i?e.invertY:i),n&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(r||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,u);o.texImage2D(l,0,d,u,c,t),e.generateMipMaps&&o.generateMipmap(l),h||this._bindTextureDirectly(l,null),n&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0};class xi extends Si{constructor(e,t,i,n=!1,r=!1,s=Si.TRILINEAR_SAMPLINGMODE,a={},o,l=5){var h,c;super(null,i,!n,r),this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this._createInternalTexture=()=>{var e;if(null!=this._texture){if(!this._displayingPosterTexture)return;this._texture.dispose(),this._displayingPosterTexture=!1}if(!this._getEngine().needPOTTextures||Pe.IsExponentOfTwo(this.video.videoWidth)&&Pe.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=Si.WRAP_ADDRESSMODE,this.wrapV=Si.WRAP_ADDRESSMODE):(this.wrapU=Si.CLAMP_ADDRESSMODE,this.wrapV=Si.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=null!==(e=this._format)&&void 0!==e?e:5,this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{const e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture)return;if(this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&u?u&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new n),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(null==e?void 0:e.message):p.Error(null==e?void 0:e.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch((e=>{if("NotAllowedError"===(null==e?void 0:e.name)){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers())return void this._onUserActionRequestedObservable.notifyObservers(this);if(!this.video.muted)return p.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,void this.video.play().catch((e=>{this._processError(e)}))}this._processError(e)}))}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return Pe.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return"string"==typeof e?(Pe.SetCorsBehavior(e,t),t.src=e):(Pe.SetCorsBehavior(e[0],t),e.forEach((e=>{const i=document.createElement("source");i.src=e,t.appendChild(i)}))),this.onDisposeObservable.addOnce((()=>{Ii(t)})),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new xi(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){var e;super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.pause()),null===(e=this._externalTexture)||void 0===e||e.dispose()}static CreateFromStreamAsync(e,t,i,n=!0){const r=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(r),r.style.transform="scale(0.0001, 0.0001)",r.style.opacity="0",r.style.position="fixed",r.style.bottom="0px",r.style.right="0px"),r.setAttribute("autoplay",""),r.setAttribute("muted","true"),r.setAttribute("playsinline",""),r.muted=!0,r.isNative||(void 0!==r.mozSrcObject?r.mozSrcObject=t:"object"==typeof r.srcObject?r.srcObject=t:r.src=window.URL&&window.URL.createObjectURL(t)),new Promise((t=>{const i=()=>{const s=new xi("video",r,e,!0,n,void 0,void 0,void 0,4);e.getEngine()._badOS&&s.onDisposeObservable.addOnce((()=>{r.remove()})),s.onDisposeObservable.addOnce((()=>{Ii(r)})),t(s),r.removeEventListener("playing",i)};r.addEventListener("playing",i),r.play()}))}static async CreateFromWebCamAsync(e,t,i=!1,n=!0){if(navigator.mediaDevices){const r=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),s=await this.CreateFromStreamAsync(e,r,t,n);return s.onDisposeObservable.addOnce((()=>{r.getTracks().forEach((e=>{e.stop()}))})),s}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,n=!1,r=!0){this.CreateFromWebCamAsync(e,i,n,r).then((function(e){t&&t(e)})).catch((function(e){p.Error(e.name)}))}}class yi{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new n,this._onClonedObservable=new n}}class Mi{constructor(e,t=null){this._isDirty=!1,this._nodeDataStorage=new yi,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new n,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=Qe.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new n,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||f.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,n){const r=this._NodeConstructors[e];return r?r(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}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")},Mi._NodeConstructors={},et([ct()],Mi.prototype,"name",void 0),et([ct()],Mi.prototype,"id",void 0),et([ct()],Mi.prototype,"uniqueId",void 0),et([ct()],Mi.prototype,"state",void 0),et([ct()],Mi.prototype,"metadata",void 0);class Pi extends Mi{constructor(e,t=null,i=!0){super(e,t),this._forward=new Ye(0,0,1),this._up=new Ye(0,1,0),this._right=new Ye(1,0,0),this._position=Ye.Zero(),this._rotation=Ye.Zero(),this._rotationQuaternion=null,this._scaling=Ye.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=Pi.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=Qe.Zero(),this._usePivotMatrix=!1,this._absolutePosition=Ye.Zero(),this._absoluteScaling=Ye.Zero(),this._absoluteRotationQuaternion=qe.Identity(),this._pivotMatrix=Qe.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new n,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e)}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e)}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}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 Ye.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return Ye.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return Ye.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=Qe.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==Pi.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}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=Qe.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||qe.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=Ze.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),Ye.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=Ye.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=Ze.Matrix[0];return this._localMatrix.invertToRef(e),Ye.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=Ye.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,n=0,r=fi.LOCAL){const s=Pi._LookAtVectorCache,a=r===fi.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,s),this.setDirection(s,t,i,n),r===fi.WORLD&&this.parent)if(this.rotationQuaternion){const e=Ze.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=Ze.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=Ze.Quaternion[0];qe.FromEulerVectorToRef(this.rotation,e);const t=Ze.Matrix[0];e.toRotationMatrix(t);const i=Ze.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=Ye.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return Ye.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,n=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,s=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,s);return this.rotationQuaternion?qe.RotationYawPitchRollToRef(r+t,a+i,n,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=r+t,this.rotation.z=n),this}setPivotPoint(e,t=fi.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==fi.WORLD){const t=Ze.Matrix[0];i.invertToRef(t),e=Ye.TransformCoordinates(e,t)}return this.setPivotMatrix(Qe.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=Ye.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=Ye.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),Ye.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=Ze.Quaternion[0],r=Ze.Vector3[0],s=Ze.Vector3[1],a=Ze.Matrix[1];Qe.IdentityToRef(a);const o=Ze.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=Pi._TmpRotation,qe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),Qe.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(s,n,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(n):n.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(s),this.position.copyFrom(r),this.parent=e,i&&this.setPivotMatrix(Qe.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!==fi.LOCAL){if(this.parent){const t=Ze.Matrix[0];this.parent.getWorldMatrix().invertToRef(t),e=Ye.TransformNormal(e,t)}n=qe.RotationAxisToRef(e,t,Pi._RotationAxisCache),n.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else n=qe.RotationAxisToRef(e,t,Pi._RotationAxisCache),this.rotationQuaternion.multiplyToRef(n,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=qe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const n=Ze.Vector3[0],r=Ze.Vector3[1],s=Ze.Vector3[2],a=Ze.Quaternion[0],o=Ze.Matrix[0],l=Ze.Matrix[1],h=Ze.Matrix[2],c=Ze.Matrix[3];return e.subtractToRef(this.position,n),Qe.TranslationToRef(n.x,n.y,n.z,o),Qe.TranslationToRef(-n.x,-n.y,-n.z,l),Qe.RotationAxisToRef(t,i,h),l.multiplyToRef(h,c),c.multiplyToRef(o,c),c.decompose(r,a,s),this.position.addInPlace(s),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const n=e.scale(t);if(i&&i!==fi.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=Ze.Quaternion[1],qe.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,n));const r=Ze.Quaternion[0];return qe.RotationYawPitchRollToRef(t,e,i,r),n.multiplyInPlace(r),this.rotationQuaternion||n.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}computeWorldMatrix(e){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const t=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===t||this.isSynchronized()))return this._currentRenderId=t,this._worldMatrix;const i=this.getScene().activeCamera,n=0!=(this._billboardMode&Pi.BILLBOARDMODE_USE_POSITION),r=this._billboardMode!==Pi.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard;this._updateCache();const s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=t,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const a=this._getEffectiveParent(),o=Pi._TmpScaling;let l,h=this._position;if(this._infiniteDistance&&!this.parent&&i){const e=i.getWorldMatrix(),t=new Ye(e.m[12],e.m[13],e.m[14]);h=Pi._TmpTranslation,h.copyFromFloats(this._position.x+t.x,this._position.y+t.y,this._position.z+t.z)}if(o.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,l=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(qe.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(l=Pi._TmpRotation,qe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),this._usePivotMatrix){const e=Ze.Matrix[1];Qe.ScalingToRef(o.x,o.y,o.z,e);const t=Ze.Matrix[0];l.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,Ze.Matrix[4]),Ze.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(h.x,h.y,h.z)}else Qe.ComposeToRef(o,l,h,this._localMatrix);if(a&&a.getWorldMatrix){if(e&&a.computeWorldMatrix(e),r){this._transformToBoneReferal?a.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),Ze.Matrix[7]):Ze.Matrix[7].copyFrom(a.getWorldMatrix());const e=Ze.Vector3[5],t=Ze.Vector3[6],i=Ze.Quaternion[0];Ze.Matrix[7].decompose(t,i,e),Qe.ScalingToRef(t.x,t.y,t.z,Ze.Matrix[7]),Ze.Matrix[7].setTranslation(e),Pi.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(Ze.Matrix[7],this._worldMatrix)}else this._transformToBoneReferal?(this._localMatrix.multiplyToRef(a.getWorldMatrix(),Ze.Matrix[6]),Ze.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localMatrix.multiplyToRef(a.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(r&&i&&this.billboardMode&&!n){const e=Ze.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),Ze.Matrix[1].copyFrom(i.getViewMatrix()),Ze.Matrix[1].setTranslationFromFloats(0,0,0),Ze.Matrix[1].invertToRef(Ze.Matrix[0]),(this.billboardMode&Pi.BILLBOARDMODE_ALL)!==Pi.BILLBOARDMODE_ALL){Ze.Matrix[0].decompose(void 0,Ze.Quaternion[0],void 0);const e=Ze.Vector3[1];Ze.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Pi.BILLBOARDMODE_X)!==Pi.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Pi.BILLBOARDMODE_Y)!==Pi.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Pi.BILLBOARDMODE_Z)!==Pi.BILLBOARDMODE_Z&&(e.z=0),Qe.RotationYawPitchRollToRef(e.y,e.x,e.z,Ze.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(Ze.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(Ze.Vector3[0])}else if(r&&i&&this.billboardMode&&n){const e=Ze.Vector3[0];this._worldMatrix.getTranslationToRef(e);const t=i.globalPosition;this._worldMatrix.invertToRef(Ze.Matrix[1]);const n=Ze.Vector3[1];Ye.TransformCoordinatesToRef(t,Ze.Matrix[1],n),n.normalize();const r=-Math.atan2(n.z,n.x)+Math.PI/2,s=Math.sqrt(n.x*n.x+n.z*n.z),a=-Math.atan2(n.y,s);if(qe.RotationYawPitchRollToRef(r,a,0,Ze.Quaternion[0]),(this.billboardMode&Pi.BILLBOARDMODE_ALL)!==Pi.BILLBOARDMODE_ALL){const e=Ze.Vector3[1];Ze.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Pi.BILLBOARDMODE_X)!==Pi.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Pi.BILLBOARDMODE_Y)!==Pi.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Pi.BILLBOARDMODE_Z)!==Pi.BILLBOARDMODE_Z&&(e.z=0),Qe.RotationYawPitchRollToRef(e.y,e.x,e.z,Ze.Matrix[0])}else Qe.FromQuaternionToRef(Ze.Quaternion[0],Ze.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(Ze.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(Ze.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):a&&a._nonUniformScaling?this._updateNonUniformScalingState(a._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=Qe.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;tnew Pi(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 Pi(e.name,t)),e,t,i);return e.localMatrix?n.setPreTransformMatrix(Qe.FromArray(e.localMatrix)):e.pivotMatrix&&n.setPivotMatrix(Qe.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 Pi)),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,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(n=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const s=this.getHierarchyBoundingVectors(e,i),a=s.max.subtract(s.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&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&n&&this.rotation.copyFrom(n)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}function Oi(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 Di(e,t,i,n,r){const s=()=>{let a;const o=e=>{e.done?i(e.value):void 0===a?a=!0:s()};do{a=void 0,r&&r.aborted?n(new Error("Aborted")):t(e,o,n),void 0===a&&(a=!1)}while(a)};s()}function Ni(e,t){let i;return Di(e,Oi,(e=>i=e),(e=>{throw e}),t),i}Pi.BILLBOARDMODE_NONE=0,Pi.BILLBOARDMODE_X=1,Pi.BILLBOARDMODE_Y=2,Pi.BILLBOARDMODE_Z=4,Pi.BILLBOARDMODE_ALL=7,Pi.BILLBOARDMODE_USE_POSITION=128,Pi.BillboardUseParentOrientation=!1,Pi._TmpRotation=qe.Zero(),Pi._TmpScaling=Ye.Zero(),Pi._TmpTranslation=Ye.Zero(),Pi._LookAtVectorCache=new Ye(0,0,0),Pi._RotationAxisCache=new qe,et([pt("position")],Pi.prototype,"_position",void 0),et([pt("rotation")],Pi.prototype,"_rotation",void 0),et([lt(10,"rotationQuaternion")],Pi.prototype,"_rotationQuaternion",void 0),et([pt("scaling")],Pi.prototype,"_scaling",void 0),et([ct("billboardMode")],Pi.prototype,"_billboardMode",void 0),et([ct()],Pi.prototype,"scalingDeterminant",void 0),et([ct("infiniteDistance")],Pi.prototype,"_infiniteDistance",void 0),et([ct()],Pi.prototype,"ignoreNonUniformScaling",void 0),et([ct()],Pi.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class Fi extends Mi{constructor(e,t,i,r=!0){super(e,i),this._position=Ye.Zero(),this._upVector=Ye.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=Fi.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Ti(0,0,1,1),this.layerMask=268435455,this.fovMode=Fi.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=Fi.RIG_MODE_NONE,this.customRenderTargets=new Array,this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new n,this.onProjectionMatrixChangedObservable=new n,this.onAfterCheckInputsObservable=new n,this.onRestoreStateObservable=new n,this.isRigCamera=!1,this._rigCameras=new Array,this._webvrViewMatrix=Qe.Identity(),this._skipRendering=!1,this._projectionMatrix=new Qe,this._postProcesses=new Array,this._activeMeshes=new De(256),this._globalPosition=Ye.Zero(),this._computedViewMatrix=Qe.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=Qe.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=qe.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),r&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}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 r=0,s=0;if(this.mode===Fi.PERSPECTIVE_CAMERA)this.fovMode===Fi.FOVMODE_VERTICAL_FIXED?(s=2*this.minZ*Math.tan(this.fov/2),r=this.getEngine().getAspectRatio(this)*s):(r=2*this.minZ*Math.tan(this.fov/2),s=r/this.getEngine().getAspectRatio(this));else{const a=this.getEngine().getRenderWidth()/2,o=this.getEngine().getRenderHeight()/2;r=(null!==(e=this.orthoRight)&&void 0!==e?e:a)-(null!==(t=this.orthoLeft)&&void 0!==t?t:-a),s=(null!==(i=this.orthoTop)&&void 0!==i?i:o)-(null!==(n=this.orthoBottom)&&void 0!==n?n:-o)}return r*s}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}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?(p.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 Qe.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,r,s,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(),u=h.useReverseDepthBuffer;if(this.mode===Fi.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?Qe.PerspectiveFovRHToRef:Qe.PerspectiveFovLHToRef,e(this.fov,h.getAspectRatio(this),u?this.maxZ:this.minZ,u?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===Fi.FOVMODE_VERTICAL_FIXED,h.isNDCHalfZRange,this.projectionPlaneTilt,u)}else{const e=h.getRenderWidth()/2,d=h.getRenderHeight()/2;c.useRightHandedSystem?Qe.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:-d,null!==(r=this.orthoTop)&&void 0!==r?r:d,u?this.maxZ:this.minZ,u?this.minZ:this.maxZ,this._projectionMatrix,h.isNDCHalfZRange):Qe.OrthoOffCenterLHToRef(null!==(s=this.orthoLeft)&&void 0!==s?s:-e,null!==(a=this.orthoRight)&&void 0!==a?a:e,null!==(o=this.orthoBottom)&&void 0!==o?o:-d,null!==(l=this.orthoTop)&&void 0!==l?l:d,u?this.maxZ:this.minZ,u?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?hi.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=hi.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!==Fi.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=Pe.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==Fi.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 Qe.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 Qe.Identity()}_getWebVRViewMatrix(){return Qe.Identity()}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=Pe.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eFi._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,n=Fi.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=Et.Parse(n,e,t);if(void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=Ye.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(Ye.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(Ye.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t{throw _("UniversalCamera")},Fi.PERSPECTIVE_CAMERA=0,Fi.ORTHOGRAPHIC_CAMERA=1,Fi.FOVMODE_VERTICAL_FIXED=0,Fi.FOVMODE_HORIZONTAL_FIXED=1,Fi.RIG_MODE_NONE=0,Fi.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Fi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Fi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Fi.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Fi.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Fi.RIG_MODE_VR=20,Fi.RIG_MODE_WEBVR=21,Fi.RIG_MODE_CUSTOM=22,Fi.ForceAttachControlToAlwaysPreventDefault=!1,et([pt("position")],Fi.prototype,"_position",void 0),et([pt("upVector")],Fi.prototype,"_upVector",void 0),et([ct()],Fi.prototype,"orthoLeft",null),et([ct()],Fi.prototype,"orthoRight",null),et([ct()],Fi.prototype,"orthoBottom",null),et([ct()],Fi.prototype,"orthoTop",null),et([ct()],Fi.prototype,"fov",void 0),et([ct()],Fi.prototype,"projectionPlaneTilt",void 0),et([ct()],Fi.prototype,"minZ",void 0),et([ct()],Fi.prototype,"maxZ",void 0),et([ct()],Fi.prototype,"inertia",void 0),et([ct()],Fi.prototype,"mode",null),et([ct()],Fi.prototype,"layerMask",void 0),et([ct()],Fi.prototype,"fovMode",void 0),et([ct()],Fi.prototype,"cameraRigMode",void 0),et([ct()],Fi.prototype,"interaxialDistance",void 0),et([ct()],Fi.prototype,"isStereoscopicSideBySide",void 0);class Li{constructor(){var e;this._applyTo=(e=this._applyToCoroutine.bind(this),(...t)=>Ni(e(...t),undefined))}set(e,t){switch(e.length||p.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 r=Ze.Vector3[0],s=Ze.Vector3[1];for(let a=i;a[e,void 0])):[[e,void 0]];return Ni(this._mergeCoroutine(void 0,n,t,!1,i))}*_mergeCoroutine(e,t,i=!1,n,r){var s,a,o,l;this._validate();const h=t.map((e=>e[0]));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===(s=this.indices)||void 0===s?void 0:s.length)&&void 0!==a?a:0);let u=r||h.some((e=>e.indices===this.indices))?null===(o=this.indices)||void 0===o?void 0:o.slice():this.indices;if(c>0){let r=null!==(l=null==u?void 0:u.length)&&void 0!==l?l:0;if(u||(u=new Array(c)),u.length!==c){if(Array.isArray(u))u.length=c;else{const e=i||u instanceof Uint32Array?new Uint32Array(c):new Uint16Array(c);e.set(u),u=e}e&&e.determinant()<0&&Li._FlipFaces(u,0,r)}let s=this.positions?this.positions.length/3:0;for(const[e,i]of t)if(e.indices){for(let t=0;t[e[0].positions,e[1]]))),n&&(yield),this.normals=Li._MergeElement(Lt.NormalKind,this.normals,e,t.map((e=>[e[0].normals,e[1]]))),n&&(yield),this.tangents=Li._MergeElement(Lt.TangentKind,this.tangents,e,t.map((e=>[e[0].tangents,e[1]]))),n&&(yield),this.uvs=Li._MergeElement(Lt.UVKind,this.uvs,e,t.map((e=>[e[0].uvs,e[1]]))),n&&(yield),this.uvs2=Li._MergeElement(Lt.UV2Kind,this.uvs2,e,t.map((e=>[e[0].uvs2,e[1]]))),n&&(yield),this.uvs3=Li._MergeElement(Lt.UV3Kind,this.uvs3,e,t.map((e=>[e[0].uvs3,e[1]]))),n&&(yield),this.uvs4=Li._MergeElement(Lt.UV4Kind,this.uvs4,e,t.map((e=>[e[0].uvs4,e[1]]))),n&&(yield),this.uvs5=Li._MergeElement(Lt.UV5Kind,this.uvs5,e,t.map((e=>[e[0].uvs5,e[1]]))),n&&(yield),this.uvs6=Li._MergeElement(Lt.UV6Kind,this.uvs6,e,t.map((e=>[e[0].uvs6,e[1]]))),n&&(yield),this.colors=Li._MergeElement(Lt.ColorKind,this.colors,e,t.map((e=>[e[0].colors,e[1]]))),n&&(yield),this.matricesIndices=Li._MergeElement(Lt.MatricesIndicesKind,this.matricesIndices,e,t.map((e=>[e[0].matricesIndices,e[1]]))),n&&(yield),this.matricesWeights=Li._MergeElement(Lt.MatricesWeightsKind,this.matricesWeights,e,t.map((e=>[e[0].matricesWeights,e[1]]))),n&&(yield),this.matricesIndicesExtra=Li._MergeElement(Lt.MatricesIndicesExtraKind,this.matricesIndicesExtra,e,t.map((e=>[e[0].matricesIndicesExtra,e[1]]))),n&&(yield),this.matricesWeightsExtra=Li._MergeElement(Lt.MatricesWeightsExtraKind,this.matricesWeightsExtra,e,t.map((e=>[e[0].matricesWeightsExtra,e[1]]))),this}static _MergeElement(e,t,i,n){const r=n.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==r.length)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const s=r.reduce(((e,t)=>e+t[0].length),t.length),a=e===Lt.PositionKind?Li._TransformVector3Coordinates:e===Lt.NormalKind?Li._TransformVector3Normals:e===Lt.TangentKind?Li._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(s);e.set(t),i&&a(e,i,0,t.length);let n=t.length;for(const[t,i]of r)e.set(t,n),i&&a(e,i,n,t.length),n+=t.length;return e}{const e=new Array(s);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 r=e(i,n);if(r!==t)throw new Error("The "+i+"s element count ("+r+") 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 Li._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return Li._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const n=new Li;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,r,s,a){throw _("polygonBuilder")}static CreateIcoSphere(e){throw _("icoSphereBuilder")}static CreatePolyhedron(e){throw _("polyhedronBuilder")}static CreateCapsule(e={orientation:Ye.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 r=0,s=0,a=0,o=0,l=0,h=0,c=0,u=0,d=0,f=0,_=0,p=0,m=0,g=0,v=0,E=0,T=0,C=0,R=0,A=0,b=!1,S=!1,I=!1,x=!1,y=1,M=0,P=null;n&&(b=!!n.facetNormals,S=!!n.facetPositions,I=!!n.facetPartitioning,y=!0===n.useRightHandedSystem?-1:1,M=n.ratio||0,x=!!n.depthSort,P=n.distanceTo,x&&void 0===P&&(P=Ye.Zero()));let O=0,D=0,N=0,F=0;for(I&&n&&n.bbSize&&(O=n.subDiv.X*M/n.bbSize.x,D=n.subDiv.Y*M/n.bbSize.y,N=n.subDiv.Z*M/n.bbSize.z,F=n.subDiv.max*n.subDiv.max,n.facetPartitioning.length=0),r=0;r!Array.isArray(e)))],Li,"_TransformVector3Coordinates",null),et([Tt.filter(((...[e])=>!Array.isArray(e)))],Li,"_TransformVector3Normals",null),et([Tt.filter(((...[e])=>!Array.isArray(e)))],Li,"_TransformVector4Normals",null),et([Tt.filter(((...[e])=>!Array.isArray(e)))],Li,"_FlipFaces",null);class wi{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class Bi{constructor(e,t,i){this.vectors=Ge.BuildArray(8,Ye.Zero),this.center=Ye.Zero(),this.centerWorld=Ye.Zero(),this.extendSize=Ye.Zero(),this.extendSizeWorld=Ye.Zero(),this.directions=Ge.BuildArray(3,Ye.Zero),this.vectorsWorld=Ge.BuildArray(8,Ye.Zero),this.minimumWorld=Ye.Zero(),this.maximumWorld=Ye.Zero(),this.minimum=Ye.Zero(),this.maximum=Ye.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const n=e.x,r=e.y,s=e.z,a=t.x,o=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(n,r,s),this.maximum.copyFromFloats(a,o,l),h[0].copyFromFloats(n,r,s),h[1].copyFromFloats(a,o,l),h[2].copyFromFloats(a,r,s),h[3].copyFromFloats(n,o,s),h[4].copyFromFloats(n,r,l),h[5].copyFromFloats(a,o,s),h[6].copyFromFloats(n,o,l),h[7].copyFromFloats(a,r,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||Qe.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=Bi._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),n=i.length();i.normalizeFromLength(n);const r=n*e,s=i.scaleInPlace(.5*r),a=this.center.subtractToRef(s,t[1]),o=this.center.addToRef(s,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,r=this.vectorsWorld,s=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(s[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=r[n];Ye.TransformCoordinatesToRef(s[n],e,a),t.minimizeInPlace(a),i.maximizeInPlace(a)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}Ye.FromArrayToRef(e.m,0,n[0]),Ye.FromArrayToRef(e.m,4,n[1]),Ye.FromArrayToRef(e.m,8,n[2]),this._worldMatrix=e}isInFrustum(e){return Bi.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return Bi.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,n=t.x,r=t.y,s=t.z,a=i.x,o=i.y,l=i.z,h=e.x,c=e.y,u=e.z,d=-.001;return!(a-hh-n||o-cc-r||l-uu-s)}intersectsSphere(e){return Bi.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,n=this.maximumWorld,r=i.x,s=i.y,a=i.z,o=n.x,l=n.y,h=n.z,c=e.x,u=e.y,d=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 r=Bi._TmpVector3[0];return Ye.ClampToRef(i,e,t,r),Ye.DistanceSquared(i,r)<=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 r=t[i];for(let t=0;t<8;++t)if(r.dotCoordinate(e[t])>=0){n=!1;break}if(n)return!1}return!0}}Bi._TmpVector3=Ge.BuildArray(3,Ye.Zero);class Ui{constructor(e,t,i){this.center=Ye.Zero(),this.centerWorld=Ye.Zero(),this.minimum=Ye.Zero(),this.maximum=Ye.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const n=Ye.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*n,this._update(i||Qe.IdentityReadOnly)}scale(e){const t=this.radius*e,i=Ui._TmpVector3,n=i[0].setAll(t),r=this.center.subtractToRef(n,i[1]),s=this.center.addToRef(n,i[2]);return this.reConstruct(r,s,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{Ye.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=Ui._TmpVector3[0];Ye.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=Ye.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const n=Ye.Dot(t.centerWorld,e),r=Math.abs(Ye.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(Ye.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(Ye.Dot(t.directions[2],e))*t.extendSize.z;i.min=n-r,i.max=n+r},zi=(e,t,i)=>(Gi(e,t,Vi),Gi(e,i,ki),!(Vi.min>ki.max||ki.min>Vi.max));class Xi{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new Bi(e,t,i),this.boundingSphere=new Ui(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){const i=Xi._TmpVector3[0].copyFrom(e).subtractInPlace(t),n=Xi._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=Ye.Minimize(this.minimum,e),i=Ye.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,Xi._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!!this.boundingSphere.centerWorld&&!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e)}intersects(e,t){if(!Ui.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!Bi.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,n=e.boundingBox;return!!(zi(i.directions[0],i,n)&&zi(i.directions[1],i,n)&&zi(i.directions[2],i,n)&&zi(n.directions[0],i,n)&&zi(n.directions[1],i,n)&&zi(n.directions[2],i,n)&&zi(Ye.Cross(i.directions[0],n.directions[0]),i,n)&&zi(Ye.Cross(i.directions[0],n.directions[1]),i,n)&&zi(Ye.Cross(i.directions[0],n.directions[2]),i,n)&&zi(Ye.Cross(i.directions[1],n.directions[0]),i,n)&&zi(Ye.Cross(i.directions[1],n.directions[1]),i,n)&&zi(Ye.Cross(i.directions[1],n.directions[2]),i,n)&&zi(Ye.Cross(i.directions[2],n.directions[0]),i,n)&&zi(Ye.Cross(i.directions[2],n.directions[1]),i,n)&&zi(Ye.Cross(i.directions[2],n.directions[2]),i,n))}}Xi._TmpVector3=Ge.BuildArray(2,Ye.Zero);class Wi{static extractMinAndMaxIndexed(e,t,i,n,r,s){for(let a=i;a!Array.isArray(e)&&!Array.isArray(t)))],Wi,"extractMinAndMaxIndexed",null),et([Tt.filter(((...[e])=>!Array.isArray(e)))],Wi,"extractMinAndMax",null);class Yi{constructor(e,t,i,n,r,s,a,o=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=n,this.indexCount=r,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=s,this._renderingMesh=a||s,l&&s.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=s.subMeshes.length-1,o&&(this.refreshBoundingInfo(),s.computeWorldMatrix(!0))}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 X(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 r=this._drawWrapper;r.setEffect(e,t,n),void 0!==i&&(r.materialContext=i),e||(r.defines=null,r.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,r,s,a,o=!0){return new Yi(e,t,i,n,r,s,a,o)}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,r=null){const s=new Ye(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new Ye(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return Wi.extractMinAndMaxIndexed(e,t,i,n,s,a),r&&(s.x-=s.x*r.x+r.y,s.y-=s.y*r.x+r.y,s.z-=s.z*r.x+r.y,a.x+=a.x*r.x+r.y,a.y+=a.y*r.x+r.y,a.z+=a.z*r.x+r.y),{minimum:s,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 Xi(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 Yi(e,a,o-a+1,t,i,n,r,s)}}class Ki{static get ForceFullSceneLoadingForIncremental(){return Ki._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Ki._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Ki._ShowLoadingScreen}static set ShowLoadingScreen(e){Ki._ShowLoadingScreen=e}static get loggingLevel(){return Ki._LoggingLevel}static set loggingLevel(e){Ki._LoggingLevel=e}static get CleanBoneMatrixWeights(){return Ki._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Ki._CleanBoneMatrixWeights=e}}Ki._ForceFullSceneLoadingForIncremental=!1,Ki._ShowLoadingScreen=!0,Ki._CleanBoneMatrixWeights=!1,Ki._LoggingLevel=0;class qi{constructor(e,t,i,n=!1,r=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||f.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={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0)))}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 qi(qi.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}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,r=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 Li;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(bi.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(bi.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(bi.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(bi.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(bi.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(bi.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),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(Lt.MatricesIndicesKind,r,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const n=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(Lt.MatricesIndicesExtraKind,r,!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&&(qi._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 r=t.getVerticesData(Lt.MatricesIndicesKind),s=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,s[e+h-4]=n):(a[e+h]=1-t,r[e+h]=n)}t.setVerticesData(Lt.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(Lt.MatricesIndicesExtraKind,s)}static Parse(e,t,i){const n=new qi(e.id,t,void 0,e.updatable);return n._loadedUniqueId=e.uniqueId,we&&we.AddTagsTo(n,e.tags),e.delayLoadingFile?(n.delayLoadState=4,n.delayLoadingFile=i+e.delayLoadingFile,n._boundingInfo=new Xi(Ye.FromArray(e.boundingBoxMinimum),Ye.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=Li.ImportVertexData):Li.ImportVertexData(e,n),t.pushGeometry(n,!0),n}}class Qi{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new Ye(0,0,0),this._diffPositionForCollisions=new Ye(0,0,0),this._collisionResponse=!0}}class ji{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=Ye.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class Zi{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new ji,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 Qi,this._enableDistantPicking=!1}}class Ji extends Pi{constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new Zi,this._waitingMaterialId=null,this.cullingStrategy=Ji.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new n,this.onCollisionPositionChangeObservable=new n,this.onMaterialChangedObservable=new n,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 Ye(.5,1,.5),this.ellipsoidOffset=new Ye(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 n,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Z.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 Nt(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}}static get BILLBOARDMODE_NONE(){return Pi.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Pi.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Pi.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Pi.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Pi.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Pi.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}_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!==Pi.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 Xi(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===Pi.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 Qe;(this.rotationQuaternion?this.rotationQuaternion:qe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(n);const r=Ye.Zero(),s=this.definedFacingForward?-1:1;return Ye.TransformCoordinatesFromFloatsToRef(e*s,t,i*s,n,r),r}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 Ye(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=Hi(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new Xi(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t0){const e=t.getPositions();e&&(i[r]+=(e[r]-i[r])*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 r=this.numBoneInfluencers>4,s=r?this.getVerticesData(Lt.MatricesIndicesExtraKind):null,a=r?this.getVerticesData(Lt.MatricesWeightsExtraKind):null,o=this.skeleton.getTransformMatrices(this),l=Ze.Vector3[0],h=Ze.Matrix[0],c=Ze.Matrix[1];let u=0;for(let d=0;d0&&(Qe.FromFloat32ArrayToRefScaled(o,Math.floor(16*e[u+f]),_,c),h.addToSelf(c));if(r)for(f=0;f<4;f++)_=a[u+f],_>0&&(Qe.FromFloat32ArrayToRefScaled(o,Math.floor(16*s[u+f]),_,c),h.addToSelf(c));n===Lt.NormalKind?Ye.TransformNormalFromFloatsToRef(i[d],i[d+1],i[d+2],h,l):Ye.TransformCoordinatesFromFloatsToRef(i[d],i[d+1],i[d+2],h,l),l.toArray(i,d),n===Lt.PositionKind&&this._positions&&this._positions[d/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(),r=e.getBoundingInfo();if(n.intersects(r,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 r=i;r1&&!s._checkCollision(e)||this._collideForSubMesh(s,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=Ze.Matrix[0],i=Ze.Matrix[1];return Qe.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,r,s=!1){const a=new wt,o="InstancedLinesMesh"===this.getClassName()||"LinesMesh"===this.getClassName()?this.intersectionThreshold:0,l=this.getBoundingInfo();if(!this.subMeshes)return a;if(!(s||e.intersectsSphere(l.boundingSphere,o)&&e.intersectsBox(l.boundingBox,o)))return a;if(n)return a.hit=!s,a.pickedMesh=s?null:this,a.distance=s?0:Ye.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),u=c.length;let d=!1;for(let e=0;e1&&!r.canIntersects(e))continue;const s=r.intersects(e,this._positions,this.getIndices(),t,i);if(s&&(t||!h||s.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:Ye.Zero()}e.depthSortedFacets=[];for(let t=0;tke?r.maximum.x-r.minimum.x:ke,e.bbSize.y=r.maximum.y-r.minimum.y>ke?r.maximum.y-r.minimum.y:ke,e.bbSize.z=r.maximum.z-r.minimum.z>ke?r.maximum.z-r.minimum.z:ke;let s=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(s=s>e.bbSize.z?s:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/s),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/s),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/s),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),Ye.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,n&&Li.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;nr.subDiv.max||a<0||a>r.subDiv.max||o<0||o>r.subDiv.max?null:r.facetPartitioning[s+r.subDiv.max*a+r.subDiv.max*r.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,i,n,r=!1,s=!0){const a=this.getWorldMatrix(),o=Ze.Matrix[5];a.invertToRef(o);const l=Ze.Vector3[8];Ye.TransformCoordinatesFromFloatsToRef(e,t,i,o,l);const h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,n,r,s);return n&&Ye.TransformCoordinatesFromFloatsToRef(n.x,n.y,n.z,a,n),h}getClosestFacetAtLocalCoordinates(e,t,i,n,r=!1,s=!0){let a=null,o=0,l=0,h=0,c=0,u=0,d=0,f=0,_=0;const p=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let v,E,T,C=Number.MAX_VALUE,R=C;for(let A=0;A=0||r&&!s&&c<=0)&&(c=E.x*T.x+E.y*T.y+E.z*T.z,u=-(E.x*e+E.y*t+E.z*i-c)/(E.x*E.x+E.y*E.y+E.z*E.z),d=e+E.x*u,f=t+E.y*u,_=i+E.z*u,o=d-e,l=f-t,h=_-i,R=o*o+l*l+h*h,Re.emitter===this))}}function $i(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function en(e,t,i){var n,r,s,a,o,l;let h=!1,c=null!==(n=e.clipPlane)&&void 0!==n?n:t.clipPlane;return h=rn(c,i,"CLIPPLANE")||h,c=null!==(r=e.clipPlane2)&&void 0!==r?r:t.clipPlane2,h=rn(c,i,"CLIPPLANE2")||h,c=null!==(s=e.clipPlane3)&&void 0!==s?s:t.clipPlane3,h=rn(c,i,"CLIPPLANE3")||h,c=null!==(a=e.clipPlane4)&&void 0!==a?a:t.clipPlane4,h=rn(c,i,"CLIPPLANE4")||h,c=null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5,h=rn(c,i,"CLIPPLANE5")||h,c=null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6,h=rn(c,i,"CLIPPLANE6")||h,h}function tn(e,t,i){var n,r,s,a,o,l;let h=null!==(n=t.clipPlane)&&void 0!==n?n:i.clipPlane;nn(e,"vClipPlane",h),h=null!==(r=t.clipPlane2)&&void 0!==r?r:i.clipPlane2,nn(e,"vClipPlane2",h),h=null!==(s=t.clipPlane3)&&void 0!==s?s:i.clipPlane3,nn(e,"vClipPlane3",h),h=null!==(a=t.clipPlane4)&&void 0!==a?a:i.clipPlane4,nn(e,"vClipPlane4",h),h=null!==(o=t.clipPlane5)&&void 0!==o?o:i.clipPlane5,nn(e,"vClipPlane5",h),h=null!==(l=t.clipPlane6)&&void 0!==l?l:i.clipPlane6,nn(e,"vClipPlane6",h)}function nn(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}function rn(e,t,i){let n=!0;if(e)if(Array.isArray(t)){const e="#define "+i;n=-1!==t.indexOf(e),n||t.push(e)}else n=t[i],t[i]=!0;return!n}Ji.OCCLUSION_TYPE_NONE=0,Ji.OCCLUSION_TYPE_OPTIMISTIC=1,Ji.OCCLUSION_TYPE_STRICT=2,Ji.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,Ji.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,Ji.CULLINGSTRATEGY_STANDARD=0,Ji.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Ji.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Ji.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,Ie("BABYLON.AbstractMesh",Ji);class sn{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!==mi.FOGMODE_NONE}static PrepareDefinesForMisc(e,t,i,n,r,s,a){a._areMiscDirty&&(a.LOGARITHMICDEPTH=i,a.POINTSIZE=n,a.FOG=r&&this.GetFogState(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=s)}static PrepareDefinesForCamera(e,t){let i=!1;if(e.activeCamera){const n=t.CAMERA_ORTHOGRAPHIC?1:0,r=t.CAMERA_PERSPECTIVE?1:0,s=e.activeCamera.mode===Fi.ORTHOGRAPHIC_CAMERA?1:0,a=e.activeCamera.mode===Fi.PERSPECTIVE_CAMERA?1:0;(n^s||r^a)&&(t.CAMERA_ORTHOGRAPHIC=1===s,t.CAMERA_PERSPECTIVE=1===a,i=!0)}return i}static PrepareDefinesForFrameBoundValues(e,t,i,n,r,s=null,a=!1){let o=sn.PrepareDefinesForCamera(e,n);!1!==s&&(o=en(i,e,n)),n.DEPTHPREPASS!==!t.getColorWrite()&&(n.DEPTHPREPASS=!n.DEPTHPREPASS,o=!0),n.INSTANCES!==r&&(n.INSTANCES=r,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,r=!1,s=!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&&s}return e.isVerticesDataPresent(Lt.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),n&&this.PrepareDefinesForBones(e,t),r&&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,r=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&&r===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){const n=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{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(r,n))}}i.lightmapMode!=ui.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+n]=!0,r["LIGHTMAPNOSPECULAR"+n]=i.lightmapMode==ui.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+n]=!1,r["LIGHTMAPNOSPECULAR"+n]=!1)}static PrepareDefinesForLights(e,t,i,n,r=4,s=!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&&!s)for(const s of t.lightSources)if(this.PrepareDefinesForLight(e,t,s,a,i,n,o),a++,a===r)break;i.SPECULARTERM=o.specularEnabled,i.SHADOWS=o.shadowEnabled;for(let e=a;e0&&(r=n+s,t.addFallback(r,"LIGHT"+s)),e.SHADOWS||(e["SHADOW"+s]&&t.addFallback(n,"SHADOW"+s),e["SHADOWPCF"+s]&&t.addFallback(n,"SHADOWPCF"+s),e["SHADOWPCSS"+s]&&t.addFallback(n,"SHADOWPCSS"+s),e["SHADOWPOISSON"+s]&&t.addFallback(n,"SHADOWPOISSON"+s),e["SHADOWESM"+s]&&t.addFallback(n,"SHADOWESM"+s),e["SHADOWCLOSEESM"+s]&&t.addFallback(n,"SHADOWCLOSEESM"+s));return r++}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&&f.LastCreatedEngine){const r=f.LastCreatedEngine.getCaps().maxVertexAttribs,s=t.morphTargetManager;if(null==s?void 0:s.isUsingTextureForTargets)return;const a=s&&s.supportsNormals&&i.NORMAL,o=s&&s.supportsTangents&&i.TANGENT,l=s&&s.supportsUVs&&i.UV1;for(let i=0;ir&&p.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,r,s=!0){e._bindLight(t,i,n,r,s)}static BindLights(e,t,i,n,r=4){const s=Math.min(t.lightSources.length,r);for(let r=0;r-1){const i=n.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(n.bones.length+1))}else{const r=n.getTransformMatrices(e);r&&(t.setMatrices("mBones",r),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=r.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),sn._CopyBonesTransformationMatrices(r,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===Fi.ORTHOGRAPHIC_CAMERA&&p.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}}sn._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},sn._TempFogColor=tt.Black();class an{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){Et.Clone((()=>e),this)}serialize(){return Et.Serialize(this)}parse(e,t,i){Et.Parse((()=>this),e,t,i)}}var on,ln;et([ct()],an.prototype,"func",null),et([ct()],an.prototype,"funcRef",null),et([ct()],an.prototype,"funcMask",null),et([ct()],an.prototype,"opStencilFail",null),et([ct()],an.prototype,"opDepthFail",null),et([ct()],an.prototype,"opStencilDepthPass",null),et([ct()],an.prototype,"mask",null),et([ct()],an.prototype,"enabled",null),(ln=on||(on={}))[ln.Created=1]="Created",ln[ln.Disposed=2]="Disposed",ln[ln.GetDefineNames=4]="GetDefineNames",ln[ln.PrepareUniformBuffer=8]="PrepareUniformBuffer",ln[ln.IsReadyForSubMesh=16]="IsReadyForSubMesh",ln[ln.PrepareDefines=32]="PrepareDefines",ln[ln.BindForSubMesh=64]="BindForSubMesh",ln[ln.PrepareEffect=128]="PrepareEffect",ln[ln.GetAnimatables=256]="GetAnimatables",ln[ln.GetActiveTextures=512]="GetActiveTextures",ln[ln.HasTexture=1024]="HasTexture",ln[ln.FillRenderTargetTextures=2048]="FillRenderTargetTextures",ln[ln.HasRenderTargetTextures=4096]="HasRenderTargetTextures",ln[ln.HardBindForSubMesh=8192]="HardBindForSubMesh";class hn{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 n,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 an,this._useUBO=!1,this._fillMode=hn.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 r=t||f.LastCreatedScene;r&&(this._scene=r,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||Pe.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new X(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=hn.ClockWiseSideOrientation:this.sideOrientation=hn.CounterClockWiseSideOrientation,this._uniformBuffer=new Nt(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),hn.OnEventObservable.notifyObservers(this,on.Created))}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(hn.MiscDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(hn.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(hn.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 n),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 n),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new n),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(hn.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(hn.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case hn.WireFrameFillMode:case hn.LineListDrawMode:case hn.LineLoopDrawMode:case hn.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?hn.WireFrameFillMode:hn.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case hn.PointFillMode:case hn.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?hn.PointFillMode:hn.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(hn.MiscDirtyFlag))}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}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===hn.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===hn.MATERIAL_OPAQUE||this._transparencyMode===hn.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(hn.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),n=(null==t?this.sideOrientation:t)===hn.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(on.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,sn.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(on.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(on.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(on.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 r={clipPlane:!1,useInstances:!1,...i},s=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const o=()=>{if(!this._scene||!this._scene.getEngine())return;const i=s.clipPlane;if(r.clipPlane&&(s.clipPlane=new li(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,s=null;if(e.subMeshes){const t=new Yi(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,r.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?s=t.effect.getCompilationError():(i=!1,setTimeout(o,16)))}i&&(this.allowShaderHotSwapping=a,s&&n&&n(s),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(o,16);r.clipPlane&&(s.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||(hn._DirtyCallbackArray.length=0,e&hn.TextureDirtyFlag&&hn._DirtyCallbackArray.push(hn._TextureDirtyCallBack),e&hn.LightDirtyFlag&&hn._DirtyCallbackArray.push(hn._LightsDirtyCallBack),e&hn.FresnelDirtyFlag&&hn._DirtyCallbackArray.push(hn._FresnelDirtyCallBack),e&hn.AttributesDirtyFlag&&hn._DirtyCallbackArray.push(hn._AttributeDirtyCallBack),e&hn.MiscDirtyFlag&&hn._DirtyCallbackArray.push(hn._MiscDirtyCallBack),e&hn.PrePassDirtyFlag&&hn._DirtyCallbackArray.push(hn._PrePassDirtyCallBack),hn._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(hn._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(hn._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(hn._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(hn._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(hn._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(hn._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(hn._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(hn._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(hn._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(hn._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(hn._TextureAndMiscDirtyCallBack)}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(on.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=Et.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 p.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=Pe.Instantiate(e.customType).Parse(e,t,i);return n._loadedUniqueId=e.uniqueId,n}}hn.TriangleFillMode=0,hn.WireFrameFillMode=1,hn.PointFillMode=2,hn.PointListDrawMode=3,hn.LineListDrawMode=4,hn.LineLoopDrawMode=5,hn.LineStripDrawMode=6,hn.TriangleStripDrawMode=7,hn.TriangleFanDrawMode=8,hn.ClockWiseSideOrientation=0,hn.CounterClockWiseSideOrientation=1,hn.TextureDirtyFlag=1,hn.LightDirtyFlag=2,hn.FresnelDirtyFlag=4,hn.AttributesDirtyFlag=8,hn.MiscDirtyFlag=16,hn.PrePassDirtyFlag=32,hn.AllDirtyFlag=63,hn.MATERIAL_OPAQUE=0,hn.MATERIAL_ALPHATEST=1,hn.MATERIAL_ALPHABLEND=2,hn.MATERIAL_ALPHATESTANDBLEND=3,hn.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,hn.MATERIAL_NORMALBLENDMETHOD_RNM=1,hn.OnEventObservable=new n,hn._AllDirtyCallBack=e=>e.markAllAsDirty(),hn._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),hn._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),hn._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),hn._MiscDirtyCallBack=e=>e.markAsMiscDirty(),hn._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),hn._LightsDirtyCallBack=e=>e.markAsLightDirty(),hn._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),hn._FresnelAndMiscDirtyCallBack=e=>{hn._FresnelDirtyCallBack(e),hn._MiscDirtyCallBack(e)},hn._TextureAndMiscDirtyCallBack=e=>{hn._TextureDirtyCallBack(e),hn._MiscDirtyCallBack(e)},hn._DirtyCallbackArray=[],hn._RunDirtyCallBacks=e=>{for(const t of hn._DirtyCallbackArray)t(e)},et([ct()],hn.prototype,"id",void 0),et([ct()],hn.prototype,"uniqueId",void 0),et([ct()],hn.prototype,"name",void 0),et([ct()],hn.prototype,"metadata",void 0),et([ct()],hn.prototype,"checkReadyOnEveryCall",void 0),et([ct()],hn.prototype,"checkReadyOnlyOnce",void 0),et([ct()],hn.prototype,"state",void 0),et([ct("alpha")],hn.prototype,"_alpha",void 0),et([ct("backFaceCulling")],hn.prototype,"_backFaceCulling",void 0),et([ct("cullBackFaces")],hn.prototype,"_cullBackFaces",void 0),et([ct()],hn.prototype,"sideOrientation",void 0),et([ct("alphaMode")],hn.prototype,"_alphaMode",void 0),et([ct()],hn.prototype,"_needDepthPrePass",void 0),et([ct()],hn.prototype,"disableDepthWrite",void 0),et([ct()],hn.prototype,"disableColorWrite",void 0),et([ct()],hn.prototype,"forceDepthWrite",void 0),et([ct()],hn.prototype,"depthFunction",void 0),et([ct()],hn.prototype,"separateCullingPass",void 0),et([ct("fogEnabled")],hn.prototype,"_fogEnabled",void 0),et([ct()],hn.prototype,"pointSize",void 0),et([ct()],hn.prototype,"zOffset",void 0),et([ct()],hn.prototype,"zOffsetUnits",void 0),et([ct()],hn.prototype,"pointsCloud",null),et([ct()],hn.prototype,"fillMode",null),et([ct()],hn.prototype,"transparencyMode",null);class cn extends hn{constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().multiMaterials.push(this),this.subMaterials=new Array,this._storeEffectOnSubMeshes=!0}get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}_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 r=i.apply(e,[t,n]);return this._markAllSubMeshesAsTexturesDirty(),r}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map((e=>e?e.getActiveTextures():[])))}hasTexture(e){var t;if(super.hasTexture(e))return!0;for(let i=0;i=0&&n.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new cn(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,we&&we.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}Ie("BABYLON.MultiMaterial",cn);class un{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class dn{}class fn{constructor(){this.visibleInstances={},this.batchCache=new _n,this.batchCacheReplacementModeInFrozenMode=new _n,this.instancesBufferSize=2048}}class _n{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=new Array,this.hardwareInstancedRendering=new Array}}class pn{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class mn{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 gn extends Ji{constructor(e,t=null,i=null,r=null,s,a=!0){if(super(e,t),this._internalMeshDataInfo=new mn,this.delayLoadState=0,this.instances=new Array,this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new fn,this._thinInstanceDataStorage=new pn,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=gn.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))},r){if(r._geometry&&r._geometry.applyToMesh(this),$.DeepCopy(r,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=r,t.useClonedMeshMap&&(r._internalMeshDataInfo.meshMap||(r._internalMeshDataInfo.meshMap={}),r._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=r._originalBuilderSideOrientation,this._creationDataStorage=r._creationDataStorage,r._ranges){const e=r._ranges;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(r.metadata&&r.metadata.clone?this.metadata=r.metadata.clone():this.metadata=r.metadata,we&&we.HasTags(r)&&we.AddTagsTo(this,we.GetTags(r,!0)),this.setEnabled(r.isEnabled(!1)),this.parent=r.parent,this.setPivotMatrix(r.getPivotMatrix()),this.id=e+"."+r.id,this.material=r.material,!s){const t=r.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 n(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}static _GetDefaultSideOrientation(e){return e||gn.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 n),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new n),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new n),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new n),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new n),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}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.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 p.Warn("You cannot use a mesh as LOD level twice"),this;const i=new un(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*s)return this.onLODLevelSelection&&this.onLODLevelSelection(s,this,this),this;for(let e=0;e0||this.hasThinInstances);this.computeWorldMatrix();const u=this.material||h.defaultMaterial;if(u)if(u._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(!u.isReady(this,c))return!1;const d=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===(s=null===(r=t.getShadowMap())||void 0===r?void 0:r.renderList)||void 0===s?void 0:s.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=d,!1;l.currentRenderPassId=d}}}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 r=!1;if(e)r=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>n){r=!0;break}if(e.verticesStart+e.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new Yi(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 r=0;r=t);r++)Yi.CreateFromIndices(0,n,r===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 Li;n.set(t,e);const r=this.getScene();new qi(qi.RandomId(),r,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=qi.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;Li.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(qi.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 Li;t.indices=e;const n=this.getScene();new qi(qi.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){if(!this._geometry)return this;const n=this.getScene().getEngine();let r;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)r=null;else switch(i){case hn.PointFillMode:r=null;break;case hn.WireFrameFillMode:r=e._getLinesIndexBuffer(this.getIndices(),n);break;default:case hn.TriangleFillMode:r=this._geometry.getIndexBuffer()}return!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,r):this._geometry._bind(t,r,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),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==hn.PointFillMode?n.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==hn.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(),r=n?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,s=this._instanceDataStorage.batchCache;if(s.mustReturn=!1,s.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,s.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,r=i.getRenderId(),a=n?t.intermediateDefaultRenderId:t.defaultRenderId;s.visibleInstances[e]=t[r],!s.visibleInstances[e]&&a&&(s.visibleInstances[e]=t[a])}return s.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==s.visibleInstances[e]&&void 0!==s.visibleInstances[e],this._instanceDataStorage.previousBatch=s,s}_renderWithInstances(e,t,i,n,r){var s;const a=i.visibleInstances[e._id],o=a?a.length:0,l=this._instanceDataStorage,h=l.instancesBufferSize;let c=l.instancesBuffer,u=l.instancesPreviousBuffer;const d=16*(o+1)*4;for(;l.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamerai&&n++,0!==s&&u++,c+=s,i=s}if(l[u]++,u>s&&(s=u),0===c)r++;else{const i=1/c;let n=0;for(let r=0;r.001&&a++}}const h=this.skeleton.bones.length,c=this.getVerticesData(Lt.MatricesIndicesKind),u=this.getVerticesData(Lt.MatricesIndicesExtraKind);let d=0;for(let e=0;e=h||i<0)&&d++}return{skinned:!0,valid:0===r&&0===a&&0===d,report:"Number of Weights = "+i/4+"\nMaximum influences = "+s+"\nMissing Weights = "+r+"\nNot Sorted = "+n+"\nNot Normalized = "+a+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+d}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return Pe.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=Ye.Zero();let r;for(r=0;r{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,r,s,a),n&&n(this)}),(()=>{}),o.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,n,r,s,a,o=!1){if(!this.isVerticesDataPresent(Lt.PositionKind)||!this.isVerticesDataPresent(Lt.NormalKind)||!this.isVerticesDataPresent(Lt.UVKind))return p.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),c=this.getVerticesData(Lt.UVKind);let u=Ye.Zero();const d=Ye.Zero(),f=He.Zero();s=s||He.Zero(),a=a||new He(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),u=Ye.Zero(),d=new Qe,f=new Qe;let _,p=0;for(let e=0;e0&&(Qe.FromFloat32ArrayToRefScaled(c,Math.floor(16*s[p+_]),m,f),d.addToSelf(f));if(o)for(_=0;_<4;_++)m=h[p+_],m>0&&(Qe.FromFloat32ArrayToRefScaled(c,Math.floor(16*l[p+_]),m,f),d.addToSelf(f));Ye.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],d,u),u.toArray(n,e),t&&(Ye.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],d,u),u.toArray(r,e)),d.reset()}return this.updateVerticesData(Lt.PositionKind,n),t&&this.updateVerticesData(Lt.NormalKind,r),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:Ye.Zero(),max:Ye.Zero()}}static Center(e){const t=e instanceof Array?gn.MinMax(e):e;return Ye.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,n,r,s){return Ni(gn._MergeMeshesCoroutine(e,t,i,n,r,s,!1))}static MergeMeshesAsync(e,t=!0,i,n,r,s){return a=gn._MergeMeshesCoroutine(e,t,i,n,r,s,!0),o=function(e=25){let t;return(i,n,r)=>{const s=performance.now();void 0===t||s-t>e?(t=s,setTimeout((()=>{Oi(i,n,r)}),0)):Oi(i,n,r)}}(),new Promise(((e,t)=>{Di(a,o,e,t,l)}));var a,o,l}static*_MergeMeshesCoroutine(e,t=!0,i,n,r,s,a){if(0===(e=e.filter(Boolean)).length)return null;let o;if(!i){let t=0;for(o=0;o=65536)return p.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}s&&(r=!1);const l=new Array,h=new Array,c=new Array,u=e[0].overrideMaterialSideOrientation;for(o=0;o{const t=e.computeWorldMatrix(!0);return[Li.ExtractFromMesh(e,!1,!1),t]},[_,m]=f(d);a&&(yield);const g=new Array(e.length-1);for(let t=1;t{throw _("GroundMesh")},gn._GoldbergMeshParser=(e,t)=>{throw _("GoldbergMesh")},gn._LinesMeshParser=(e,t)=>{throw _("LinesMesh")},Ie("BABYLON.Mesh",gn),gn.prototype.setMaterialByID=function(e){return this.setMaterialById(e)},gn.CreateDisc=gn.CreateDisc||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.CreateBox=gn.CreateBox||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.CreateSphere=gn.CreateSphere||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.CreateCylinder=gn.CreateCylinder||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.CreateTorusKnot=gn.CreateTorusKnot||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.CreateTorus=gn.CreateTorus||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.CreatePlane=gn.CreatePlane||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.CreateGround=gn.CreateGround||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.CreateTiledGround=gn.CreateTiledGround||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.CreateGroundFromHeightMap=gn.CreateGroundFromHeightMap||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.CreateTube=gn.CreateTube||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.CreatePolyhedron=gn.CreatePolyhedron||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.CreateIcoSphere=gn.CreateIcoSphere||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.CreateDecal=gn.CreateDecal||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.CreateCapsule=gn.CreateCapsule||(()=>{throw new Error("Import MeshBuilder to populate this function")}),gn.ExtendToGoldberg=gn.ExtendToGoldberg||(()=>{throw new Error("Import MeshBuilder to populate this function")});class vn extends hn{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new Qe,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)}}class En{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,Z.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,Z.MarkAllMaterialsAsDirty(1))}}En._DiffuseTextureEnabled=!0,En._DetailTextureEnabled=!0,En._AmbientTextureEnabled=!0,En._OpacityTextureEnabled=!0,En._ReflectionTextureEnabled=!0,En._EmissiveTextureEnabled=!0,En._SpecularTextureEnabled=!0,En._BumpTextureEnabled=!0,En._LightmapTextureEnabled=!0,En._RefractionTextureEnabled=!0,En._ColorGradingTextureEnabled=!0,En._FresnelEnabled=!0,En._ClearCoatTextureEnabled=!0,En._ClearCoatBumpTextureEnabled=!0,En._ClearCoatTintTextureEnabled=!0,En._SheenTextureEnabled=!0,En._AnisotropicTextureEnabled=!0,En._ThicknessTextureEnabled=!0,En._RefractionIntensityTextureEnabled=!0,En._TranslucencyIntensityTextureEnabled=!0,En._IridescenceTextureEnabled=!0;P.IncludesShadersStore.backgroundFragmentDeclaration="uniform vec4 vEyePosition;\nuniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n";P.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";P.IncludesShadersStore.backgroundUboDeclaration="layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\n#include\n";P.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";P.IncludesShadersStore.reflectionFunction="vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)\n{\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y;\nreturn vec3(s,t,0); \n}\nvec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)\n{\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y;\nreturn vec3(1.0-s,t,0); \n}\nvec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{\nvec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nr=vec3(reflectionMatrix*vec4(r,0));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y;\nreturn vec3(s,t,0);\n}\nvec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix)\n{\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr=vec3(reflectionMatrix*vec4(r,0));\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n}\nvec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{\nvec3 viewDir=worldPos.xyz-eyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n}\nvec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{\nvec3 viewDir=normalize(worldPos.xyz-eyePosition);\nvec3 coords=reflect(viewDir,worldNormal);\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n}\nvec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition)\n{\nvec3 viewDir=normalize(worldPos.xyz-eyePosition);\nvec3 coords=reflect(viewDir,worldNormal);\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n}\nvec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix)\n{\nreturn vec3(reflectionMatrix*(view*worldPos));\n}\nvec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix)\n{\nreturn vec3(reflectionMatrix*vec4(positionW,1.));\n}\n#ifdef REFLECTION\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nreturn computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nreturn computeFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nreturn computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nreturn computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nreturn computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_CUBIC\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nreturn computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition);\n#else\nreturn computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn computeProjectionCoords(worldPos,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn computeSkyBoxCoords(vPositionUVW,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\n";P.IncludesShadersStore.imageProcessingDeclaration="#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#if defined(VIGNETTE) || defined(DITHER)\nuniform vec2 vInverseScreenSize;\n#endif\n#ifdef VIGNETTE\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef DITHER\nuniform float ditherIntensity;\n#endif\n";P.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";P.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";P.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}";P.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;i(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t*=2,this.reflectionReflectance0=Rn.StandardReflectance0*t,this.reflectionReflectance90=Rn.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=Rn.StandardReflectance0+(1-Rn.StandardReflectance0)*t,this.reflectionReflectance90=Rn.StandardReflectance90+(1-Rn.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_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._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()}))))}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}get hasRenderTargetTextures(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new Cn);const n=this.getScene(),r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const s=n.getEngine();if(sn.PrepareDefinesForLights(n,e,r,!1,this._maxSimultaneousLights),r._needNormals=!0,sn.PrepareDefinesForMultiview(n,r),r._areTexturesDirty){if(r._needUVs=!1,n.texturesEnabled){if(n.getEngine().getCaps().textureLOD&&(r.TEXTURELODSUPPORT=!0),this._diffuseTexture&&En.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;sn.PrepareDefinesForMergedUV(this._diffuseTexture,r,"DIFFUSE"),r.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,r.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,r.OPACITYFRESNEL=this._opacityFresnel}else r.DIFFUSE=!1,r.DIFFUSEDIRECTUV=0,r.DIFFUSEHASALPHA=!1,r.GAMMADIFFUSE=!1,r.OPACITYFRESNEL=!1;const e=this._reflectionTexture;if(e&&En.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(r.REFLECTION=!0,r.GAMMAREFLECTION=e.gammaSpace,r.RGBDREFLECTION=e.isRGBD,r.REFLECTIONBLUR=this._reflectionBlur>0,r.LODINREFLECTIONALPHA=e.lodLevelInAlpha,r.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,r.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===Si.INVCUBIC_MODE&&(r.INVERTCUBICMAP=!0),r.REFLECTIONMAP_3D=e.isCube,r.REFLECTIONMAP_OPPOSITEZ=r.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case Si.EXPLICIT_MODE:r.REFLECTIONMAP_EXPLICIT=!0;break;case Si.PLANAR_MODE:r.REFLECTIONMAP_PLANAR=!0;break;case Si.PROJECTION_MODE:r.REFLECTIONMAP_PROJECTION=!0;break;case Si.SKYBOX_MODE:r.REFLECTIONMAP_SKYBOX=!0;break;case Si.SPHERICAL_MODE:r.REFLECTIONMAP_SPHERICAL=!0;break;case Si.EQUIRECTANGULAR_MODE:r.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Si.FIXED_EQUIRECTANGULAR_MODE:r.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Si.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:r.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Si.CUBIC_MODE:case Si.INVCUBIC_MODE:default:r.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(r.REFLECTIONFRESNEL=!0,r.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(r.REFLECTIONFRESNEL=!1,r.REFLECTIONFALLOFF=!1)}else r.REFLECTION=!1,r.REFLECTIONFRESNEL=!1,r.REFLECTIONFALLOFF=!1,r.REFLECTIONBLUR=!1,r.REFLECTIONMAP_3D=!1,r.REFLECTIONMAP_SPHERICAL=!1,r.REFLECTIONMAP_PLANAR=!1,r.REFLECTIONMAP_CUBIC=!1,r.REFLECTIONMAP_PROJECTION=!1,r.REFLECTIONMAP_SKYBOX=!1,r.REFLECTIONMAP_EXPLICIT=!1,r.REFLECTIONMAP_EQUIRECTANGULAR=!1,r.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,r.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,r.INVERTCUBICMAP=!1,r.REFLECTIONMAP_OPPOSITEZ=!1,r.LODINREFLECTIONALPHA=!1,r.GAMMAREFLECTION=!1,r.RGBDREFLECTION=!1}r.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,r.USERGBCOLOR=this._useRGBColor,r.NOISE=this._enableNoise}if(r._areLightsDirty&&(r.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),r.BACKMAT_SHADOWONLY=this._shadowOnly),r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r)}if(sn.PrepareDefinesForMisc(e,n,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),sn.PrepareDefinesForFrameBoundValues(n,s,this,r,i,null,t.getRenderingMesh().hasThinInstances),sn.PrepareDefinesForAttributes(e,r,!1,!0,!1)&&e&&(n.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(Lt.NormalKind)||(e.createNormals(!0),p.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;r.FOG&&i.addFallback(0,"FOG"),r.POINTSIZE&&i.addFallback(1,"POINTSIZE"),r.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),sn.HandleFallbacksForShadows(r,i,this._maxSimultaneousLights);const a=[Lt.PositionKind];r.NORMAL&&a.push(Lt.NormalKind),r.UV1&&a.push(Lt.UVKind),r.UV2&&a.push(Lt.UV2Kind),sn.PrepareAttributesForBones(a,e,r,i),sn.PrepareAttributesForInstances(a,r);const o=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix"];$i(o);const l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];bt&&(bt.PrepareUniforms(o,r),bt.PrepareSamplers(l,r)),sn.PrepareUniformsAndSamplersList({uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:r,maxSimultaneousLights:this._maxSimultaneousLights});const c=r.toString(),u=n.getEngine().createEffect("background",{attributes:a,uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:c,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},s);t.setEffect(u,r,this._materialContext),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,n.performancePriority!==di.BackwardCompatible&&(this.checkReadyOnlyOnce=!0),0))}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const n=this.getScene(),r=i.materialDefines;if(!r)return;const s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e),sn.BindBonesParameters(t,this._activeEffect);const a=this._mustRebind(n,s,t.visibility);if(a){this._uniformBuffer.bindToEffect(s,"Material"),this.bindViewProjection(s);const e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(n.texturesEnabled&&(this._diffuseTexture&&En.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),sn.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&En.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),r.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),n.texturesEnabled&&(this._diffuseTexture&&En.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&En.ReflectionTextureEnabled&&(r.REFLECTIONBLUR&&r.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):r.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),r.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w)))),tn(this._activeEffect,this,n),n.bindEyePosition(s)}else n.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(s,"Material"),this._needToBindSceneUbo=!0);!a&&this.isFrozen||(n.lightsEnabled&&sn.BindLights(n,t,this._activeEffect,r,this._maxSimultaneousLights),this.bindView(s),sn.BindFogParameters(n,t,this._activeEffect,!0),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return Et.Clone((()=>new Rn(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return Et.Parse((()=>new Rn(e.name,t)),e,t,i)}}function An(e){const t=e.segments||32,i=e.diameterX||e.diameter||1,n=e.diameterY||e.diameter||1,r=e.diameterZ||e.diameter||1,s=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,a=e.slice&&e.slice<=0?1:e.slice||1,o=0===e.sideOrientation?0:e.sideOrientation||Li.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new Ye(i/2,n/2,r/2),c=2+t,u=2*c,d=[],f=[],_=[],p=[];for(let e=0;e<=c;e++){const t=e/c,i=t*Math.PI*a;for(let e=0;e<=u;e++){const n=e/u,r=n*Math.PI*2*s,a=Qe.RotationZ(-i),o=Qe.RotationY(r),l=Ye.TransformCoordinates(Ye.Up(),a),c=Ye.TransformCoordinates(l,o),d=c.multiply(h),m=c.divide(h).normalize();f.push(d.x,d.y,d.z),_.push(m.x,m.y,m.z),p.push(n,bi.UseOpenGLOrientationForUV?1-t:t)}if(e>0){const t=f.length/3;for(let i=t-2*(u+1);i+u+21&&(d.push(i),d.push(i+1),d.push(i+u+1)),(ebn(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:s,updatable:r},n);class Sn extends Pi{constructor(e,t,i,r,s=null){super(e,r),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=Sn.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new n,this.onLoadObservable=new n,r=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=Boolean(i.clickToPlay),i.autoPlay=void 0===i.autoPlay||Boolean(i.autoPlay),i.loop=void 0===i.loop||Boolean(i.loop),i.size=Math.abs(i.size)||(r.activeCamera?.48*r.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=bn(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:gn.BACKSIDE},r);const a=this._material=new Rn(e+"_material",r);a.useEquirectangularFOV=!0,a.fovMultiplier=1,a.opacityFresnel=!1;const o=this._initTexture(t,r,i);if(this.texture=o,this._mesh.material=a,this._mesh.parent=this,this._halfDomeMask=bn("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:gn.BACKSIDE},r),this._halfDomeMask.rotate(gi.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce((()=>{this._setReady(!0)})),i.faceForward&&r.activeCamera){const e=r.activeCamera,t=Ye.Forward(),i=Ye.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(Ye.Dot(t,i))}this._changeTextureMode(this._textureMode)}get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=Si.CLAMP_ADDRESSMODE,this._texture.wrapV=Si.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=Si.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=Si.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case Sn.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case Sn.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((i=>{let n=i.isRightCamera;this._crossEye&&(n=!n),this._texture.uOffset=n?e:t}));break}case Sn.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0}))}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}Sn.MODE_MONOSCOPIC=0,Sn.MODE_TOPBOTTOM=1,Sn.MODE_SIDEBYSIDE=2;class In extends Sn{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const n={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},r=new xi((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,Si.TRILINEAR_SAMPLINGMODE,n);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add((e=>{var t;(null===(t=e.pickInfo)||void 0===t?void 0:t.pickedMesh)===this.mesh&&this._texture.video.play()}),Wt.POINTERDOWN)),this._textureObserver=r.onLoadObservable.add((()=>{this.onLoadObservable.notifyObservers()})),r}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}In.MODE_MONOSCOPIC=Sn.MODE_MONOSCOPIC,In.MODE_TOPBOTTOM=Sn.MODE_TOPBOTTOM,In.MODE_SIDEBYSIDE=Sn.MODE_SIDEBYSIDE;class xn{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==Wt.POINTERDOWN?e.type===Wt.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=H.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const i=e-this._lastInteractionTime-this._idleRotationWaitTime,n=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*n,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=null!=e?e:H.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha)=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}yn.EASINGMODE_EASEIN=0,yn.EASINGMODE_EASEOUT=1,yn.EASINGMODE_EASEINOUT=2;class Mn extends yn{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class Pn extends yn{easeInCore(e){return e*e}}class On extends yn{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}var Dn;!function(e){e[e.NONE=0]="NONE",e[e.STEP=1]="STEP"}(Dn||(Dn={}));class Nn{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new Nn(this.name,this.from,this.to)}}class Fn{constructor(e,t,i,n,r,s){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=n,this.loopMode=r,this.enableBlending=s,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===r?Fn.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=Fn._UniqueIdGenerator++}static _PrepareAnimation(e,t,i,n,r,s,a,o){let l;if(!isNaN(parseFloat(r))&&isFinite(r)?l=Fn.ANIMATIONTYPE_FLOAT:r instanceof qe?l=Fn.ANIMATIONTYPE_QUATERNION:r instanceof Ye?l=Fn.ANIMATIONTYPE_VECTOR3:r instanceof He?l=Fn.ANIMATIONTYPE_VECTOR2:r instanceof tt?l=Fn.ANIMATIONTYPE_COLOR3:r instanceof it?l=Fn.ANIMATIONTYPE_COLOR4:r instanceof Ei&&(l=Fn.ANIMATIONTYPE_SIZE),null==l)return null;const h=new Fn(e,t,i,l,a),c=[{frame:0,value:r},{frame:n,value:s}];return h.setKeys(c),void 0!==o&&h.setEasingFunction(o),h}static CreateAnimation(e,t,i,n){const r=new Fn(e+"Animation",e,i,t,Fn.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(n),r}static CreateAndStartAnimation(e,t,i,n,r,s,a,o,l,h,c){const u=Fn._PrepareAnimation(e,i,n,r,s,a,o,l);return u?(t.getScene&&(c=t.getScene()),c?c.beginDirectAnimation(t,[u],0,r,1===u.loopMode,1,h):null):null}static CreateAndStartHierarchyAnimation(e,t,i,n,r,s,a,o,l,h,c){const u=Fn._PrepareAnimation(e,n,r,s,a,o,l,h);return u?t.getScene().beginDirectHierarchyAnimation(t,i,[u],0,s,1===u.loopMode,1,c):null}static CreateMergeAndStartAnimation(e,t,i,n,r,s,a,o,l,h){const c=Fn._PrepareAnimation(e,i,n,r,s,a,o,l);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,r,1===c.loopMode,1,h)):null}static MakeAnimationAdditive(e,t=0,i,n=!1,r){let s=e;if(n&&(s=e.clone(),s.name=r||s.name),!s._keys.length)return s;t=t>=0?t:0;let a=0;const o=s._keys[0];let l=s._keys.length-1;const h=s._keys[l],c={referenceValue:o.value,referencePosition:Ze.Vector3[0],referenceQuaternion:Ze.Quaternion[0],referenceScaling:Ze.Vector3[1],keyPosition:Ze.Vector3[2],keyQuaternion:Ze.Quaternion[1],keyScaling:Ze.Vector3[3]};let u=!1,d=o.frame,f=h.frame;if(i){const e=s.getRange(i);e&&(d=e.from,f=e.to)}let _=o.frame===d,p=h.frame===f;if(1===s._keys.length){const e=s._getKeyValue(s._keys[0]);c.referenceValue=e.clone?e.clone():e,u=!0}else if(t<=o.frame){const e=s._getKeyValue(o.value);c.referenceValue=e.clone?e.clone():e,u=!0}else if(t>=h.frame){const e=s._getKeyValue(h.value);c.referenceValue=e.clone?e.clone():e,u=!0}let m=0;for(;!u||!_||!p&&m=e.frame&&t<=i.frame){let n;if(t===e.frame)n=s._getKeyValue(e.value);else if(t===i.frame)n=s._getKeyValue(i.value);else{const e={key:m,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT};n=s._interpolate(t,e)}c.referenceValue=n.clone?n.clone():n,u=!0}if(!_&&d>=e.frame&&d<=i.frame){if(d===e.frame)a=m;else if(d===i.frame)a=m+1;else{const e={key:m,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},t=s._interpolate(d,e),i={frame:d,value:t.clone?t.clone():t};s._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=s._interpolate(f,e),i={frame:f,value:t.clone?t.clone():t};s._keys.splice(m+1,0,i),l=m+1}p=!0}m++}for(s.dataType===Fn.ANIMATIONTYPE_QUATERNION?c.referenceValue.normalize().conjugateInPlace():s.dataType===Fn.ANIMATIONTYPE_MATRIX&&(c.referenceValue.decompose(c.referenceScaling,c.referenceQuaternion,c.referencePosition),c.referenceQuaternion.normalize().conjugateInPlace()),m=a;m<=l;m++){const e=s._keys[m];if(!m||s.dataType===Fn.ANIMATIONTYPE_FLOAT||e.value!==o.value)switch(s.dataType){case Fn.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),Qe.ComposeToRef(c.keyScaling,c.keyQuaternion,c.keyPosition,e.value);break;case Fn.ANIMATIONTYPE_QUATERNION:c.referenceValue.multiplyToRef(e.value,e.value);break;case Fn.ANIMATIONTYPE_VECTOR2:case Fn.ANIMATIONTYPE_VECTOR3:case Fn.ANIMATIONTYPE_COLOR3:case Fn.ANIMATIONTYPE_COLOR4:e.value.subtractToRef(c.referenceValue,e.value);break;case Fn.ANIMATIONTYPE_SIZE:e.value.width-=c.referenceValue.width,e.value.height-=c.referenceValue.height;break;default:e.value-=c.referenceValue}}return s}static TransitionTo(e,t,i,n,r,s,a,o=null){if(a<=0)return i[e]=t,o&&o(),null;const l=r*(a/1e3);s.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(s);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}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 r=t.key;for(;r>=0&&e=i[r+1].frame;)++r;if(t.key=r,r<0)return this._getKeyValue(i[0].value);if(r+1>n-1)return this._getKeyValue(i[n-1].value);const s=i[r],a=i[r+1],o=this._getKeyValue(s.value),l=this._getKeyValue(a.value);if(s.interpolation===Dn.STEP)return a.frame>e?o:l;const h=void 0!==s.outTangent&&void 0!==a.inTangent,c=a.frame-s.frame;let u=(e-s.frame)/c;const d=this.getEasingFunction();switch(null!==d&&(u=d.ease(u)),this.dataType){case Fn.ANIMATIONTYPE_FLOAT:{const e=h?this.floatInterpolateFunctionWithTangents(o,s.outTangent*c,l,a.inTangent*c,u):this.floatInterpolateFunction(o,l,u);switch(t.loopMode){case Fn.ANIMATIONLOOPMODE_CYCLE:case Fn.ANIMATIONLOOPMODE_CONSTANT:return e;case Fn.ANIMATIONLOOPMODE_RELATIVE:return t.offsetValue*t.repeatCount+e}break}case Fn.ANIMATIONTYPE_QUATERNION:{const e=h?this.quaternionInterpolateFunctionWithTangents(o,s.outTangent.scale(c),l,a.inTangent.scale(c),u):this.quaternionInterpolateFunction(o,l,u);switch(t.loopMode){case Fn.ANIMATIONLOOPMODE_CYCLE:case Fn.ANIMATIONLOOPMODE_CONSTANT:return e;case Fn.ANIMATIONLOOPMODE_RELATIVE:return e.addInPlace(t.offsetValue.scale(t.repeatCount))}return e}case Fn.ANIMATIONTYPE_VECTOR3:{const e=h?this.vector3InterpolateFunctionWithTangents(o,s.outTangent.scale(c),l,a.inTangent.scale(c),u):this.vector3InterpolateFunction(o,l,u);switch(t.loopMode){case Fn.ANIMATIONLOOPMODE_CYCLE:case Fn.ANIMATIONLOOPMODE_CONSTANT:return e;case Fn.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case Fn.ANIMATIONTYPE_VECTOR2:{const e=h?this.vector2InterpolateFunctionWithTangents(o,s.outTangent.scale(c),l,a.inTangent.scale(c),u):this.vector2InterpolateFunction(o,l,u);switch(t.loopMode){case Fn.ANIMATIONLOOPMODE_CYCLE:case Fn.ANIMATIONLOOPMODE_CONSTANT:return e;case Fn.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case Fn.ANIMATIONTYPE_SIZE:switch(t.loopMode){case Fn.ANIMATIONLOOPMODE_CYCLE:case Fn.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(o,l,u);case Fn.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(o,l,u).add(t.offsetValue.scale(t.repeatCount))}break;case Fn.ANIMATIONTYPE_COLOR3:{const e=h?this.color3InterpolateFunctionWithTangents(o,s.outTangent.scale(c),l,a.inTangent.scale(c),u):this.color3InterpolateFunction(o,l,u);switch(t.loopMode){case Fn.ANIMATIONLOOPMODE_CYCLE:case Fn.ANIMATIONLOOPMODE_CONSTANT:return e;case Fn.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case Fn.ANIMATIONTYPE_COLOR4:{const e=h?this.color4InterpolateFunctionWithTangents(o,s.outTangent.scale(c),l,a.inTangent.scale(c),u):this.color4InterpolateFunction(o,l,u);switch(t.loopMode){case Fn.ANIMATIONLOOPMODE_CYCLE:case Fn.ANIMATIONLOOPMODE_CONSTANT:return e;case Fn.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case Fn.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case Fn.ANIMATIONLOOPMODE_CYCLE:case Fn.ANIMATIONLOOPMODE_CONSTANT:return Fn.AllowMatricesInterpolation?this.matrixInterpolateFunction(o,l,u,t.workValue):o;case Fn.ANIMATIONLOOPMODE_RELATIVE:return o}}return 0}matrixInterpolateFunction(e,t,i,n){return Fn.AllowMatrixDecomposeForInterpolation?n?(Qe.DecomposeLerpToRef(e,t,i,n),n):Qe.DecomposeLerp(e,t,i):n?(Qe.LerpToRef(e,t,i,n),n):Qe.Lerp(e,t,i)}clone(){const e=new Fn(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 Fn.ANIMATIONTYPE_QUATERNION:if(r=qe.FromArray(t.values),t.values.length>=8){const e=qe.FromArray(t.values.slice(4,8));e.equals(qe.Zero())||(a=e)}if(t.values.length>=12){const e=qe.FromArray(t.values.slice(8,12));e.equals(qe.Zero())||(o=e)}t.values.length>=13&&(l=t.values[12]);break;case Fn.ANIMATIONTYPE_MATRIX:r=Qe.FromArray(t.values),t.values.length>=17&&(l=t.values[16]);break;case Fn.ANIMATIONTYPE_COLOR3:r=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 Fn.ANIMATIONTYPE_COLOR4:r=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 Fn.ANIMATIONTYPE_VECTOR3:default:r=Ye.FromArray(t.values),t.values[3]&&(a=Ye.FromArray(t.values[3])),t.values[4]&&(o=Ye.FromArray(t.values[4])),t.values[5]&&(l=t.values[5])}const h={};h.frame=t.frame,h.value=r,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(s=0;s{const r=new ee;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let t=JSON.parse(r.responseText);if(t.animations&&(t=t.animations),t.length){const e=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")})),r.open("GET",t),r.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const n=new ee;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),r=new Array;for(const t of n.animations){const i=this.Parse(t);i.snippetId=e,r.push(i)}t(r)}else{const n=JSON.parse(i.animation),r=this.Parse(n);r.snippetId=e,t(r)}}else i("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}Fn._UniqueIdGenerator=0,Fn.AllowMatricesInterpolation=!1,Fn.AllowMatrixDecomposeForInterpolation=!0,Fn.SnippetUrl="https://snippet.babylonjs.com",Fn.ANIMATIONTYPE_FLOAT=0,Fn.ANIMATIONTYPE_VECTOR3=1,Fn.ANIMATIONTYPE_QUATERNION=2,Fn.ANIMATIONTYPE_MATRIX=3,Fn.ANIMATIONTYPE_COLOR3=4,Fn.ANIMATIONTYPE_COLOR4=7,Fn.ANIMATIONTYPE_VECTOR2=5,Fn.ANIMATIONTYPE_SIZE=6,Fn.ANIMATIONLOOPMODE_RELATIVE=0,Fn.ANIMATIONLOOPMODE_CYCLE=1,Fn.ANIMATIONLOOPMODE_CONSTANT=2,Fn.CreateFromSnippetAsync=Fn.ParseFromSnippetAsync,Ie("BABYLON.Animation",Fn),Mi._AnimationRangeFactory=(e,t,i)=>new Nn(e,t,i);class Ln{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;const t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add((e=>{if(!e)return;e.computeWorldMatrix(!0);const t=e.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=.05*t,this.upperRadiusTransitionRange=.05*t})):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))}))}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return!!this._attachedCamera&&this._attachedCamera.radius===e&&!this._radiusIsAnimating}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(Ln.EasingFunction.setEasingMode(Ln.EasingMode),this._radiusBounceTransition=Fn.CreateAnimation("radius",Fn.ANIMATIONTYPE_FLOAT,60,Ln.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=Fn.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,(()=>this._clearAnimationLocks()));t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}}Ln.EasingFunction=new class extends yn{constructor(e=1){super(),this.amplitude=e}easeInCore(e){const t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}}(.3),Ln.EasingMode=yn.EASINGMODE_EASEOUT;class wn{constructor(){this.onTargetFramingAnimationEndObservable=new n,this._mode=wn.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();wn.EasingFunction.setEasingMode(wn.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==Wt.POINTERDOWN?e.type===Wt.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&this.zoomOnMesh(e,void 0,(()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()}))})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const n=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(n.minimumWorld,n.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const n=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(n.min,n.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const n=new Ye(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new Ye(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),n&&n(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),l&&this._animatables.push(l)}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=t.subtract(e).length(),n=this._getFrustumSlope(),r=.5*i*this._radiusScale,s=r*Math.sqrt(1+1/(n.x*n.x)),a=r*Math.sqrt(1+1/(n.y*n.y));let o=Math.max(s,a);const l=this._attachedCamera;return l?(l.lowerRadiusLimit&&this._mode===wn.IgnoreBoundsSizeMode&&(o=ol.upperRadiusLimit?l.upperRadiusLimit:o),o):0}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=H.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,i=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=Fn.CreateAnimation("beta",Fn.ANIMATIONTYPE_FLOAT,60,wn.EasingFunction));const e=Fn.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_getFrustumSlope(){const e=this._attachedCamera;if(!e)return He.Zero();const t=e.getScene().getEngine().getAspectRatio(e),i=Math.tan(e.fov/2);return new He(i*t,i)}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=H.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}wn.EasingFunction=new class extends yn{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}},wn.EasingMode=yn.EASINGMODE_EASEINOUT,wn.IgnoreBoundsSizeMode=0,wn.FitFrustumSidesMode=1;class Bn extends Fi{constructor(e,t,i,n=!0){super(e,t,i,n),this._tmpUpVector=Ye.Zero(),this._tmpTargetVector=Ye.Zero(),this.cameraDirection=new Ye(0,0,0),this.cameraRotation=new He(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new qe,this.rotation=new Ye(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=Ye.Zero(),this._initialFocalDistance=1,this._viewMatrix=Qe.Zero(),this._camMatrix=Qe.Zero(),this._cameraTransformMatrix=Qe.Zero(),this._cameraRotationMatrix=Qe.Zero(),this._referencePoint=new Ye(0,0,1),this._transformedReferencePoint=Ye.Zero(),this._defaultUp=Ye.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(){return this.lockedTarget?(this.lockedTarget.absolutePosition&&this.lockedTarget.computeWorldMatrix(),this.lockedTarget.absolutePosition||this.lockedTarget):null}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 Ye(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new Ye(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new qe(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+=ke),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),Qe.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&&qe.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(Ze.Matrix[0]),Ye.TransformNormalToRef(this.cameraDirection,Ze.Matrix[0],Ze.Vector3[0]),void this.position.addInPlace(Ze.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()&&qe.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]?p.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=!Fi.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=Et.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=Un[e];if(i){const n=t[e],r=Et.Parse((()=>new i),n,null);this.add(r)}}}else for(const t in this.attached){const i=Un[this.attached[t].getClassName()];if(i){const n=Et.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(n)}}}}class kn{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Pe.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let n=0,r=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=s=>{var a,o;const l=s.event,h="touch"===l.pointerType;if(t.isInVRExclusivePointerMode)return;if(s.type!==Wt.POINTERMOVE&&-1===this.buttons.indexOf(l.button))return;const c=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){const e=l.movementX,t=l.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(s.type!==Wt.POINTERDOWN&&h&&(null===(a=this._pointA)||void 0===a?void 0:a.pointerId)!==l.pointerId&&(null===(o=this._pointB)||void 0===o?void 0:o.pointerId)!==l.pointerId)return;if(s.type!==Wt.POINTERDOWN||-1!==this._currentActiveButton&&!h)if(s.type===Wt.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(s.type!==Wt.POINTERUP||this._currentActiveButton!==l.button&&!h){if(s.type===Wt.POINTERMOVE)if(e||l.preventDefault(),this._pointA&&null===this._pointB){const e=l.clientX-this._pointA.x,t=l.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=l.clientX,this._pointA.y=l.clientY}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;e.x=l.clientX,e.y=l.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,a=t*t+i*i,o={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:s.type};this.onMultiTouch(this._pointA,this._pointB,n,a,r,o),r=o,n=a}}else{try{null==c||c.releasePointerCapture(l.pointerId)}catch(e){}h||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==l.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==l.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==n||r)&&(this.onMultiTouch(this._pointA,this._pointB,n,0,r,null),n=0,r=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else{try{null==c||c.setPointerCapture(l.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType};else{if(null!==this._pointB)return;this._pointB={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType}}-1!==this._currentActiveButton||h||(this._currentActiveButton=l.button),this.onButtonDown(l),e||(l.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Wt.POINTERDOWN|Wt.POINTERUP|Wt.POINTERMOVE|Wt.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,n=0,r=null,this.onLostFocus()},this._contextMenuBind=this.onContextMenu.bind(this),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const s=this.camera.getScene().getEngine().getHostWindow();s&&Pe.RegisterTopRootEvents(s,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Pe.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,n,r,s){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}et([ct()],kn.prototype,"buttons",void 0);class Gn extends kn{constructor(){super(...arguments),this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.useNaturalPinchZoom=!1,this.pinchZoom=!0,this.panningSensibility=1e3,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this.pinchInwards=!0,this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}getClassName(){return"ArcRotateCameraPointersInput"}_computeMultiTouchPanning(e,t){if(0!==this.panningSensibility&&e&&t){const i=t.x-e.x,n=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=n/this.panningSensibility}}_computePinchZoom(e,t){const i=this.camera.radius||Gn.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=.001*(t-e)*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){0!==this.panningSensibility&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,n,r,s){0===i&&null===r||0===n&&null===s||(this.multiTouchPanAndZoom?(this._computePinchZoom(i,n),this._computeMultiTouchPanning(r,s)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(n)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,n),this._isPinching=!0):this._computeMultiTouchPanning(r,s)):this.multiTouchPanning?this._computeMultiTouchPanning(r,s):this.pinchZoom&&this._computePinchZoom(i,n))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}Gn.MinimumRadiusForPinch=.001,et([ct()],Gn.prototype,"buttons",void 0),et([ct()],Gn.prototype,"angularSensibilityX",void 0),et([ct()],Gn.prototype,"angularSensibilityY",void 0),et([ct()],Gn.prototype,"pinchPrecision",void 0),et([ct()],Gn.prototype,"pinchDeltaPercentage",void 0),et([ct()],Gn.prototype,"useNaturalPinchZoom",void 0),et([ct()],Gn.prototype,"pinchZoom",void 0),et([ct()],Gn.prototype,"panningSensibility",void 0),et([ct()],Gn.prototype,"multiTouchPanning",void 0),et([ct()],Gn.prototype,"multiTouchPanAndZoom",void 0),Un.ArcRotateCameraPointersInput=Gn;class zn{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=Pe.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===Qt.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t0?n/(1+this.wheelDeltaPercentage):n*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Pe.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Wt.POINTERWHEEL)return;const i=t.event;let n=0;const r=i.deltaMode===Jt.DOM_DELTA_LINE?40:1,s=-i.deltaY*r;if(this.customComputeDeltaFromMouseWheel)n=this.customComputeDeltaFromMouseWheel(s,this,i);else if(this.wheelDeltaPercentage){if(n=this._computeDeltaFromMouseWheelLegacyEvent(s,this.camera.radius),n>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+n;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=Be.Clamp(e,0,Number.MAX_VALUE),n=this._computeDeltaFromMouseWheelLegacyEvent(s,e)}}else n=s/(40*this.wheelPrecision);n&&(this.zoomToMouseLocation&&this._hitPlane?this._zoomToMouse(n):this.camera.inertialRadiusOffset+=n),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Wt.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;const e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){const e=this.camera,t=e.target.subtract(e.position);this._hitPlane=li.FromPositionAndNormal(e.target,t)}_getPosition(){var e;const t=this.camera,i=t.getScene(),n=i.createPickingRay(i.pointerX,i.pointerY,Qe.Identity(),t,!1);let r=0;return this._hitPlane&&(r=null!==(e=n.intersectsPlane(this._hitPlane))&&void 0!==e?e:0),n.origin.addInPlace(n.direction.scaleInPlace(r))}_zoomToMouse(e){var t,i;const n=this.camera,r=1-n.inertia;if(n.lowerRadiusLimit){const i=null!==(t=n.lowerRadiusLimit)&&void 0!==t?t:0;n.radius-(n.inertialRadiusOffset+e)/rt&&(e=(n.radius-t)*r-n.inertialRadiusOffset)}const s=e/r/n.radius,a=this._getPosition(),o=Ze.Vector3[6];a.subtractToRef(n.target,o),o.scaleInPlace(s),o.scaleInPlace(r),this._inertialPanning.addInPlace(o),n.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)()=>new Hn(e,0,0,1,Ye.Zero(),t)));class Hn extends Bn{constructor(e,t,i,r,s,a,o=!0){super(e,Ye.Zero(),a,o),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=Ye.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=He.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new Qe,this.panningAxis=new Ye(1,1,0),this._transformedDirection=new Ye,this.mapPanning=!1,this.onMeshTargetChangedObservable=new n,this.checkCollisions=!1,this.collisionRadius=new Ye(.5,.5,.5),this._previousPosition=Ye.Zero(),this._collisionVelocity=Ye.Zero(),this._newPosition=Ye.Zero(),this._computationVector=Ye.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);const n=Math.cos(this.alpha),r=Math.sin(this.alpha),s=Math.cos(this.beta);let a=Math.sin(this.beta);0===a&&(a=1e-4);const o=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*n*a,this.radius*s,this.radius*r*a),o.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=l.clone(),l=l.negate()),this._computeViewMatrix(this._position,o,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=Ye.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new Wn(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new Qe,this._upToYMatrix=new Qe,this._upVector=Ye.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){Qe.RotationAlignToRef(Ye.UpReadOnly,this._upVector,this._yToUpMatrix),Qe.RotationAlignToRef(this._upVector,Ye.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){const e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){const t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){const e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){const t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){const e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){const t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){const e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){const t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){const e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){const e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){const t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){const e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Ln,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return null!=this._framingBehavior}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new wn,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return null!=this._autoRotationBehavior}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new xn,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}_initCache(){super._initCache(),this._cache._target=new Ye(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=He.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){const e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}_isSynchronizedViewMatrix(){return!!super._isSynchronizedViewMatrix()&&this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset)}attachControl(e,t,i=!0,n=2){const r=arguments;t=Pe.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=i,this._panningMouseButton=n,"boolean"==typeof r[0]&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1;let t=this.inertialAlphaOffset;this.beta<=0&&(t*=-1),this.getScene().useRightHandedSystem&&(t*=-1),this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(t*=-1),this.alpha+=t*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||Ye.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,n=!1){var r;if(n=null!==(r=this.overrideCloneAlphaBetaRadius)&&void 0!==r?r:n,e.getBoundingInfo)this._targetBoundingCenter=t?e.getBoundingInfo().boundingBox.centerWorld.clone():null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const t=e,n=this._getTargetPosition();if(n&&!i&&n.equals(t))return;this._targetHost=null,this._target=t,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}n||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let n=Math.sin(this.beta);0===n&&(n=1e-4),0===this.radius&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*n,this.radius*i,this.radius*t*n),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||Ye.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&n<0&&(e=e.negate()),this._computeViewMatrix(this._position,r,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=gn.MinMax(e),n=Ye.Distance(i.min,i.max);this.radius=n*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:n},t)}focusOn(e,t=!1){let i,n;if(void 0===e.min){const t=e||this.getScene().meshes;i=gn.MinMax(t),n=Ye.Distance(i.min,i.max)}else i=e,n=e.distance;this._target=gn.Center(i),t||(this.maxZ=2*n)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case Fi.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Fi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Fi.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Fi.RIG_MODE_STEREOSCOPIC_INTERLACED:case Fi.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case Fi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const n=new Hn(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return n._cameraRigParams={},n.isRigCamera=!0,n.rigParent=this,n.upVector=this.upVector,n.mode=this.mode,n.orthoLeft=this.orthoLeft,n.orthoRight=this.orthoRight,n.orthoBottom=this.orthoBottom,n.orthoTop=this.orthoTop,n}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case Fi.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Fi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Fi.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Fi.RIG_MODE_STEREOSCOPIC_INTERLACED:case Fi.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case Fi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}et([ct()],Hn.prototype,"alpha",void 0),et([ct()],Hn.prototype,"beta",void 0),et([ct()],Hn.prototype,"radius",void 0),et([ct()],Hn.prototype,"overrideCloneAlphaBetaRadius",void 0),et([pt("target")],Hn.prototype,"_target",void 0),et([mt("targetHost")],Hn.prototype,"_targetHost",void 0),et([ct()],Hn.prototype,"inertialAlphaOffset",void 0),et([ct()],Hn.prototype,"inertialBetaOffset",void 0),et([ct()],Hn.prototype,"inertialRadiusOffset",void 0),et([ct()],Hn.prototype,"lowerAlphaLimit",void 0),et([ct()],Hn.prototype,"upperAlphaLimit",void 0),et([ct()],Hn.prototype,"lowerBetaLimit",void 0),et([ct()],Hn.prototype,"upperBetaLimit",void 0),et([ct()],Hn.prototype,"lowerRadiusLimit",void 0),et([ct()],Hn.prototype,"upperRadiusLimit",void 0),et([ct()],Hn.prototype,"inertialPanningX",void 0),et([ct()],Hn.prototype,"inertialPanningY",void 0),et([ct()],Hn.prototype,"pinchToPanMaxDistance",void 0),et([ct()],Hn.prototype,"panningDistanceLimit",void 0),et([pt()],Hn.prototype,"panningOriginTarget",void 0),et([ct()],Hn.prototype,"panningInertia",void 0),et([ct()],Hn.prototype,"zoomToMouseLocation",null),et([ct()],Hn.prototype,"zoomOnFactor",void 0),et([_t()],Hn.prototype,"targetScreenOffset",void 0),et([ct()],Hn.prototype,"allowUpsideDown",void 0),et([ct()],Hn.prototype,"useInputToRestoreState",void 0);class Yn{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,n,r){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 r=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==r.frameId&&(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=n.clone()}}}P.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#define ADDITIONAL_FRAGMENT_DECLARATION\n";P.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";P.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";P.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";P.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";P.IncludesShadersStore.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n";P.IncludesShadersStore.samplerFragmentDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\nuniform sampler2D _SAMPLERNAME_Sampler;\n#endif\n";P.IncludesShadersStore.fresnelFunction="#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif\n";P.IncludesShadersStore.bumpFragmentMainFunctions="#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\nvec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale)\n{\n#ifdef NORMALXYSCALE\nnormal=normalize(normal*vec3(scale,scale,1.0));\n#endif\nreturn normalize(cotangentFrame*normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale)\n{\nreturn perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);\n}\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams)\n{\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\ntangent*=tangentSpaceParams.x;\nbitangent*=tangentSpaceParams.y;\nfloat det=max(dot(tangent,tangent),dot(bitangent,bitangent));\nfloat invmax=det==0.0 ? 0.0 : inversesqrt(det);\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\n#endif\n";P.IncludesShadersStore.bumpFragmentFunctions="#if defined(BUMP)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)\n#endif\n#if defined(DETAIL)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)\n#endif\n#if defined(BUMP) && defined(PARALLAX)\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nbool keepWorking=true;\nfor (int i=0; icurrRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\nkeepWorking=false;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n";P.IncludesShadersStore.logDepthDeclaration="#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif\n";P.IncludesShadersStore.bumpFragment="vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#elif defined(BUMP)\nfloat normalScale=vBumpInfos.y;\n#else\nfloat normalScale=1.0;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#elif defined(BUMP)\nvec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);\n#else\nvec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.));\n#endif\n#elif defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nvec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;\nmat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.));\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef DETAIL\nvec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);\nvec2 detailNormalRG=detailColor.wy*2.0-1.0;\nfloat detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));\nvec3 detailNormal=vec3(detailNormalRG,detailNormalB);\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW);\n#elif !defined(DETAIL)\nnormalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);\n#else\nvec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;\n#if DETAIL_NORMALBLENDMETHOD==0 \ndetailNormal.xy*=vDetailInfos.z;\nvec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));\n#elif DETAIL_NORMALBLENDMETHOD==1 \ndetailNormal.xy*=vDetailInfos.z;\nbumpNormal+=vec3(0.0,0.0,1.0);\ndetailNormal*=vec3(-1.0,-1.0,1.0);\nvec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;\n#endif\nnormalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);\n#endif\n#elif defined(DETAIL)\ndetailNormal.xy*=vDetailInfos.z;\nnormalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);\n#endif\n";P.IncludesShadersStore.depthPrePass="#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif\n";P.IncludesShadersStore.logDepthFragment="#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif\n";P.IncludesShadersStore.oitFragment="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\nfloat fragDepth=gl_FragCoord.z; \n#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS\nuint halfFloat=packHalf2x16(vec2(fragDepth));\nvec2 full=unpackHalf2x16(halfFloat);\nfragDepth=full.x;\n#endif\nivec2 fragCoord=ivec2(gl_FragCoord.xy);\nvec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;\nvec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);\ndepth.rg=vec2(-MAX_DEPTH);\nfrontColor=lastFrontColor;\nbackColor=vec4(0.0);\n#ifdef USE_REVERSE_DEPTHBUFFER\nfloat furthestDepth=-lastDepth.x;\nfloat nearestDepth=lastDepth.y;\n#else\nfloat nearestDepth=-lastDepth.x;\nfloat furthestDepth=lastDepth.y;\n#endif\nfloat alphaMultiplier=1.0-lastFrontColor.a;\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepth>nearestDepth || fragDepthfurthestDepth) {\n#endif\nreturn;\n}\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepthfurthestDepth) {\n#else\nif (fragDepth>nearestDepth && fragDepth\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#include[SCENE_MRT_COUNT]\n#include\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#define RECIPROCAL_PI2 0.15915494\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include[1..7]\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular)\n#endif\n#include\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS)\nif (baseColor.a\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef DETAIL\nbaseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y);\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);\n#ifdef RGBDLIGHTMAP\nlightmapColor.rgb=fromRGBD(lightmapColor);\n#endif\nlightmapColor.rgb*=vLightmapInfos.y;\n#endif\n#include[0..maxSimultaneousLights]\nvec4 refractionColor=vec4(0.,0.,0.,1.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\n#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC\nrefractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition);\n#endif\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector);\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords);\n#endif\n#ifdef RGBDREFRACTION\nrefractionColor.rgb=fromRGBD(refractionColor);\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor.rgb=toGammaSpace(refractionColor.rgb);\n#endif\nrefractionColor.rgb*=vRefractionInfos.x;\n#endif\nvec4 reflectionColor=vec4(0.,0.,0.,1.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nvReflectionUVW.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias);\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW);\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords);\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor.rgb=toGammaSpace(reflectionColor.rgb);\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n#ifdef ALPHATEST\n#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS\nif (alpha\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\ncolor.a*=visibility;\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\n#ifdef PREPASS\nfloat writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;\ngl_FragData[0]=color; \n#ifdef PREPASS_POSITION\ngl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);\n#endif\n#ifdef PREPASS_VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\nvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\nvec2 velocity=abs(a-b);\nvelocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;\ngl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);\n#endif\n#ifdef PREPASS_IRRADIANCE\ngl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_DEPTH\ngl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4((view*vec4(normalW,0.0)).rgb,writeGeometryInfo); \n#endif\n#ifdef PREPASS_ALBEDO_SQRT\ngl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_REFLECTIVITY\n#if defined(SPECULARTERM)\n#if defined(SPECULAR)\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularMapColor)*writeGeometryInfo; \n#else\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularColor,1.0)*writeGeometryInfo;\n#endif\n#else\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo;\n#endif\n#endif\n#endif\n#if !defined(PREPASS) || defined(WEBGL2)\ngl_FragColor=color;\n#endif\n#include\n#if ORDER_INDEPENDENT_TRANSPARENCY\nif (fragDepth==nearestDepth) {\nfrontColor.rgb+=color.rgb*color.a*alphaMultiplier;\nfrontColor.a=1.0-alphaMultiplier*(1.0-color.a);\n} else {\nbackColor+=color;\n}\n#endif\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";P.IncludesShadersStore.defaultVertexDeclaration="uniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\nuniform mat4 detailMatrix;\n#endif\n#define ADDITIONAL_VERTEX_DECLARATION\n";P.IncludesShadersStore.uvAttributeDeclaration="#ifdef UV{X}\nattribute vec2 uv{X};\n#endif\n";P.IncludesShadersStore.prePassVertexDeclaration="#ifdef PREPASS\n#ifdef PREPASS_DEPTH\nvarying vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nuniform mat4 previousViewProjection;\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#endif\n";P.IncludesShadersStore.samplerVertexDeclaration="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n";P.IncludesShadersStore.bumpVertexDeclaration="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n";P.IncludesShadersStore.morphTargetsVertexGlobalDeclaration="#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#ifdef MORPHTARGETS_TEXTURE \nprecision mediump sampler2DArray; \nuniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];\nuniform vec3 morphTargetTextureInfo;\nuniform sampler2DArray morphTargets;\nvec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)\n{ \nfloat y=floor(vertexIndex/morphTargetTextureInfo.y);\nfloat x=vertexIndex-y*morphTargetTextureInfo.y;\nvec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);\nreturn texture(morphTargets,textureUV).xyz;\n}\n#endif\n#endif\n";P.IncludesShadersStore.morphTargetsVertexDeclaration="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#ifdef MORPHTARGETS_UV\nattribute vec2 uv_{X};\n#endif\n#endif\n#endif\n";P.IncludesShadersStore.morphTargetsVertexGlobal="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nfloat vertexID;\n#endif\n#endif\n";P.IncludesShadersStore.morphTargetsVertex="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE \nvertexID=float(gl_VertexID)*morphTargetTextureInfo.x;\npositionUpdated+=(readVector3FromRawSampler({X},vertexID)-position)*morphTargetInfluences[{X}];\nvertexID+=1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(readVector3FromRawSampler({X},vertexID) -normal)*morphTargetInfluences[{X}];\nvertexID+=1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated+=(readVector3FromRawSampler({X},vertexID).xy-uv)*morphTargetInfluences[{X}];\nvertexID+=1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(readVector3FromRawSampler({X},vertexID) -tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#else\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";P.IncludesShadersStore.prePassVertex="#ifdef PREPASS_DEPTH\nvViewPos=(view*worldPos).rgb;\n#endif\n#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*worldPos;\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;\npreviousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n";P.IncludesShadersStore.uvVariableDeclaration="#if !defined(UV{X}) && defined(MAINUV{X})\nvec2 uv{X}=vec2(0.,0.);\n#endif\n#ifdef MAINUV{X}\nvMainUV{X}=uv{X};\n#endif\n";P.IncludesShadersStore.samplerVertexImplementation="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nif (v_INFONAME_==0.)\n{\nv_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));\n}\n#ifdef UV2\nelse if (v_INFONAME_==1.)\n{\nv_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef UV3\nelse if (v_INFONAME_==2.)\n{\nv_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));\n}\n#endif\n#ifdef UV4\nelse if (v_INFONAME_==3.)\n{\nv_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));\n}\n#endif\n#ifdef UV5\nelse if (v_INFONAME_==4.)\n{\nv_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));\n}\n#endif\n#ifdef UV6\nelse if (v_INFONAME_==5.)\n{\nv_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));\n}\n#endif\n#endif\n";P.IncludesShadersStore.bumpVertex="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif\n";P.IncludesShadersStore.vertexColorMixing="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvColor=vec4(1.0);\n#ifdef VERTEXCOLOR\n#ifdef VERTEXALPHA\nvColor*=color;\n#else\nvColor.rgb*=color.rgb;\n#endif\n#endif\n#ifdef INSTANCESCOLOR\nvColor*=instanceColor;\n#endif\n#endif\n";P.IncludesShadersStore.pointCloudVertex="#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n";P.IncludesShadersStore.logDepthVertex="#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif\n";P.ShadersStore.defaultVertexShader="#include<__decl__defaultVertex>\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#include[2..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\n#include\n#include[1..7]\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)\n#endif\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));\nvNormalW=normalize(normalWorld*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\ngl_Position=viewProjection*worldPos;\n} else {\ngl_Position=viewProjectionR*worldPos;\n}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\nvPositionW=vec3(worldPos);\n#include\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\n#endif\n#include[2..7]\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)\n#endif\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";const Kn=new RegExp("^([gimus]+)!");class qn{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let t=0;te.priority-t.priority)),this._codeInjectionPoints={};const i={};i[qn._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 on.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 r=null===(n=this._codeInjectionPoints)||void 0===n?void 0:n[t];if(!r)return i;for(let e in r){let n="";for(const i of this._activePlugins){const r=i.getCustomCode(t);(null==r?void 0:r[e])&&(n+=r[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=Kn.exec(e);i&&i.length>=2&&(t=i[1],e=e.substring(t.length+1))}t.indexOf("g")<0&&(t+="g");const r=i,s=new RegExp(e,t);let a=s.exec(r);for(;null!==a;){let e=n;for(let t=0;te),this)}serialize(){return Et.Serialize(this)}parse(e,t,i){Et.Parse((()=>this),e,t,i)}}et([ct()],Qn.prototype,"name",void 0),et([ct()],Qn.prototype,"priority",void 0),et([ct()],Qn.prototype,"registerForExtraEvents",void 0);class jn extends Ct{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class Zn extends Qn{constructor(e,t=!0){super(e,"DetailMap",140,new jn,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=hn.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isReadyForSubMesh(e,t,i){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&En.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&&En.DetailTextureEnabled&&this._isEnabled?(sn.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&&En.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),sn.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&En.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"}]}}}et([ut("detailTexture"),ht("_markAllSubMeshesAsTexturesDirty")],Zn.prototype,"texture",void 0),et([ct()],Zn.prototype,"diffuseBlendLevel",void 0),et([ct()],Zn.prototype,"roughnessBlendLevel",void 0),et([ct()],Zn.prototype,"bumpLevel",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Zn.prototype,"normalBlendMethod",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Zn.prototype,"isEnabled",void 0);const Jn={effect:null,subMesh:null};class $n extends Ct{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 er extends vn{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 De(16),this._worldViewProjectionMatrix=Qe.Zero(),this._globalAmbientColor=new tt(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new Zn(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new Yn,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),er.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),er.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}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}get hasRenderTargetTextures(){return!!(er.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(er.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===hn.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==hn.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(on.GetDefineNames,this._eventInfo),t.materialDefines=new $n(this._eventInfo.defineNames));const n=this.getScene(),r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const s=n.getEngine();r._needNormals=sn.PrepareDefinesForLights(n,e,r,!0,this._maxSimultaneousLights,this._disableLighting),sn.PrepareDefinesForMultiview(n,r);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(sn.PrepareDefinesForPrePass(n,r,this.canRenderToMRT&&!a),sn.PrepareDefinesForOIT(n,r,a),r._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,r._needUVs=!1;for(let e=1;e<=6;++e)r["MAINUV"+e]=!1;if(n.texturesEnabled){if(r.DIFFUSEDIRECTUV=0,r.BUMPDIRECTUV=0,r.AMBIENTDIRECTUV=0,r.OPACITYDIRECTUV=0,r.EMISSIVEDIRECTUV=0,r.SPECULARDIRECTUV=0,r.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&er.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;sn.PrepareDefinesForMergedUV(this._diffuseTexture,r,"DIFFUSE")}else r.DIFFUSE=!1;if(this._ambientTexture&&er.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;sn.PrepareDefinesForMergedUV(this._ambientTexture,r,"AMBIENT")}else r.AMBIENT=!1;if(this._opacityTexture&&er.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;sn.PrepareDefinesForMergedUV(this._opacityTexture,r,"OPACITY"),r.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else r.OPACITY=!1;if(this._reflectionTexture&&er.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(r._needNormals=!0,r.REFLECTION=!0,r.ROUGHNESS=this._roughness>0,r.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,r.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===Si.INVCUBIC_MODE,r.REFLECTIONMAP_3D=this._reflectionTexture.isCube,r.REFLECTIONMAP_OPPOSITEZ=r.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,r.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case Si.EXPLICIT_MODE:r.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case Si.PLANAR_MODE:r.setReflectionMode("REFLECTIONMAP_PLANAR");break;case Si.PROJECTION_MODE:r.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case Si.SKYBOX_MODE:r.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case Si.SPHERICAL_MODE:r.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case Si.EQUIRECTANGULAR_MODE:r.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case Si.FIXED_EQUIRECTANGULAR_MODE:r.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case Si.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:r.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case Si.CUBIC_MODE:case Si.INVCUBIC_MODE:default:r.setReflectionMode("REFLECTIONMAP_CUBIC")}r.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else r.REFLECTION=!1,r.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&er.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;sn.PrepareDefinesForMergedUV(this._emissiveTexture,r,"EMISSIVE")}else r.EMISSIVE=!1;if(this._lightmapTexture&&er.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;sn.PrepareDefinesForMergedUV(this._lightmapTexture,r,"LIGHTMAP"),r.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,r.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else r.LIGHTMAP=!1;if(this._specularTexture&&er.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;sn.PrepareDefinesForMergedUV(this._specularTexture,r,"SPECULAR"),r.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else r.SPECULAR=!1;if(n.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&er.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;sn.PrepareDefinesForMergedUV(this._bumpTexture,r,"BUMP"),r.PARALLAX=this._useParallax,r.PARALLAXOCCLUSION=this._useParallaxOcclusion,r.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else r.BUMP=!1,r.PARALLAX=!1,r.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&er.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;r._needUVs=!0,r.REFRACTION=!0,r.REFRACTIONMAP_3D=this._refractionTexture.isCube,r.RGBDREFRACTION=this._refractionTexture.isRGBD,r.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else r.REFRACTION=!1;r.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else r.DIFFUSE=!1,r.AMBIENT=!1,r.OPACITY=!1,r.REFLECTION=!1,r.EMISSIVE=!1,r.LIGHTMAP=!1,r.BUMP=!1,r.REFRACTION=!1;r.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),r.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,r.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,r.SPECULAROVERALPHA=this._useSpecularOverAlpha,r.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,r.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,r.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r),r.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,r.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}r._areFresnelDirty&&(er.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(r.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,r.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,r.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,r.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,r.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,r.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,r._needNormals=!0,r.FRESNEL=!0):r.FRESNEL=!1),sn.PrepareDefinesForMisc(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,r),sn.PrepareDefinesForFrameBoundValues(n,s,this,r,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=r,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),sn.PrepareDefinesForAttributes(e,r,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let o=!1;if(r.isDirty){const i=r._areLightsDisposed;r.markAsProcessed();const a=new Tn;r.REFLECTION&&a.addFallback(0,"REFLECTION"),r.SPECULAR&&a.addFallback(0,"SPECULAR"),r.BUMP&&a.addFallback(0,"BUMP"),r.PARALLAX&&a.addFallback(1,"PARALLAX"),r.PARALLAXOCCLUSION&&a.addFallback(0,"PARALLAXOCCLUSION"),r.SPECULAROVERALPHA&&a.addFallback(0,"SPECULAROVERALPHA"),r.FOG&&a.addFallback(1,"FOG"),r.POINTSIZE&&a.addFallback(0,"POINTSIZE"),r.LOGARITHMICDEPTH&&a.addFallback(0,"LOGARITHMICDEPTH"),sn.HandleFallbacksForShadows(r,a,this._maxSimultaneousLights),r.SPECULARTERM&&a.addFallback(0,"SPECULARTERM"),r.DIFFUSEFRESNEL&&a.addFallback(1,"DIFFUSEFRESNEL"),r.OPACITYFRESNEL&&a.addFallback(2,"OPACITYFRESNEL"),r.REFLECTIONFRESNEL&&a.addFallback(3,"REFLECTIONFRESNEL"),r.EMISSIVEFRESNEL&&a.addFallback(4,"EMISSIVEFRESNEL"),r.FRESNEL&&a.addFallback(4,"FRESNEL"),r.MULTIVIEW&&a.addFallback(0,"MULTIVIEW");const l=[Lt.PositionKind];r.NORMAL&&l.push(Lt.NormalKind),r.TANGENT&&l.push(Lt.TangentKind);for(let e=1;e<=6;++e)r["UV"+e]&&l.push(`uv${1===e?"":e}`);r.VERTEXCOLOR&&l.push(Lt.ColorKind),sn.PrepareAttributesForBones(l,e,r,a),sn.PrepareAttributesForInstances(l,r),sn.PrepareAttributesForMorphTargets(l,e,r),sn.PrepareAttributesForBakedVertexAnimation(l,e,r);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"],u=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"];this._eventInfo.fallbacks=a,this._eventInfo.fallbackRank=0,this._eventInfo.defines=r,this._eventInfo.uniforms=c,this._eventInfo.attributes=l,this._eventInfo.samplers=u,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._callbackPluginEventGeneric(on.PrepareEffect,this._eventInfo),Yn.AddUniforms(c),Yn.AddSamplers(u),bt&&(bt.PrepareUniforms(c,r),bt.PrepareSamplers(u,r)),sn.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:r,maxSimultaneousLights:this._maxSimultaneousLights}),$i(c);const f={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,c,d,u,r,l,f));const _=r.toString(),p=t.effect;let m=n.getEngine().createEffect(h,{attributes:l,uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:_,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:r.NUM_MORPH_INFLUENCERS},processFinalCode:f.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:r.PREPASS},s);if(this._eventInfo.customCode=void 0,m)if(this._onEffectCreatedObservable&&(Jn.effect=m,Jn.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Jn)),this.allowShaderHotSwapping&&p&&!m.isReady()){if(m=p,r.markAsUnprocessed(),o=this.isFrozen,i)return r._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(m,r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!o,t.effect._wasPreviouslyUsingInstances=i,n.performancePriority!==di.BackwardCompatible&&(this.checkReadyOnlyOnce=!0),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 r=this.getScene(),s=i.materialDefines;if(!s)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,r,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=a._forceRebindOnNextCall||this._mustRebind(r,a,t.visibility);sn.BindBonesParameters(t,a);const l=this._uniformBuffer;if(o){if(this.bindViewProjection(a),!l.useUbo||!this.isFrozen||!l.isSync||a._forceRebindOnNextCall){if(er.FresnelEnabled&&s.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))),r.texturesEnabled){if(this._diffuseTexture&&er.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),sn.BindTextureMatrix(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&er.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),sn.BindTextureMatrix(this._ambientTexture,l,"ambient")),this._opacityTexture&&er.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),sn.BindTextureMatrix(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&er.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&&er.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),sn.BindTextureMatrix(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&er.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),sn.BindTextureMatrix(this._lightmapTexture,l,"lightmap")),this._specularTexture&&er.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),sn.BindTextureMatrix(this._specularTexture,l,"specular")),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&er.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),sn.BindTextureMatrix(this._bumpTexture,l,"bump"),r._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&&er.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),s.SPECULARTERM&&l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",er.EmissiveTextureEnabled?this.emissiveColor:tt.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),r.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}r.texturesEnabled&&(this._diffuseTexture&&er.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&er.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&er.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&er.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&er.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&er.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&er.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&er.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&er.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),tn(a,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!o&&this.isFrozen||(r.lightsEnabled&&!this._disableLighting&&sn.BindLights(r,t,a,s,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==mi.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||s.PREPASS)&&this.bindView(a),sn.BindFogParameters(r,t,a),s.NUM_MORPH_INFLUENCERS&&sn.BindMorphTargetParameters(t,a),s.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(n=t.bakedVertexAnimationManager)||void 0===n||n.bind(a,s.INSTANCES)),this.useLogarithmicDepth&&sn.BindLogDepth(s,a,r),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,r,s,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===(r=this._opacityTexture)||void 0===r||r.dispose(),null===(s=this._reflectionTexture)||void 0===s||s.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=Et.Clone((()=>new er(e,this.getScene())),this);return t.name=e,t.id=e,this.stencil.copyTo(t.stencil),t}static Parse(e,t,i){const n=Et.Parse((()=>new er(e.name,t)),e,t,i);return e.stencil&&n.stencil.parse(e.stencil,t,i),n}static get DiffuseTextureEnabled(){return En.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){En.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return En.DetailTextureEnabled}static set DetailTextureEnabled(e){En.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return En.AmbientTextureEnabled}static set AmbientTextureEnabled(e){En.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return En.OpacityTextureEnabled}static set OpacityTextureEnabled(e){En.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return En.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){En.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return En.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){En.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return En.SpecularTextureEnabled}static set SpecularTextureEnabled(e){En.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return En.BumpTextureEnabled}static set BumpTextureEnabled(e){En.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return En.LightmapTextureEnabled}static set LightmapTextureEnabled(e){En.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return En.RefractionTextureEnabled}static set RefractionTextureEnabled(e){En.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return En.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){En.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return En.FresnelEnabled}static set FresnelEnabled(e){En.FresnelEnabled=e}}et([ut("diffuseTexture")],er.prototype,"_diffuseTexture",void 0),et([ht("_markAllSubMeshesAsTexturesAndMiscDirty")],er.prototype,"diffuseTexture",void 0),et([ut("ambientTexture")],er.prototype,"_ambientTexture",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"ambientTexture",void 0),et([ut("opacityTexture")],er.prototype,"_opacityTexture",void 0),et([ht("_markAllSubMeshesAsTexturesAndMiscDirty")],er.prototype,"opacityTexture",void 0),et([ut("reflectionTexture")],er.prototype,"_reflectionTexture",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"reflectionTexture",void 0),et([ut("emissiveTexture")],er.prototype,"_emissiveTexture",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"emissiveTexture",void 0),et([ut("specularTexture")],er.prototype,"_specularTexture",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"specularTexture",void 0),et([ut("bumpTexture")],er.prototype,"_bumpTexture",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"bumpTexture",void 0),et([ut("lightmapTexture")],er.prototype,"_lightmapTexture",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"lightmapTexture",void 0),et([ut("refractionTexture")],er.prototype,"_refractionTexture",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"refractionTexture",void 0),et([dt("ambient")],er.prototype,"ambientColor",void 0),et([dt("diffuse")],er.prototype,"diffuseColor",void 0),et([dt("specular")],er.prototype,"specularColor",void 0),et([dt("emissive")],er.prototype,"emissiveColor",void 0),et([ct()],er.prototype,"specularPower",void 0),et([ct("useAlphaFromDiffuseTexture")],er.prototype,"_useAlphaFromDiffuseTexture",void 0),et([ht("_markAllSubMeshesAsTexturesAndMiscDirty")],er.prototype,"useAlphaFromDiffuseTexture",void 0),et([ct("useEmissiveAsIllumination")],er.prototype,"_useEmissiveAsIllumination",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"useEmissiveAsIllumination",void 0),et([ct("linkEmissiveWithDiffuse")],er.prototype,"_linkEmissiveWithDiffuse",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"linkEmissiveWithDiffuse",void 0),et([ct("useSpecularOverAlpha")],er.prototype,"_useSpecularOverAlpha",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"useSpecularOverAlpha",void 0),et([ct("useReflectionOverAlpha")],er.prototype,"_useReflectionOverAlpha",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"useReflectionOverAlpha",void 0),et([ct("disableLighting")],er.prototype,"_disableLighting",void 0),et([ht("_markAllSubMeshesAsLightsDirty")],er.prototype,"disableLighting",void 0),et([ct("useObjectSpaceNormalMap")],er.prototype,"_useObjectSpaceNormalMap",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"useObjectSpaceNormalMap",void 0),et([ct("useParallax")],er.prototype,"_useParallax",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"useParallax",void 0),et([ct("useParallaxOcclusion")],er.prototype,"_useParallaxOcclusion",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"useParallaxOcclusion",void 0),et([ct()],er.prototype,"parallaxScaleBias",void 0),et([ct("roughness")],er.prototype,"_roughness",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"roughness",void 0),et([ct()],er.prototype,"indexOfRefraction",void 0),et([ct()],er.prototype,"invertRefractionY",void 0),et([ct()],er.prototype,"alphaCutOff",void 0),et([ct("useLightmapAsShadowmap")],er.prototype,"_useLightmapAsShadowmap",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"useLightmapAsShadowmap",void 0),et([ft("diffuseFresnelParameters")],er.prototype,"_diffuseFresnelParameters",void 0),et([ht("_markAllSubMeshesAsFresnelDirty")],er.prototype,"diffuseFresnelParameters",void 0),et([ft("opacityFresnelParameters")],er.prototype,"_opacityFresnelParameters",void 0),et([ht("_markAllSubMeshesAsFresnelAndMiscDirty")],er.prototype,"opacityFresnelParameters",void 0),et([ft("reflectionFresnelParameters")],er.prototype,"_reflectionFresnelParameters",void 0),et([ht("_markAllSubMeshesAsFresnelDirty")],er.prototype,"reflectionFresnelParameters",void 0),et([ft("refractionFresnelParameters")],er.prototype,"_refractionFresnelParameters",void 0),et([ht("_markAllSubMeshesAsFresnelDirty")],er.prototype,"refractionFresnelParameters",void 0),et([ft("emissiveFresnelParameters")],er.prototype,"_emissiveFresnelParameters",void 0),et([ht("_markAllSubMeshesAsFresnelDirty")],er.prototype,"emissiveFresnelParameters",void 0),et([ct("useReflectionFresnelFromSpecular")],er.prototype,"_useReflectionFresnelFromSpecular",void 0),et([ht("_markAllSubMeshesAsFresnelDirty")],er.prototype,"useReflectionFresnelFromSpecular",void 0),et([ct("useGlossinessFromSpecularMapAlpha")],er.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"useGlossinessFromSpecularMapAlpha",void 0),et([ct("maxSimultaneousLights")],er.prototype,"_maxSimultaneousLights",void 0),et([ht("_markAllSubMeshesAsLightsDirty")],er.prototype,"maxSimultaneousLights",void 0),et([ct("invertNormalMapX")],er.prototype,"_invertNormalMapX",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"invertNormalMapX",void 0),et([ct("invertNormalMapY")],er.prototype,"_invertNormalMapY",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"invertNormalMapY",void 0),et([ct("twoSidedLighting")],er.prototype,"_twoSidedLighting",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],er.prototype,"twoSidedLighting",void 0),et([ct()],er.prototype,"useLogarithmicDepth",null),Ie("BABYLON.StandardMaterial",er),mi.DefaultMaterialFactory=e=>new er("default material",e);P.ShadersStore.postprocessVertexShader="attribute vec2 position;\nuniform vec2 scale;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class tr{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}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}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,r=14){var s;return null===(s=this._depthStencilTexture)||void 0===s||s.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:n,depthTextureFormat:r},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,r,a;let o=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!==s.Depth&&n!==s.DepthStencil||(t=!0,i--);const r=[],a=[];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 ir extends tr{constructor(e,t,i,n,r){super(e,t,i,n),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._context=r}_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 r=this._context,s=this._framebuffer,a=this._engine._currentFramebuffer;this._engine._bindUnboundFramebuffer(s);const o=r[this._engine.webGLVersion>1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],l=-1!==i?r.TEXTURE_CUBE_MAP_POSITIVE_X+i:r.TEXTURE_2D;r.framebufferTexture2D(r.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)}}K.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const n=new ir(e,t,i,this,this._gl);return this._renderTargetWrapperCache.push(n),n},K.prototype.createRenderTargetTexture=function(e,t){var i,n;const r=this._createHardwareRenderTargetWrapper(!1,!1,e);let a,o=!0,l=!1,h=!1,c=1;void 0!==t&&"object"==typeof t&&(o=null===(i=t.generateDepthBuffer)||void 0===i||i,l=!!t.generateStencilBuffer,h=!!t.noColorAttachment,a=t.colorAttachment,c=null!==(n=t.samples)&&void 0!==n?n:1);const u=a||(h?null:this._createInternalTexture(e,t,!0,s.RenderTarget)),d=e.width||e,f=e.height||e,_=this._currentFramebuffer,p=this._gl,m=p.createFramebuffer();return this._bindUnboundFramebuffer(m),r._depthStencilBuffer=this._setupFramebufferDepthAttachments(l,o,d,f),u&&!u.is2DArray&&p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,u._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(_),r._framebuffer=m,r._generateDepthBuffer=o,r._generateStencilBuffer=l,r.setTextures(u),this.updateRenderTargetTextureSampleCount(r,c),r},K.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)},K.prototype._createDepthStencilTexture=function(e,t,i){const n=this._gl,r=e.layers||0,a=0!==r?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D,l=new o(this,s.DepthStencil);if(!this._caps.depthTextureExtension)return p.Error("Depth texture is not supported by your browser or hardware."),l;const h={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t};if(this._bindTextureDirectly(a,l,!0),this._setupDepthStencilTexture(l,e,h.generateStencil,0!==h.comparisonFunction&&h.bilinearFiltering,h.comparisonFunction,h.samples),void 0!==h.depthTextureFormat){if(15!==h.depthTextureFormat&&16!==h.depthTextureFormat&&17!==h.depthTextureFormat&&13!==h.depthTextureFormat&&14!==h.depthTextureFormat&&18!==h.depthTextureFormat)return p.Error("Depth texture format is not supported."),l;l.format=h.depthTextureFormat}else l.format=h.generateStencil?13:16;const c=17===l.format||13===l.format||18===l.format;i._depthStencilTexture=l,i._depthStencilTextureWithStencil=c;let u=n.UNSIGNED_INT;15===l.format?u=n.UNSIGNED_SHORT:17===l.format||13===l.format?u=n.UNSIGNED_INT_24_8:14===l.format?u=n.FLOAT:18===l.format&&(u=n.FLOAT_32_UNSIGNED_INT_24_8_REV);const d=c?n.DEPTH_STENCIL:n.DEPTH_COMPONENT;let f=d;this.webGLVersion>1&&(15===l.format?f=n.DEPTH_COMPONENT16:16===l.format?f=n.DEPTH_COMPONENT24:17===l.format||13===l.format?f=n.DEPTH24_STENCIL8:14===l.format?f=n.DEPTH_COMPONENT32F:18===l.format&&(f=n.DEPTH32F_STENCIL8)),l.is2DArray?n.texImage3D(a,0,f,l.width,l.height,r,0,d,u,null):n.texImage2D(a,0,f,l.width,l.height,0,d,u,null),this._bindTextureDirectly(a,null),this._internalTexturesCache.push(l);const _=i;if(_._depthStencilBuffer){const e=this._currentFramebuffer;this._bindUnboundFramebuffer(_._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(_._depthStencilBuffer),_._depthStencilBuffer=null}return l},K.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&&i.renderbufferStorageMultisample){const r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const s=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBAMultiSampleBufferFormat(e.texture.type),i.COLOR_ATTACHMENT0,!1);if(!s)throw new Error("Unable to create multi sampled framebuffer");n._MSAARenderBuffer=s}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};class nr{constructor(e,t,i,r,s,a,o=1,l,h,c=null,u=0,d="postprocess",f,_=!1,p=5,m=S.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 De(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new He(1,1),this._texelSize=He.Zero(),this.onActivateObservable=new n,this.onSizeChangedObservable=new n,this.onApplyObservable=new n,this.onBeforeRenderObservable=new n,this.onAfterRenderObservable=new n,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=s,this.renderTargetSamplingMode=o||1,this._reusable=h||!1,this._textureType=u,this._textureFormat=p,this._shaderLanguage=m,this._samplers=r||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=d,this._parameters=i||[],this._parameters.push("scale"),this._indexParameters=f,this._drawWrapper=new X(this._engine),_||this.updateEffect(c)}static RegisterShaderCodeProcessing(e,t){t?nr._CustomShaderCodeProcessing[null!=e?e:""]=t:delete nr._CustomShaderCodeProcessing[null!=e?e:""]}static _GetShaderCodeProcessing(e){var t;return null!==(t=nr._CustomShaderCodeProcessing[e])&&void 0!==t?t:nr._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)}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 De(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,n,r,s,a,o){var l,h;const c=nr._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 r=null!==(h=null==i?void 0:i.slice())&&void 0!==h?h:[];r.push(...this._samplers),e=c.defineCustomBindings(this.name,e,n,r),t=n,i=r}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!=r?r:null,onError:null!=s?s: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 s=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=Et.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=nr.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=xe(e.customType);if(!n||!n._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return n._Parse(e,r,t,i)}static _Parse(e,t,i,n){return Et.Parse((()=>new nr(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)}}nr._CustomShaderCodeProcessing={},et([ct()],nr.prototype,"uniqueId",void 0),et([ct()],nr.prototype,"name",void 0),et([ct()],nr.prototype,"width",void 0),et([ct()],nr.prototype,"height",void 0),et([ct()],nr.prototype,"renderTargetSamplingMode",void 0),et([gt()],nr.prototype,"clearColor",void 0),et([ct()],nr.prototype,"autoClear",void 0),et([ct()],nr.prototype,"alphaMode",void 0),et([ct()],nr.prototype,"alphaConstants",void 0),et([ct()],nr.prototype,"enablePixelPerfectMode",void 0),et([ct()],nr.prototype,"forceFullscreenViewport",void 0),et([ct()],nr.prototype,"scaleMode",void 0),et([ct()],nr.prototype,"alwaysForcePOT",void 0),et([ct("samples")],nr.prototype,"_samples",void 0),et([ct()],nr.prototype,"adaptScaleToCurrentViewport",void 0),Ie("BABYLON.PostProcess",nr);P.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}",K.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 r=this._gl,a=new o(this,s.RenderTarget);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,a,!0);const l=this._getSamplingParameters(n.samplingMode,n.generateMipMaps);1!==n.type||this._caps.textureFloat||(n.type=0,p.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,l.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,l.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let t=0;t<6;t++)r.texImage2D(r.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 h=r.createFramebuffer();return this._bindUnboundFramebuffer(h),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(n.generateStencilBuffer,n.generateDepthBuffer,e,e),n.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=h,i._generateDepthBuffer=n.generateDepthBuffer,i._generateStencilBuffer=n.generateStencilBuffer,a.width=e,a.height=e,a.isReady=!0,a.isCube=!0,a.samples=1,a.generateMipMaps=n.generateMipMaps,a.samplingMode=n.samplingMode,a.type=n.type,a.format=n.format,this._internalTexturesCache.push(a),i.setTextures(a),i};const rr={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class sr{constructor(e,t=rr){var i,n;this._fullscreenViewport=new Ti(0,0,1,1);const r=null!==(i=t.positions)&&void 0!==i?i:rr.positions,s=null!==(n=t.indices)&&void 0!==n?n:rr.indices;this.engine=e,this._vertexBuffers={[Lt.PositionKind]:new Lt(e,r,Lt.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(s);for(const e in this._vertexBuffers)this._vertexBuffers[e]._rebuild()}))}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}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 ar{constructor(e){let t;this.onApplyObservable=new n;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 r=e.defines?e.defines.join("\n"):"";this._drawWrapper=new X(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,r,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new O(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,r,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()})))}get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const or="passPixelShader",lr="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}";P.ShadersStore[or]=lr;const hr=or,cr=lr;class ur{static _CreateDumpRenderer(){if(!ur._DumpToolsEngine){const e=document.createElement("canvas"),t=new K(e,!1,{preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1});t.getCaps().parallelShaderCompile=void 0;const i=new sr(t),n=new ar({engine:t,name:hr,fragmentShader:cr,samplerNames:["textureSampler"]});ur._DumpToolsEngine={canvas:e,engine:t,renderer:i,wrapper:n}}return ur._DumpToolsEngine}static async DumpFramebuffer(e,t,i,n,r="image/png",s){const a=await i.readPixels(0,0,e,t),o=new Uint8Array(a.buffer);ur.DumpData(e,t,o,n,r,s,!0)}static DumpDataAsync(e,t,i,n="image/png",r,s=!1,a=!1,o){return new Promise((l=>{ur.DumpData(e,t,i,(e=>l(e)),n,r,s,a,o)}))}static DumpData(e,t,i,n,r="image/png",s,a=!1,o=!1,l){const h=ur._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?Pe.ToBlob(h.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;n&&n(t)},t.readAsArrayBuffer(e)}),r,l):Pe.EncodeScreenshotCanvasData(h.canvas,n,r,s,l),c.dispose()}static Dispose(){ur._DumpToolsEngine&&(ur._DumpToolsEngine.wrapper.dispose(),ur._DumpToolsEngine.renderer.dispose(),ur._DumpToolsEngine.engine.dispose()),ur._DumpToolsEngine=null}}Pe.DumpData=ur.DumpData,Pe.DumpDataAsync=ur.DumpDataAsync,Pe.DumpFramebuffer=ur.DumpFramebuffer;class dr extends Si{constructor(e,t,i,r=!1,s=!0,a=0,o=!1,l=Si.TRILINEAR_SAMPLINGMODE,h=!0,c=!1,u=!1,d=5,f=!1,_,p,m=!1,g=!1){var v,E,T,C,R,A;let b;if("object"==typeof r){const e=r;r=!!e.generateMipMaps,s=null===(v=e.doNotChangeAspectRatio)||void 0===v||v,a=null!==(E=e.type)&&void 0!==E?E:0,o=!!e.isCube,l=null!==(T=e.samplingMode)&&void 0!==T?T:Si.TRILINEAR_SAMPLINGMODE,h=null===(C=e.generateDepthBuffer)||void 0===C||C,c=!!e.generateStencilBuffer,u=!!e.isMulti,d=null!==(R=e.format)&&void 0!==R?R:5,f=!!e.delayAllocation,_=e.samples,p=e.creationFlags,m=!!e.noColorAttachment,g=!!e.useSRGBBuffer,b=e.colorAttachment}if(super(null,i,!r,void 0,l,void 0,void 0,void 0,void 0,d),this._unObserveRenderList=null,this._renderListHasChanged=(e,t)=>{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 n,this.onAfterUnbindObservable=new n,this.onBeforeRenderObservable=new n,this.onAfterRenderObservable=new n,this.onClearObservable=new n,this.onResizeObservable=new n,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=Ye.Zero(),!(i=this.getScene()))return;const S=this.getScene().getEngine();this._coordinatesMode=Si.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=S.onResizeObservable.add((()=>{})),this._generateMipMaps=!!r,this._doNotChangeAspectRatio=s,this._renderingManager=new Gt(i),this._renderingManager._useSceneAutoClearSetup=!0,u||(this._renderTargetOptions={generateMipMaps:r,type:a,format:null!==(A=this._format)&&void 0!==A?A:void 0,samplingMode:this.samplingMode,generateDepthBuffer:h,generateStencilBuffer:c,samples:_,creationFlags:p,noColorAttachment:m,useSRGBBuffer:g,colorAttachment:b},this.samplingMode===Si.NEAREST_SAMPLINGMODE&&(this.wrapU=Si.CLAMP_ADDRESSMODE,this.wrapV=Si.CLAMP_ADDRESSMODE),f||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=Si.INVCUBIC_MODE,this._textureMatrix=Qe.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==_&&(this.samples=_)))}get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=Xe(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;e0&&(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 r=this.getScene();if(!r)return i;const s=r.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(let e=0;e1||this.activeCamera&&this.activeCamera!==r.activeCamera)&&r.setTransformMatrix(r.activeCamera.getViewMatrix(),r.activeCamera.getProjectionMatrix(!0)),s.setViewport(r.activeCamera.viewport)),r.resetCachedMaterial(),h}_bestReflectionRenderTargetDimension(e,t){const i=e*t,n=Z.NearestPOT(i+16384/(128+i));return Math.min(Z.FloorPOT(e),n)}_prepareRenderingManager(e,t,i,n){const r=this.getScene();if(!r)return;this._renderingManager.reset();const s=r.getRenderId();for(let a=0;a=0&&this._renderingManager.dispatchParticles(i)}}_bindFrameBuffer(e=0,t=0){const i=this.getScene();if(!i)return;const n=i.getEngine();this._renderTarget&&n.bindFramebuffer(this._renderTarget,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,t)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindFramebuffer(this._renderTarget,this.isCube,(()=>{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,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,r=null){var s,a,o,l,h,c;const u=this.getScene();if(!u)return;const d=u.getEngine();if(null===(s=d._debugPushGroup)||void 0===s||s.call(d,`render to face #${e} layer #${n}`,1),this._prepareFrame(u,e,n,t),this.is2DArray?(d.currentRenderPassId=this._renderPassIds[n],this.onBeforeRenderObservable.notifyObservers(n)):(d.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),d.snapshotRendering&&1===d.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||u.clearColor,!0,!0,!0);else{let s=null;const c=this.renderList?this.renderList:u.getActiveMeshes().data,f=this.renderList?this.renderList.length:u.getActiveMeshes().length;this.getCustomRenderList&&(s=this.getCustomRenderList(this.is2DArray?n:e,c,f)),s?this._prepareRenderingManager(s,s.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(c,f,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),s=c);for(const t of u._beforeRenderTargetClearStage)t.action(this,e,n);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||u.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||u.updateTransformMatrix(!0);for(const t of u._beforeRenderTargetDrawStage)t.action(this,e,n);this._renderingManager.render(this.customRenderFunction,s,this.renderParticles,this.renderSprites);for(const t of u._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&&u.postProcessManager._finalizeFrame(!1,null!==(h=this._renderTarget)&&void 0!==h?h:void 0,e);for(const t of u._afterRenderTargetPostProcessStage)t.action(this,e,n);this._texture&&(this._texture.generateMipMaps=_),this._doNotChangeAspectRatio||u.updateTransformMatrix(!0),i&&ur.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),d)}this._unbindFrameBuffer(d,e),this._texture&&this.isCube&&5===e&&d.generateMipMapsForCubemap(this._texture),null===(c=d._debugPopGroup)||void 0===c||c.call(d,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 dr(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===dr.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=dr.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}dr.REFRESHRATE_RENDER_ONCE=0,dr.REFRESHRATE_RENDER_ONEVERYFRAME=1,dr.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,Si._CreateRenderTargetTexture=(e,t,i,n,r)=>new dr(e,t,i,n);P.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 fr extends nr{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,n,r,s,a=0,o=!1){super(e,"pass",null,null,t,i,n,r,s,void 0,a,void 0,null,o)}static _Parse(e,t,i,n){return Et.Parse((()=>new fr(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,n)}}let _r,pr;function mr(e){_r||(_r=new Float32Array(1),pr=new Int32Array(_r.buffer)),_r[0]=e;const t=pr[0];let i=t>>16&32768,n=t>>12&2047;const r=t>>23&255;return r<103?i:r>142?(i|=31744,i|=(255==r?0:1)&&8388607&t,i):r<113?(n|=2048,i|=(n>>114-r)+(n>>113-r&1),i):(i|=r-112<<10|n>>1,i+=1&n,i)}function gr(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))}Ie("BABYLON.PassPostProcess",fr),Z._RescalePostProcessFactory=e=>new fr("rescale",1,null,2,e,!1,0);class vr{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),n=i.getCaps(),r=t.isReady;let s=!1;n.textureHalfFloatRender&&n.textureHalfFloatLinearFiltering?(s=!0,t.type=2):n.textureFloatRender&&n.textureFloatLinearFiltering&&(s=!0,t.type=1),s&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const a=()=>{if(s){const n=new nr("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);n.externalTextureSamplerBinding=!0;const r=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],r,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),n&&n.dispose(),r._swapAndDie(t),t.isReady=!0}))}};r?a():e.onLoadObservable.addOnce(a)}static EncodeTextureToRGBD(e,t,i=0){return function(e,t,i,n,r,s){const a=t.getEngine();return t.isReady=!1,r=null!=r?r:t.samplingMode,n=null!=n?n:t.type,s=null!=s?s:t.format,-1===n&&(n=0),new Promise((o=>{const l=new nr("postprocess",e,null,null,1,null,r,a,!1,void 0,n,void 0,null,!1,s);l.externalTextureSamplerBinding=!0;const h=a.createRenderTargetTexture({width:t.width,height:t.height},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:r,type:n,format:s});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)}}let Er=0;const Tr=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const n=Si.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+Er++,e,!0,!1,Si.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const r=e.getEngine().getLoadedTexturesCache(),s=r.indexOf(n.getInternalTexture());-1!==s&&r.splice(s,1),n.isRGBD=!0,n.wrapU=Si.CLAMP_ADDRESSMODE,n.wrapV=Si.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=n,e.useDelayedTextureLoading=t,vr.ExpandRGBDTexture(n);const a=e.getEngine().onContextRestoredObservable.add((()=>{n.isRGBD=!0;const e=()=>{n.isReady()?vr.ExpandRGBDTexture(n):Pe.SetImmediate(e)};e()}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(a)}))}return e.environmentBRDFTexture};class Cr extends Ct{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1}}class Rr extends Qn{constructor(e,t=!0){super(e,"PBRBRDF",90,new Cr,t),this._useEnergyConservation=Rr.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=Rr.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=Rr.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=Rr.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=Rr.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=Rr.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=Rr.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=Rr.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation}getClassName(){return"PBRBRDFConfiguration"}}Rr.DEFAULT_USE_ENERGY_CONSERVATION=!0,Rr.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,Rr.DEFAULT_USE_SPHERICAL_HARMONICS=!0,Rr.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,et([ct(),ht("_markAllSubMeshesAsMiscDirty")],Rr.prototype,"useEnergyConservation",void 0),et([ct(),ht("_markAllSubMeshesAsMiscDirty")],Rr.prototype,"useSmithVisibilityHeightCorrelated",void 0),et([ct(),ht("_markAllSubMeshesAsMiscDirty")],Rr.prototype,"useSphericalHarmonics",void 0),et([ct(),ht("_markAllSubMeshesAsMiscDirty")],Rr.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);const Ar=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],br=[()=>1,e=>e.y,e=>e.z,e=>e.x,e=>e.x*e.y,e=>e.y*e.z,e=>3*e.z*e.z-1,e=>e.x*e.z,e=>e.x*e.x-e.y*e.y],Sr=(e,t)=>Ar[e]*br[e](t),Ir=[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 xr{constructor(){this.preScaled=!1,this.l00=Ye.Zero(),this.l1_1=Ye.Zero(),this.l10=Ye.Zero(),this.l11=Ye.Zero(),this.l2_2=Ye.Zero(),this.l2_1=Ye.Zero(),this.l20=Ye.Zero(),this.l21=Ye.Zero(),this.l22=Ye.Zero()}addLight(e,t,i){Ze.Vector3[0].set(t.r,t.g,t.b);const n=Ze.Vector3[0],r=Ze.Vector3[1];n.scaleToRef(i,r),r.scaleToRef(Sr(0,e),Ze.Vector3[2]),this.l00.addInPlace(Ze.Vector3[2]),r.scaleToRef(Sr(1,e),Ze.Vector3[2]),this.l1_1.addInPlace(Ze.Vector3[2]),r.scaleToRef(Sr(2,e),Ze.Vector3[2]),this.l10.addInPlace(Ze.Vector3[2]),r.scaleToRef(Sr(3,e),Ze.Vector3[2]),this.l11.addInPlace(Ze.Vector3[2]),r.scaleToRef(Sr(4,e),Ze.Vector3[2]),this.l2_2.addInPlace(Ze.Vector3[2]),r.scaleToRef(Sr(5,e),Ze.Vector3[2]),this.l2_1.addInPlace(Ze.Vector3[2]),r.scaleToRef(Sr(6,e),Ze.Vector3[2]),this.l20.addInPlace(Ze.Vector3[2]),r.scaleToRef(Sr(7,e),Ze.Vector3[2]),this.l21.addInPlace(Ze.Vector3[2]),r.scaleToRef(Sr(8,e),Ze.Vector3[2]),this.l22.addInPlace(Ze.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(Ir[0]),this.l1_1.scaleInPlace(Ir[1]),this.l10.scaleInPlace(Ir[2]),this.l11.scaleInPlace(Ir[3]),this.l2_2.scaleInPlace(Ir[4]),this.l2_1.scaleInPlace(Ir[5]),this.l20.scaleInPlace(Ir[6]),this.l21.scaleInPlace(Ir[7]),this.l22.scaleInPlace(Ir[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(Ar[0]),this.l1_1.scaleInPlace(Ar[1]),this.l10.scaleInPlace(Ar[2]),this.l11.scaleInPlace(Ar[3]),this.l2_2.scaleInPlace(Ar[4]),this.l2_1.scaleInPlace(Ar[5]),this.l20.scaleInPlace(Ar[6]),this.l21.scaleInPlace(Ar[7]),this.l22.scaleInPlace(Ar[8])}updateFromArray(e){return Ye.FromArrayToRef(e[0],0,this.l00),Ye.FromArrayToRef(e[1],0,this.l1_1),Ye.FromArrayToRef(e[2],0,this.l10),Ye.FromArrayToRef(e[3],0,this.l11),Ye.FromArrayToRef(e[4],0,this.l2_2),Ye.FromArrayToRef(e[5],0,this.l2_1),Ye.FromArrayToRef(e[6],0,this.l20),Ye.FromArrayToRef(e[7],0,this.l21),Ye.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return Ye.FromFloatsToRef(e[0],e[1],e[2],this.l00),Ye.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),Ye.FromFloatsToRef(e[6],e[7],e[8],this.l10),Ye.FromFloatsToRef(e[9],e[10],e[11],this.l11),Ye.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),Ye.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),Ye.FromFloatsToRef(e[18],e[19],e[20],this.l20),Ye.FromFloatsToRef(e[21],e[22],e[23],this.l21),Ye.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new xr).updateFromArray(e)}static FromPolynomial(e){const t=new xr;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 yr{constructor(){this.x=Ye.Zero(),this.y=Ye.Zero(),this.z=Ye.Zero(),this.xx=Ye.Zero(),this.yy=Ye.Zero(),this.zz=Ye.Zero(),this.xy=Ye.Zero(),this.yz=Ye.Zero(),this.zx=Ye.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=xr.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){Ze.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=Ze.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),Ze.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),Ze.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(Ze.Vector3[0]).addInPlace(Ze.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(Ze.Vector3[0]).subtractInPlace(Ze.Vector3[1]),this.zz.copyFrom(e.l00),Ze.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(Ze.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 yr).updateFromHarmonics(e)}static FromArray(e){const t=new yr;return Ye.FromArrayToRef(e[0],0,t.x),Ye.FromArrayToRef(e[1],0,t.y),Ye.FromArrayToRef(e[2],0,t.z),Ye.FromArrayToRef(e[3],0,t.xx),Ye.FromArrayToRef(e[4],0,t.yy),Ye.FromArrayToRef(e[5],0,t.zz),Ye.FromArrayToRef(e[6],0,t.yz),Ye.FromArrayToRef(e[7],0,t.zx),Ye.FromArrayToRef(e[8],0,t.xy),t}}class Mr{constructor(e,t,i,n){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=n}}class Pr{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),r=e.readPixels(1,void 0,void 0,!1);let s,a;e.isRenderTarget?(s=e.readPixels(3,void 0,void 0,!1),a=e.readPixels(2,void 0,void 0,!1)):(s=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([r,n,s,a,o,l]).then((([t,n,r,s,a,o])=>{const l={size:i,right:n,left:t,up:r,down:s,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 xr;let i=0;const n=2/e.size,r=n,s=.5*n,a=s-1;for(let o=0;o<6;o++){const l=this._FileFaces[o],h=e[l.name];let c=a;const u=5===e.format?4:3;for(let o=0;o{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))),null}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});P.IncludesShadersStore.pbrFragmentDeclaration="uniform vec4 vEyePosition;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec4 vMetallicReflectanceFactors;\nuniform vec3 vEmissiveColor;\nuniform float visibility;\nuniform vec3 vAmbientColor;\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REALTIME_FILTERING\nuniform vec2 vReflectionFilteringInfo;\n#endif\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;\nuniform vec3 vRefractionSize; \n#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;\nuniform vec4 vClearCoatRefractionParams;\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;\nuniform vec2 vClearCoatTangentSpaceParams;\nuniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;\nuniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;\nuniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#endif\n#ifdef IRIDESCENCE\nuniform vec4 vIridescenceParams;\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;\nuniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\nuniform vec4 vSheenColor;\n#ifdef SHEEN_ROUGHNESS\nuniform float vSheenRoughness;\n#endif\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionMicrosurfaceInfos;\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\n#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;\nuniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;\nuniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;\nuniform mat4 translucencyIntensityMatrix;\n#endif\nuniform vec2 vThicknessParam;\nuniform vec3 vDiffusionDistance;\nuniform vec4 vTintColor;\nuniform vec3 vSubSurfaceIntensity;\n#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\n#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;\nuniform vec3 vSphericalL1_1;\nuniform vec3 vSphericalL10;\nuniform vec3 vSphericalL11;\nuniform vec3 vSphericalL2_2;\nuniform vec3 vSphericalL2_1;\nuniform vec3 vSphericalL20;\nuniform vec3 vSphericalL21;\nuniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\n#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";P.IncludesShadersStore.pbrUboDeclaration="layout(std140,column_major) uniform;\nuniform Material {\nvec2 vAlbedoInfos;\nvec4 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec3 vReflectivityInfos;\nvec2 vMicroSurfaceSamplerInfos;\nvec2 vReflectionInfos;\nvec2 vReflectionFilteringInfo;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec3 vBumpInfos;\nmat4 albedoMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 reflectivityMatrix;\nmat4 microSurfaceSamplerMatrix;\nmat4 bumpMatrix;\nvec2 vTangentSpaceParams;\nmat4 reflectionMatrix;\nvec3 vReflectionColor;\nvec4 vAlbedoColor;\nvec4 vLightingIntensity;\nvec3 vReflectionMicrosurfaceInfos;\nfloat pointSize;\nvec4 vReflectivityColor;\nvec3 vEmissiveColor;\nvec3 vAmbientColor;\nvec2 vDebugMode;\nvec4 vMetallicReflectanceFactors;\nvec2 vMetallicReflectanceInfos;\nmat4 metallicReflectanceMatrix;\nvec2 vReflectanceInfos;\nmat4 reflectanceMatrix;\nvec3 vSphericalL00;\nvec3 vSphericalL1_1;\nvec3 vSphericalL10;\nvec3 vSphericalL11;\nvec3 vSphericalL2_2;\nvec3 vSphericalL2_1;\nvec3 vSphericalL20;\nvec3 vSphericalL21;\nvec3 vSphericalL22;\nvec3 vSphericalX;\nvec3 vSphericalY;\nvec3 vSphericalZ;\nvec3 vSphericalXX_ZZ;\nvec3 vSphericalYY_ZZ;\nvec3 vSphericalZZ;\nvec3 vSphericalXY;\nvec3 vSphericalYZ;\nvec3 vSphericalZX;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";P.IncludesShadersStore.pbrFragmentExtraDeclaration="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include[1..7]\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n";P.IncludesShadersStore.samplerFragmentAlternateDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n#endif\n";P.IncludesShadersStore.pbrFragmentSamplersDeclaration="#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL)\nuniform sampler2D sheenRoughnessSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;\nuniform sampler2D reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D refractionSamplerLow;\nuniform sampler2D refractionSamplerHigh;\n#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#endif\n";P.IncludesShadersStore.subSurfaceScatteringFunctions="bool testLightingForSSS(float diffusionProfile)\n{\nreturn diffusionProfile<1.;\n}";P.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}";P.IncludesShadersStore.pbrHelperFunctions="#define RECIPROCAL_PI2 0.15915494\n#define RECIPROCAL_PI 0.31830988618\n#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{\nreturn square(roughness)+MINIMUMVARIANCE;\n}\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=saturate(reflectance0*25.0);\nreturn reflectance90;\n}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);\nvec3 nDfdy=dFdy(normalVector.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\nfloat geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\ngeometricAlphaGFactor*=0.75;\nreturn vec2(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {\nfloat alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);\nfloat alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);\nreturn vec2(alphaT,alphaB);\n}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy) {\nvec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;\nvec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);\nvec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);\nvec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));\nreturn anisotropicNormal;\n}\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {\nreturn exp(-alpha*distance);\n}\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {\nreturn cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));\n}\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {\nreturn -log(color)/distance;\n}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {\nvec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);\nreturn clearCoatAbsorption;\n}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n#endif\n";P.IncludesShadersStore.harmonicsFunctions="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nvec3 computeEnvironmentIrradiance(vec3 normal) {\nreturn vSphericalL00\n+ vSphericalL1_1*(normal.y)\n+ vSphericalL10*(normal.z)\n+ vSphericalL11*(normal.x)\n+ vSphericalL2_2*(normal.y*normal.x)\n+ vSphericalL2_1*(normal.y*normal.z)\n+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+ vSphericalL21*(normal.z*normal.x)\n+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));\n}\n#else\nvec3 computeEnvironmentIrradiance(vec3 normal) {\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz *Nz+C1;\nvec3 t2=a2 *Ny+t1;\nvec3 t3=b3 *Nx+t2;\nreturn t3;\n}\n#endif\n#endif\n";P.IncludesShadersStore.pbrDirectLightingSetupFunctions="struct preLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat lightDistance;\nfloat attenuation;\nvec3 L;\nvec3 H;\nfloat NdotV;\nfloat NdotLUnclamped;\nfloat NdotL;\nfloat VdotH;\nfloat roughness;\n#ifdef IRIDESCENCE\nfloat iridescenceIntensity;\n#endif\n};\npreLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nresult.lightDistance=sqrt(result.lightDistanceSquared);\nresult.L=normalize(result.lightOffset);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\nresult.NdotLUnclamped=dot(N,result.L);\nresult.NdotL=saturateEps(result.NdotLUnclamped);\nreturn result;\n}\npreLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\nresult.lightDistance=length(-lightData.xyz);\nresult.L=normalize(-lightData.xyz);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\nresult.NdotLUnclamped=dot(N,result.L);\nresult.NdotL=saturateEps(result.NdotLUnclamped);\nreturn result;\n}\npreLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\nresult.NdotL=dot(N,lightData.xyz)*0.5+0.5;\nresult.NdotL=saturateEps(result.NdotL);\nresult.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;\n}";P.IncludesShadersStore.pbrDirectLightingFalloffFunctions="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/maxEps(lightDistanceSquared);\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nfloat lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=saturate(1.0-factor*factor);\nattenuation*=attenuation;\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=saturate(cd*lightAngleScale+lightAngleOffset);\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}";P.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 (iridescenceIOR0&&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,r;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===(r=this._tintTexture)||void 0===r||r.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"}]}}}Dr._DefaultIndexOfRefraction=1.5,et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"isEnabled",void 0),et([ct()],Dr.prototype,"intensity",void 0),et([ct()],Dr.prototype,"roughness",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"indexOfRefraction",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"texture",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"useRoughnessFromMainTexture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"textureRoughness",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"remapF0OnInterfaceChange",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"bumpTexture",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"isTintEnabled",void 0),et([dt()],Dr.prototype,"tintColor",void 0),et([ct()],Dr.prototype,"tintColorAtDistance",void 0),et([ct()],Dr.prototype,"tintThickness",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Dr.prototype,"tintTexture",void 0);class Nr extends Ct{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 Fr extends Qn{constructor(e,t=!0){super(e,"PBRIridescence",110,new Nr,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=Fr._DefaultMinimumThickness,this.maximumThickness=Fr._DefaultMaximumThickness,this.indexOfRefraction=Fr._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&En.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&En.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&&En.IridescenceTextureEnabled?sn.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&En.IridescenceTextureEnabled?sn.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 r,s,a,o,l,h,c,u;if(!this._isEnabled)return;const d=n.materialDefines,f=this._material.isFrozen,_=d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;e.useUbo&&f&&e.isSync||(_&&En.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),sn.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&En.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",null!==(s=null===(r=this._texture)||void 0===r?void 0:r.coordinatesIndex)&&void 0!==s?s: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!==(u=null===(c=this._thicknessTexture)||void 0===c?void 0:c.level)&&void 0!==u?u:0),this._texture&&sn.BindTextureMatrix(this._texture,e,"iridescence"),!this._thicknessTexture||_||d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE||sn.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&En.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!_&&!d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&En.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"}]}}}Fr._DefaultMinimumThickness=100,Fr._DefaultMaximumThickness=400,Fr._DefaultIndexOfRefraction=1.3,et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Fr.prototype,"isEnabled",void 0),et([ct()],Fr.prototype,"intensity",void 0),et([ct()],Fr.prototype,"minimumThickness",void 0),et([ct()],Fr.prototype,"maximumThickness",void 0),et([ct()],Fr.prototype,"indexOfRefraction",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Fr.prototype,"texture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Fr.prototype,"thicknessTexture",void 0);class Lr extends Ct{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.MAINUV1=!1}}class wr extends Qn{constructor(e,t=!0){super(e,"PBRAnisotropic",110,new Lr,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new He(1,0),this._texture=null,this.texture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&En.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&&En.AnisotropicTextureEnabled?sn.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&&En.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),sn.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&En.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"}]}}}et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],wr.prototype,"isEnabled",void 0),et([ct()],wr.prototype,"intensity",void 0),et([_t()],wr.prototype,"direction",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],wr.prototype,"texture",void 0);class Br extends Ct{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 Ur extends Qn{constructor(e,t=!0){super(e,"Sheen",120,new Br,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]}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&En.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&En.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&&En.SheenTextureEnabled?(sn.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&En.SheenTextureEnabled?sn.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 r,s,a,o,l,h,c,u;if(!this._isEnabled)return;const d=n.materialDefines,f=this._material.isFrozen,_=d.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;e.useUbo&&f&&e.isSync||(_&&En.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),sn.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&En.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",null!==(s=null===(r=this._texture)||void 0===r?void 0:r.coordinatesIndex)&&void 0!==s?s: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!==(u=null===(c=this._textureRoughness)||void 0===c?void 0:c.level)&&void 0!==u?u:0),this._texture&&sn.BindTextureMatrix(this._texture,e,"sheen"),!this._textureRoughness||_||d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE||sn.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&&En.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!_&&!d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&En.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"}]}}}et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"isEnabled",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"linkSheenWithAlbedo",void 0),et([ct()],Ur.prototype,"intensity",void 0),et([dt()],Ur.prototype,"color",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"texture",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"useRoughnessFromMainTexture",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"roughness",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"textureRoughness",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Ur.prototype,"albedoScaling",void 0);class Vr extends Ct{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 kr extends Qn{constructor(e,t=!0){super(e,"PBRSubSurface",130,new Vr,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]}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()}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&En.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&En.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,r=(i||!this._refractionIntensityTexture)&&(n||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&En.ThicknessTextureEnabled&&sn.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&En.RefractionIntensityTextureEnabled&&!r&&sn.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&En.TranslucencyIntensityTextureEnabled&&!r&&sn.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)&&r,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&r,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&r,this._isRefractionEnabled&&t.texturesEnabled){const i=this._getRefractionTexture(t);i&&En.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(Ze.Vector3[0]);const r=Math.max(Math.abs(Ze.Vector3[0].x),Math.abs(Ze.Vector3[0].y),Math.abs(Ze.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*r,(this.maximumThickness-this.minimumThickness)*r)}bindForSubMesh(e,t,i,n){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const r=n.materialDefines,s=this._material.isFrozen,a=this._material.realTimeFiltering,o=r.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!s||!e.isSync){if(this._thicknessTexture&&En.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),sn.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&En.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),sn.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&En.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),sn.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&En.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,Be.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&&En.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&En.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&En.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),l&&En.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){En.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!(En.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"}]}}}et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"isRefractionEnabled",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"isTranslucencyEnabled",void 0),et([ct(),ht("_markScenePrePassDirty")],kr.prototype,"isScatteringEnabled",void 0),et([ct()],kr.prototype,"_scatteringDiffusionProfileIndex",void 0),et([ct()],kr.prototype,"refractionIntensity",void 0),et([ct()],kr.prototype,"translucencyIntensity",void 0),et([ct()],kr.prototype,"useAlbedoToTintRefraction",void 0),et([ct()],kr.prototype,"useAlbedoToTintTranslucency",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"thicknessTexture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"refractionTexture",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"indexOfRefraction",void 0),et([ct()],kr.prototype,"_volumeIndexOfRefraction",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"volumeIndexOfRefraction",null),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"invertRefractionY",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"linkRefractionWithTransparency",void 0),et([ct()],kr.prototype,"minimumThickness",void 0),et([ct()],kr.prototype,"maximumThickness",void 0),et([ct()],kr.prototype,"useThicknessAsDepth",void 0),et([dt()],kr.prototype,"tintColor",void 0),et([ct()],kr.prototype,"tintColorAtDistance",void 0),et([dt()],kr.prototype,"diffusionDistance",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useMaskFromThicknessTexture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"refractionIntensityTexture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"translucencyIntensityTexture",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useGltfStyleTextures",void 0);const Gr={effect:null,subMesh:null};class zr extends Ct{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 Xr extends vn{constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new Ke(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Xr.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=Xr.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 De(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 Rr(this),this.clearCoat=new Dr(this),this.iridescence=new Fr(this),this.anisotropy=new wr(this),this.sheen=new Ur(this),this.subSurface=new kr(this),this.detailMap=new Zn(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),En.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=Tr(this.getScene()),this.prePassConfiguration=new Yn}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()}))))}get hasRenderTargetTextures(){return!!(En.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===Xr.PBRMATERIAL_OPAQUE||this._transparencyMode===Xr.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===Xr.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Xr.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(on.GetDefineNames,this._eventInfo),t.materialDefines=new zr(this._eventInfo.defineNames));const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=this.getScene(),s=r.getEngine();if(n._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,r.texturesEnabled)){if(this._albedoTexture&&En.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&En.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&En.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&En.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture&&!e.irradianceTexture.isReadyOrNotBlocking())return!1}if(this._lightmapTexture&&En.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&En.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(En.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(s.getCaps().standardDerivatives&&this._bumpTexture&&En.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&En.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;s.getCaps().standardDerivatives||e.isVerticesDataPresent(Lt.NormalKind)||(e.createNormals(!0),p.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&&(Gr.effect=l,Gr.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Gr)),this.allowShaderHotSwapping&&a&&!l.isReady()){if(l=a,n.markAsUnprocessed(),h=this.isFrozen,o)return n._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(l,n,this._materialContext);return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!h,t.effect._wasPreviouslyUsingInstances=!!i,r.performancePriority!==di.BackwardCompatible&&(this.checkReadyOnlyOnce=!0),0))}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,i=null,n=null,r=null,s=null,a){if(this._prepareDefines(e,t,r,s,a),!t.isDirty)return null;t.markAsProcessed();const o=this.getScene().getEngine(),l=new Tn;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=sn.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),sn.PrepareAttributesForBones(c,e,t,l),sn.PrepareAttributesForInstances(c,t),sn.PrepareAttributesForMorphTargets(c,e,t),sn.PrepareAttributesForBakedVertexAnimation(c,e,t);let u="pbr";const d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],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=d,this._eventInfo.attributes=c,this._eventInfo.samplers=f,this._eventInfo.uniformBuffersNames=_,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._callbackPluginEventGeneric(on.PrepareEffect,this._eventInfo),Yn.AddUniforms(d),Yn.AddSamplers(f),$i(d),bt&&(bt.PrepareUniforms(d,t),bt.PrepareSamplers(f,t)),sn.PrepareUniformsAndSamplersList({uniformsNames:d,uniformBuffersNames:_,samplers:f,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const p={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,d,_,f,t,c,p));const m=t.toString(),g=o.createEffect(u,{attributes:c,uniformsNames:d,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,r=!1){var s;const a=this.getScene(),o=a.getEngine();sn.PrepareDefinesForLights(a,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,sn.PrepareDefinesForMultiview(a,t);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(sn.PrepareDefinesForPrePass(a,t,this.canRenderToMRT&&!l),sn.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&&En.DiffuseTextureEnabled?(sn.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&En.AmbientTextureEnabled?(sn.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&En.OpacityTextureEnabled?(sn.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&En.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,e.coordinatesMode===Si.INVCUBIC_MODE&&(t.INVERTCUBICMAP=!0),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 Si.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case Si.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case Si.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case Si.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case Si.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case Si.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Si.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Si.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Si.CUBIC_MODE:case Si.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==Si.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&&En.LightmapTextureEnabled?(sn.PrepareDefinesForMergedUV(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&En.EmissiveTextureEnabled?(sn.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,En.SpecularTextureEnabled){if(this._metallicTexture?(sn.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?(sn.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===(s=this._reflectanceTexture)||void 0===s?void 0:s._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!e,this._metallicReflectanceTexture?(sn.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)?(sn.PrepareDefinesForMergedUV(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?sn.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;o.getCaps().standardDerivatives&&this._bumpTexture&&En.BumpTextureEnabled&&!this._disableBumpMap?(sn.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&En.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&&En.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===Xr.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Xr.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&&(sn.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),sn.PrepareDefinesForFrameBoundValues(a,o,this,t,!!i,n,r),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),sn.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==Xr.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const n={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(on.GetDefineNames,this._eventInfo);const r=new zr(this._eventInfo.defineNames),s=this._prepareEffect(e,r,void 0,void 0,n.useInstances,n.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(Gr.effect=s,Gr.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Gr)),s.isReady()?t&&t(this):s.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,r,s,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 u=h._forceRebindOnNextCall||this._mustRebind(o,h,t.visibility);sn.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let d=null;const f=this._uniformBuffer;if(u){if(this.bindViewProjection(h),d=this._getReflectionTexture(),!f.useUbo||!this.isFrozen||!f.isSync||h._forceRebindOnNextCall){if(o.texturesEnabled){if(this._albedoTexture&&En.DiffuseTextureEnabled&&(f.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),sn.BindTextureMatrix(this._albedoTexture,f,"albedo")),this._ambientTexture&&En.AmbientTextureEnabled&&(f.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),sn.BindTextureMatrix(this._ambientTexture,f,"ambient")),this._opacityTexture&&En.OpacityTextureEnabled&&(f.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),sn.BindTextureMatrix(this._opacityTexture,f,"opacity")),d&&En.ReflectionTextureEnabled){if(f.updateMatrix("reflectionMatrix",d.getReflectionTextureMatrix()),f.updateFloat2("vReflectionInfos",d.level,0),d.boundingBoxSize){const e=d;f.updateVector3("vReflectionPosition",e.boundingBoxPosition),f.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=d.getSize().width;f.updateFloat2("vReflectionFilteringInfo",e,Be.Log2(e))}if(!l.USEIRRADIANCEMAP){const e=d.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",d.getSize().width,d.lodGenerationScale,d.lodGenerationOffset)}this._emissiveTexture&&En.EmissiveTextureEnabled&&(f.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),sn.BindTextureMatrix(this._emissiveTexture,f,"emissive")),this._lightmapTexture&&En.LightmapTextureEnabled&&(f.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),sn.BindTextureMatrix(this._lightmapTexture,f,"lightmap")),En.SpecularTextureEnabled&&(this._metallicTexture?(f.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),sn.BindTextureMatrix(this._metallicTexture,f,"reflectivity")):this._reflectivityTexture&&(f.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),sn.BindTextureMatrix(this._reflectivityTexture,f,"reflectivity")),this._metallicReflectanceTexture&&(f.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),sn.BindTextureMatrix(this._metallicReflectanceTexture,f,"metallicReflectance")),this._reflectanceTexture&&l.REFLECTANCE&&(f.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),sn.BindTextureMatrix(this._reflectanceTexture,f,"reflectance")),this._microSurfaceTexture&&(f.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),sn.BindTextureMatrix(this._microSurfaceTexture,f,"microSurfaceSampler"))),this._bumpTexture&&c.getCaps().standardDerivatives&&En.BumpTextureEnabled&&!this._disableBumpMap&&(f.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),sn.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!==(r=null===(n=this.subSurface)||void 0===n?void 0:n._indexOfRefraction)&&void 0!==r?r:1.5,t=1,i=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(i*this._metallicF0Factor,nt.Color3[0]);const s=this._metallicF0Factor;f.updateColor4("vMetallicReflectanceFactors",nt.Color3[0],s)}else f.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);f.updateColor3("vEmissiveColor",En.EmissiveTextureEnabled?this._emissiveColor:tt.BlackReadOnly),f.updateColor3("vReflectionColor",this._reflectionColor),!l.SS_REFRACTION&&(null===(s=this.subSurface)||void 0===s?void 0:s._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&&En.DiffuseTextureEnabled&&f.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&En.AmbientTextureEnabled&&f.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&En.OpacityTextureEnabled&&f.setTexture("opacitySampler",this._opacityTexture),d&&En.ReflectionTextureEnabled&&(l.LODBASEDMICROSFURACE?f.setTexture("reflectionSampler",d):(f.setTexture("reflectionSampler",d._lodTextureMid||d),f.setTexture("reflectionSamplerLow",d._lodTextureLow||d),f.setTexture("reflectionSamplerHigh",d._lodTextureHigh||d)),l.USEIRRADIANCEMAP&&f.setTexture("irradianceSampler",d.irradianceTexture)),l.ENVIRONMENTBRDF&&f.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&En.EmissiveTextureEnabled&&f.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&En.LightmapTextureEnabled&&f.setTexture("lightmapSampler",this._lightmapTexture),En.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&&En.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),tn(this._activeEffect,this,o),this.bindEyePosition(h)}else o.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!u&&this.isFrozen||(o.lightsEnabled&&!this._disableLighting&&sn.BindLights(o,t,this._activeEffect,l,this._maxSimultaneousLights),(o.fogEnabled&&t.applyFog&&o.fogMode!==mi.FOGMODE_NONE||d||t.receiveShadows||l.PREPASS)&&this.bindView(h),sn.BindFogParameters(o,t,this._activeEffect,!0),l.NUM_MORPH_INFLUENCERS&&sn.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),sn.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,r,s,a,o,l,h,c,u,d,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===(r=this._opacityTexture)||void 0===r||r.dispose(),null===(s=this._reflectionTexture)||void 0===s||s.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===(u=this._metallicReflectanceTexture)||void 0===u||u.dispose(),null===(d=this._reflectanceTexture)||void 0===d||d.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)}}Xr.PBRMATERIAL_OPAQUE=hn.MATERIAL_OPAQUE,Xr.PBRMATERIAL_ALPHATEST=hn.MATERIAL_ALPHATEST,Xr.PBRMATERIAL_ALPHABLEND=hn.MATERIAL_ALPHABLEND,Xr.PBRMATERIAL_ALPHATESTANDBLEND=hn.MATERIAL_ALPHATESTANDBLEND,Xr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,Xr.LIGHTFALLOFF_PHYSICAL=0,Xr.LIGHTFALLOFF_GLTF=1,Xr.LIGHTFALLOFF_STANDARD=2,et([vt()],Xr.prototype,"_imageProcessingConfiguration",void 0),et([ht("_markAllSubMeshesAsMiscDirty")],Xr.prototype,"debugMode",void 0),et([ct()],Xr.prototype,"useLogarithmicDepth",null);class Wr extends Xr{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=Wr.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=Tr(this.getScene())}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===Xr.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Xr.LIGHTFALLOFF_PHYSICAL:Xr.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Xr.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Xr.LIGHTFALLOFF_GLTF:Xr.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}getClassName(){return"PBRMaterial"}clone(e){const t=Et.Clone((()=>new Wr(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),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=Et.Parse((()=>new Wr(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}}Wr.PBRMATERIAL_OPAQUE=Xr.PBRMATERIAL_OPAQUE,Wr.PBRMATERIAL_ALPHATEST=Xr.PBRMATERIAL_ALPHATEST,Wr.PBRMATERIAL_ALPHABLEND=Xr.PBRMATERIAL_ALPHABLEND,Wr.PBRMATERIAL_ALPHATESTANDBLEND=Xr.PBRMATERIAL_ALPHATESTANDBLEND,Wr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Xr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"directIntensity",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"emissiveIntensity",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"environmentIntensity",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"specularIntensity",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"disableBumpMap",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"albedoTexture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"ambientTexture",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"ambientTextureStrength",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesAndMiscDirty")],Wr.prototype,"opacityTexture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"reflectionTexture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"emissiveTexture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"reflectivityTexture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"metallicTexture",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"metallic",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"roughness",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"metallicF0Factor",void 0),et([dt(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"metallicReflectanceColor",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"metallicReflectanceTexture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"reflectanceTexture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"microSurfaceTexture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"bumpTexture",void 0),et([ut(),ht("_markAllSubMeshesAsTexturesDirty",null)],Wr.prototype,"lightmapTexture",void 0),et([dt("ambient"),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"ambientColor",void 0),et([dt("albedo"),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"albedoColor",void 0),et([dt("reflectivity"),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"reflectivityColor",void 0),et([dt("reflection"),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"reflectionColor",void 0),et([dt("emissive"),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"emissiveColor",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"microSurface",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useLightmapAsShadowmap",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesAndMiscDirty")],Wr.prototype,"useAlphaFromAlbedoTexture",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesAndMiscDirty")],Wr.prototype,"forceAlphaTest",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesAndMiscDirty")],Wr.prototype,"alphaCutOff",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useSpecularOverAlpha",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useRoughnessFromMetallicTextureGreen",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useMetallnessFromMetallicTextureBlue",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useAmbientInGrayScale",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),et([ct()],Wr.prototype,"usePhysicalLightFalloff",null),et([ct()],Wr.prototype,"useGLTFLightFalloff",null),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useRadianceOverAlpha",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useObjectSpaceNormalMap",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useParallax",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useParallaxOcclusion",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"parallaxScaleBias",void 0),et([ct(),ht("_markAllSubMeshesAsLightsDirty")],Wr.prototype,"disableLighting",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"forceIrradianceInFragment",void 0),et([ct(),ht("_markAllSubMeshesAsLightsDirty")],Wr.prototype,"maxSimultaneousLights",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"invertNormalMapX",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"invertNormalMapY",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"twoSidedLighting",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useAlphaFresnel",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useLinearAlphaFresnel",void 0),et([ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"environmentBRDFTexture",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"forceNormalForward",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"enableSpecularAntiAliasing",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useHorizonOcclusion",void 0),et([ct(),ht("_markAllSubMeshesAsTexturesDirty")],Wr.prototype,"useRadianceOcclusion",void 0),et([ct(),ht("_markAllSubMeshesAsMiscDirty")],Wr.prototype,"unlit",void 0),Ie("BABYLON.PBRMaterial",Wr);class Hr extends Mi{constructor(e,t){super(e,t),this.diffuse=new tt(1,1,1),this.specular=new tt(1,1,1),this.falloffType=Hr.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=Hr.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 Nt(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=new Array,this.excludedMeshes=new Array,this._resyncMeshes()}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())}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,n,r=!0){var s;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&&r){const e=null!==(s=this.getShadowGenerator(t.activeCamera))&&void 0!==s?s: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=Hr.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const n=Et.Clone(i,this);return e&&(n.name=e),t&&(n.parent=t),n.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(n),n}serialize(){const e=Et.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)}))),Et.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return Mi.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){const i=Hr.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const n=Et.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 r=i.apply(e,[t,n]);for(const e of r)e._resyncLightSource(this);return r};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 r=i.apply(e,[t,n]);return this._resyncMeshes(),r},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===Hr.INTENSITYMODE_AUTOMATIC&&(i=t===Hr.LIGHTTYPEID_DIRECTIONALLIGHT?Hr.INTENSITYMODE_ILLUMINANCE:Hr.INTENSITYMODE_LUMINOUSINTENSITY),t){case Hr.LIGHTTYPEID_POINTLIGHT:case Hr.LIGHTTYPEID_SPOTLIGHT:switch(i){case Hr.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Hr.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Hr.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case Hr.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Hr.INTENSITYMODE_ILLUMINANCE:e=1;break;case Hr.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001),e=2*Math.PI*(1-Math.cos(t));break}}break;case Hr.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Hr.FALLOFF_DEFAULT=ui.FALLOFF_DEFAULT,Hr.FALLOFF_PHYSICAL=ui.FALLOFF_PHYSICAL,Hr.FALLOFF_GLTF=ui.FALLOFF_GLTF,Hr.FALLOFF_STANDARD=ui.FALLOFF_STANDARD,Hr.LIGHTMAP_DEFAULT=ui.LIGHTMAP_DEFAULT,Hr.LIGHTMAP_SPECULAR=ui.LIGHTMAP_SPECULAR,Hr.LIGHTMAP_SHADOWSONLY=ui.LIGHTMAP_SHADOWSONLY,Hr.INTENSITYMODE_AUTOMATIC=ui.INTENSITYMODE_AUTOMATIC,Hr.INTENSITYMODE_LUMINOUSPOWER=ui.INTENSITYMODE_LUMINOUSPOWER,Hr.INTENSITYMODE_LUMINOUSINTENSITY=ui.INTENSITYMODE_LUMINOUSINTENSITY,Hr.INTENSITYMODE_ILLUMINANCE=ui.INTENSITYMODE_ILLUMINANCE,Hr.INTENSITYMODE_LUMINANCE=ui.INTENSITYMODE_LUMINANCE,Hr.LIGHTTYPEID_POINTLIGHT=ui.LIGHTTYPEID_POINTLIGHT,Hr.LIGHTTYPEID_DIRECTIONALLIGHT=ui.LIGHTTYPEID_DIRECTIONALLIGHT,Hr.LIGHTTYPEID_SPOTLIGHT=ui.LIGHTTYPEID_SPOTLIGHT,Hr.LIGHTTYPEID_HEMISPHERICLIGHT=ui.LIGHTTYPEID_HEMISPHERICLIGHT,et([dt()],Hr.prototype,"diffuse",void 0),et([dt()],Hr.prototype,"specular",void 0),et([ct()],Hr.prototype,"falloffType",void 0),et([ct()],Hr.prototype,"intensity",void 0),et([ct()],Hr.prototype,"range",null),et([ct()],Hr.prototype,"intensityMode",null),et([ct()],Hr.prototype,"radius",null),et([ct()],Hr.prototype,"_renderPriority",void 0),et([ht("_reorderLightsInScene")],Hr.prototype,"renderPriority",void 0),et([ct("shadowEnabled")],Hr.prototype,"_shadowEnabled",void 0),et([ct("excludeWithLayerMask")],Hr.prototype,"_excludeWithLayerMask",void 0),et([ct("includeOnlyWithLayerMask")],Hr.prototype,"_includeOnlyWithLayerMask",void 0),et([ct("lightmapMode")],Hr.prototype,"_lightmapMode",void 0),Mi.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new Yr(e,Ye.Zero(),t)));class Yr extends Hr{constructor(e,t,i){super(e,i),this.groundColor=new tt(0,0,0),this.direction=t||Ye.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=Ye.Normalize(e.subtract(Ye.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=Ye.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=Ye.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=Qe.Identity()),this._worldMatrix}getTypeID(){return Hr.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}et([dt()],Yr.prototype,"groundColor",void 0),et([pt()],Yr.prototype,"direction",void 0);P.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";P.IncludesShadersStore.packingFunctions="vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\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}";P.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";P.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";P.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}";P.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";P.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 Kr extends nr{constructor(e,t,i,n,r,s=Si.BILINEAR_SAMPLINGMODE,a,o,l=0,h="",c=!1,u=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],n,r,s,a,o,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,u),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}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"}updateEffect(e=null,t=null,i=null,n,r,s){this._updateParameters(r,s)}_updateParameters(e,t){const i=this._kernel,n=(i-1)/2;let r=[],s=[],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 Et.Parse((()=>new Kr(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,n)}}et([ct("kernel")],Kr.prototype,"_kernel",void 0),et([ct("packedFloat")],Kr.prototype,"_packedFloat",void 0),et([_t()],Kr.prototype,"direction",void 0),Ie("BABYLON.BlurPostProcess",Kr);class qr extends dr{constructor(e,t,i,n,r=0,s=Si.BILINEAR_SAMPLINGMODE,a=!0){if(super(e,t,i,n,!0,r,!1,s,a),this.mirrorPlane=new li(0,1,0,1),this._transformMatrix=Qe.Zero(),this._mirrorMatrix=Qe.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateGammaSpace()}));const o=i.getEngine();let l;o.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add((()=>{var t;null===(t=o._debugPushGroup)||void 0===t||t.call(o,`mirror generation for ${e}`,1)})),this.onAfterUnbindObservable.add((()=>{var e;null===(e=o._debugPopGroup)||void 0===e||e.call(o,1)})),this.onBeforeRenderObservable.add((()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),Qe.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),l=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=Ye.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)})),this.onAfterRenderObservable.add((()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=l}))}set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){const e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){const e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){const e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new Kr("horizontal blur",new He(1,0),this._blurKernelX,this._blurRatio,null,Si.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new Kr("vertical blur",new He(0,1),this._blurKernelY,this._blurRatio,null,Si.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new qr(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var e;super.dispose();const t=this.getScene();t&&t.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),null===(e=this._sceneUBO)||void 0===e||e.dispose()}}Si._CreateMirror=(e,t,i,n)=>new qr(e,t,i,n),K.prototype._createDepthStencilCubeTexture=function(e,t,i){const n=new o(this,s.DepthStencil);if(n.isCube=!0,1===this.webGLVersion)return p.Error("Depth cube texture is not supported by WebGL 1."),n;const r={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t},a=this._gl;this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,n,!0),this._setupDepthStencilTexture(n,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction),i._depthStencilTexture=n,i._depthStencilTextureWithStencil=r.generateStencil;for(let t=0;t<6;t++)r.generateStencil?a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,a.DEPTH24_STENCIL8,e,e,0,a.DEPTH_STENCIL,a.UNSIGNED_INT_24_8,null):a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,a.DEPTH_COMPONENT24,e,e,0,a.DEPTH_COMPONENT,a.UNSIGNED_INT,null);return this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(n),n},K.prototype._partialLoadFile=function(e,t,i,n,r=null){this._loadFile(e,(e=>{i[t]=e,i._internalCount++,6===i._internalCount&&n(i)}),void 0,void 0,!0,((e,t)=>{r&&e&&r(e.status+" "+e.statusText,t)}))},K.prototype._cascadeLoadFiles=function(e,t,i,n=null){const r=[];r._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,r,t,n)},K.prototype._cascadeLoadImgs=function(e,t,i,n,r=null,s){const a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(n[o],o,a,e,t,i,r,s)},K.prototype._partialLoadImg=function(e,t,i,n,r,s,a=null,o){const l=Me();pe(e,(e=>{i[t]=e,i._internalCount++,n&&n.removePendingData(l),6===i._internalCount&&s&&s(r,i)}),((e,t)=>{n&&n.removePendingData(l),a&&a(e,t)}),n?n.offlineProvider:null,o),n&&n.addPendingData(l)},K.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)},K.prototype.createCubeTextureBase=function(e,t,i,n,r=null,a=null,l,h=null,c=!1,u=0,d=0,f=null,_=null,m=null,g=!1){const v=f||new o(this,s.Cube);v.isCube=!0,v.url=e,v.generateMipMaps=!n,v._lodGenerationScale=u,v._lodGenerationOffset=d,v._useSRGBBuffer=!!g&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!n),this._doNotHandleContextLost||(v._extension=h,v._files=i);const E=e;this._transformTextureUrl&&!f&&(e=this._transformTextureUrl(e));const T=e.split("?")[0],C=T.lastIndexOf("."),R=h||(C>-1?T.substring(C).toLowerCase():"");let A=null;for(const e of K._TextureLoaders)if(e.canLoad(R)){A=e;break}const b=(s,o)=>{e===E?a&&s&&a(s.status+" "+s.statusText,o):(p.Warn(`Failed to load ${e}, falling back to the ${E}`),this.createCubeTextureBase(E,t,i,!!n,r,a,l,h,c,u,d,v,_,m,g))};if(A){const n=e=>{_&&_(v,e),A.loadCubeData(e,v,c,r,a)};i&&6===i.length?A.supportCascades?this._cascadeLoadFiles(t,(e=>n(e.map((e=>new Uint8Array(e))))),i,a):a?a("Textures type does not support cascades."):p.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,b)}else{if(!i)throw new Error("Cannot load cubemap because files were not defined");this._cascadeLoadImgs(t,v,((e,t)=>{m&&m(e,t)}),i,a)}return this._internalTexturesCache.push(v),v},K.prototype.createCubeTexture=function(e,t,i,n,r=null,s=null,a,o=null,l=!1,h=0,c=0,u=null,d,f=!1){const _=this._gl;return this.createCubeTextureBase(e,t,i,!!n,r,s,a,o,l,h,c,u,(e=>this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?K.GetExponentOfTwo(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,s=i,o=[_.TEXTURE_CUBE_MAP_POSITIVE_X,_.TEXTURE_CUBE_MAP_POSITIVE_Y,_.TEXTURE_CUBE_MAP_POSITIVE_Z,_.TEXTURE_CUBE_MAP_NEGATIVE_X,_.TEXTURE_CUBE_MAP_NEGATIVE_Y,_.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const l=a?this._getInternalFormat(a,e._useSRGBBuffer):e._useSRGBBuffer?_.SRGB8_ALPHA8:_.RGBA;let h=a?this._getInternalFormat(a):_.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(h=l);for(let e=0;en+=e)),new Qr(n,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,n=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const s=new Qr(e,t,null,!1,null,null,null,void 0,!0,i,n);return t.useDelayedTextureLoading=r,s}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,n=!1,r=null,s=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"),u=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(u?(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(d||u||c||s||(s=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,s){for(let t=0;t-1!==e.getActiveTextures().indexOf(this)))),this._textureMatrix=e)}_loadTexture(e=null,t=null){var i;const n=this.getScene(),r=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const s=()=>{var t;this.onLoadObservable.notifyObservers(this),r&&(r.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),Si.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Pe.SetImmediate((()=>s())):this._texture.onLoadedObservable.add((()=>s())):(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=Et.Parse((()=>{let n=!1;return e.prefiltered&&(n=e.prefiltered),new Qr(i+e.name,t,e.extensions,!1,e.files||null,null,null,void 0,n,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(n.boundingBoxPosition=Ye.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(n.boundingBoxSize=Ye.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t{const t=new Qr(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}function jr(e){const t=[],i=[],n=[],r=[],s=e.width||e.size||1,a=e.height||e.size||1,o=0===e.sideOrientation?0:e.sideOrientation||Li.DEFAULTSIDE,l=s/2,h=a/2;i.push(-l,-h,0),n.push(0,0,-1),r.push(0,bi.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),n.push(0,0,-1),r.push(1,bi.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),n.push(0,0,-1),r.push(1,bi.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),n.push(0,0,-1),r.push(0,bi.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),Li._ComputeSides(o,i,t,n,r,e.frontUVs,e.backUVs);const c=new Li;return c.indices=t,c.positions=i,c.normals=n,c.uvs=r,c}function Zr(e,t={},i=null){const n=new gn(e,i);return t.sideOrientation=gn._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,jr(t).applyToMesh(n,t.updatable),t.sourcePlane&&(n.translate(t.sourcePlane.normal,-t.sourcePlane.d),n.setDirection(t.sourcePlane.normal.scale(-1))),n}function Jr(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 r=[];const s=e.width||e.size||1,a=e.height||e.size||1,o=e.depth||e.size||1,l=e.wrap||!1;let h=void 0===e.topBaseAt?1:e.topBaseAt,c=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,c=(c+4)%4;let u=[2,0,3,1][h],d=[2,0,1,3][c],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],r=[22,23,20,21];for(;u>0;)e.unshift(e.pop()),n.unshift(n.pop()),u--;for(;d>0;)i.unshift(i.pop()),r.unshift(r.pop()),d--;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(r[0],r[2],r[3],r[0],r[1],r[2])}const _=[s/2,a/2,o/2];r=f.reduce(((e,t,i)=>e.concat(t*_[i%3])),[]);const p=0===e.sideOrientation?0:e.sideOrientation||Li.DEFAULTSIDE,m=e.faceUV||new Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new Ke(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,bi.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),n.push(m[e].x,bi.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),n.push(m[e].x,bi.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),n.push(m[e].z,bi.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);Li._ComputeSides(p,r,t,i,n,e.frontUVs,e.backUVs);const E=new Li;if(E.indices=t,E.positions=r,E.normals=i,E.uvs=n,g){const e=p===Li.DOUBLESIDE?v.concat(v):v;E.colors=e}return E}function $r(e,t={},i=null){const n=new gn(e,i);return t.sideOrientation=gn._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,Jr(t).applyToMesh(n,t.updatable),n}et([ct()],Qr.prototype,"url",void 0),et([ct("rotationY")],Qr.prototype,"rotationY",null),et([ct("files")],Qr.prototype,"_files",void 0),et([ct("forcedExtension")],Qr.prototype,"_forcedExtension",void 0),et([ct("extensions")],Qr.prototype,"_extensions",void 0),et([lt(12,"textureMatrix")],Qr.prototype,"_textureMatrix",void 0),Si._CubeTextureParser=Qr.Parse,Ie("BABYLON.CubeTexture",Qr),Li.CreatePlane=jr,gn.CreatePlane=(e,t,i,n,r)=>Zr(e,{size:t,width:t,height:t,sideOrientation:r,updatable:n},i),Li.CreateBox=Jr,gn.CreateBox=(e,t,i=null,n,r)=>$r(e,{size:t,sideOrientation:r,updatable:n},i);class es{constructor(e,t){this._errorHandler=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options={...es._GetDefaultOptions(),...e},this._scene=t,this.onErrorObservable=new n,this._setupBackground(),this._setupImageProcessing()}static _GetDefaultOptions(){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new tt(.2,.2,.3).toLinearSpace().scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new tt(.2,.2,.3).toLinearSpace().scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:Ye.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}updateOptions(e){const t={...this._options,...e};this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new it(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof Ri)return void(this._scene.environmentTexture=this._options.environmentTexture);const e=Qr.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new gn("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;const e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};const n=this._scene.getWorldExtends((e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox)),r=n.max.subtract(n.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof Hn&&this._scene.activeCamera.upperRadiusLimit&&(e=2*this._scene.activeCamera.upperRadiusLimit,t=e);const s=r.length();s>e&&(e=2*s,t=e),e*=1.1,t*=1.5,i=n.min.add(r.scale(.5)),i.y=n.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){this._ground&&!this._ground.isDisposed()||(this._ground=Zr("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((()=>{this._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new Rn("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){this._groundMaterial&&(this._groundTexture||(this._options.groundTexture instanceof Ri?this._groundMaterial.diffuseTexture=this._options.groundTexture:(this._groundTexture=new Si(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture)))}_setupGroundMirrorTexture(e){const t=Si.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new qr("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,Si.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new li(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e{this._skybox=null}))),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new Rn("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){this._skyboxMaterial&&(this._skyboxTexture||(this._options.skyboxTexture instanceof Ri?this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture:(this._skyboxTexture=new Qr(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=Si.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture)))}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}}es._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",es._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",es._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class ts{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._keys=new Array}attachControl(e){e=Pe.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===Qt.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._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)){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 r=n.event,s="touch"===r.pointerType;if(t.isInVRExclusivePointerMode)return;if(!this.touchEnabled&&s)return;if(n.type!==Wt.POINTERMOVE&&-1===this.buttons.indexOf(r.button))return;const a=r.target;if(n.type===Wt.POINTERDOWN){if(s&&-1!==this._activePointerId||!s&&-1!==this._currentActiveButton)return;this._activePointerId=r.pointerId;try{null==a||a.setPointerCapture(r.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=r.button),this._previousPosition={x:r.clientX,y:r.clientY},e||(r.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(n.event)}else if(n.type===Wt.POINTERUP){if(s&&this._activePointerId!==r.pointerId||!s&&this._currentActiveButton!==r.button)return;try{null==a||a.releasePointerCapture(r.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(n.type===Wt.POINTERMOVE&&(this._activePointerId===r.pointerId||!s))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(n.event);else if(this._previousPosition){let t=r.clientX-this._previousPosition.x;const i=r.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:r.clientX,y:r.clientY},e||r.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 r=i.movementY;this.camera.cameraRotation.x+=r/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Wt.POINTERDOWN|Wt.POINTERUP|Wt.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"}}et([ct()],is.prototype,"buttons",void 0),et([ct()],is.prototype,"angularSensibility",void 0),Un.FreeCameraMouseInput=is;class ns{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new n,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=Pe.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Wt.POINTERWHEEL)return;const i=t.event,n=i.deltaMode===Jt.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,Wt.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}var rs;et([ct()],ns.prototype,"wheelPrecisionX",void 0),et([ct()],ns.prototype,"wheelPrecisionY",void 0),et([ct()],ns.prototype,"wheelPrecisionZ",void 0),function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(rs||(rs={}));class ss extends ns{constructor(){super(...arguments),this._moveRelative=Ye.Zero(),this._rotateRelative=Ye.Zero(),this._moveScene=Ye.Zero(),this._wheelXAction=rs.MoveRelative,this._wheelXActionCoordinate=_i.X,this._wheelYAction=rs.MoveRelative,this._wheelYActionCoordinate=_i.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==rs.MoveRelative||(this._wheelXAction=rs.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==rs.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==rs.MoveRelative||(this._wheelYAction=rs.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==rs.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==rs.MoveRelative||(this._wheelZAction=rs.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==rs.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==rs.RotateRelative||(this._wheelXAction=rs.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==rs.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==rs.RotateRelative||(this._wheelYAction=rs.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==rs.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==rs.RotateRelative||(this._wheelZAction=rs.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==rs.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==rs.MoveScene||(this._wheelXAction=rs.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==rs.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==rs.MoveScene||(this._wheelYAction=rs.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==rs.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==rs.MoveScene||(this._wheelZAction=rs.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==rs.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=Qe.Zero();this.camera.getViewMatrix().invertToRef(e);const t=Ye.Zero();Ye.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 rs.MoveRelative:n=this._moveRelative;break;case rs.RotateRelative:n=this._rotateRelative;break;case rs.MoveScene:n=this._moveScene}switch(i){case _i.X:n.set(e,0,0);break;case _i.Y:n.set(0,e,0);break;case _i.Z:n.set(0,0,e)}}}et([ct()],ss.prototype,"wheelXMoveRelative",null),et([ct()],ss.prototype,"wheelYMoveRelative",null),et([ct()],ss.prototype,"wheelZMoveRelative",null),et([ct()],ss.prototype,"wheelXRotateRelative",null),et([ct()],ss.prototype,"wheelYRotateRelative",null),et([ct()],ss.prototype,"wheelZRotateRelative",null),et([ct()],ss.prototype,"wheelXMoveScene",null),et([ct()],ss.prototype,"wheelYMoveScene",null),et([ct()],ss.prototype,"wheelZMoveScene",null),Un.FreeCameraMouseWheelInput=ss;class as{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=Pe.IsSafari()}attachControl(e){e=Pe.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,r="mouse"===n.pointerType||this._isSafari&&void 0===n.pointerType;if(this.allowMouse||!r)if(i.type===Wt.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===Wt.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===Wt.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,Wt.POINTERDOWN|Wt.POINTERUP|Wt.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 Ye(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);Qe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(Ye.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}et([ct()],as.prototype,"touchAngularSensibility",void 0),et([ct()],as.prototype,"touchMoveSensibility",void 0),Un.FreeCameraTouchInput=as;class os extends Vn{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new ts),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new is(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new ss,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new as),this}clear(){super.clear(),this._mouseInput=null}}class ls extends Bn{constructor(e,t,i,n=!0){super(e,t,i,n),this.ellipsoid=new Ye(.5,1,.5),this.ellipsoidOffset=new Ye(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=Ye.Zero(),this._diffPosition=Ye.Zero(),this._newPosition=Ye.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()>Z.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new os(this),this.inputs.addKeyboard().addMouse()}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)}attachControl(e,t){t=Pe.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new Ye(0,0,0),this.cameraRotation=new He(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?Ye.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=Ye.Zero(),this._transformedDirection=Ye.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"}}et([pt()],ls.prototype,"ellipsoid",void 0),et([pt()],ls.prototype,"ellipsoidOffset",void 0),et([ct()],ls.prototype,"checkCollisions",void 0),et([ct()],ls.prototype,"applyGravity",void 0),os.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new hs,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class hs{constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new qe,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new n,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-Pe.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?Pe.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?Pe.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?Pe.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new qe(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}static WaitForOrientationChangeAsync(e){return new Promise(((t,i)=>{let n=!1;const r=()=>{window.removeEventListener("deviceorientation",r),n=!0,t()};e&&setTimeout((()=>{n||(window.removeEventListener("deviceorientation",r),i("WaitForOrientationChangeAsync timed out"))}),e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"==e?window.addEventListener("deviceorientation",r):Pe.Warn("Permission not granted.")})).catch((e=>{Pe.Error(e)})):window.addEventListener("deviceorientation",r)}))}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new qe),this._camera&&this._camera.onDisposeObservable.add((()=>{this._onDeviceOrientationChangedObservable.clear()}))}attachControl(){const e=this.camera.getScene().getEngine().getHostWindow();if(e){const t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t():Pe.Warn("Permission not granted.")})).catch((e=>{Pe.Error(e)})):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(qe.RotationYawPitchRollToRef(Pe.ToRadians(this._alpha),Pe.ToRadians(this._beta),-Pe.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}Un.FreeCameraDeviceOrientationInput=hs,Mi.AddNodeConstructor("DeviceOrientationCamera",((e,t)=>()=>new cs(e,Ye.Zero(),t)));class cs extends ls{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new qe,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new qe,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce((()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add((e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new qe),qe.FromEulerAnglesToRef(0,e.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))})))}))}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=gi.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new qe),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}}class us{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return Qe.Translation(e,0,0)}get rightHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return Qe.Translation(-e,0,0)}get leftPreViewMatrix(){return Qe.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return Qe.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new us;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}P.ShadersStore.vrDistortionCorrectionPixelShader="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}";class ds extends nr{constructor(e,t,i,n){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,n.postProcessScaleFactor,t,Si.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=n.distortionK,this._postProcessScaleFactor=n.postProcessScaleFactor,this._lensCenterOffset=n.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add((()=>{this._scaleIn=new He(2,2/this.aspectRatio),this._scaleFactor=new He(1/this._postProcessScaleFactor*.5,1/this._postProcessScaleFactor*.5*this.aspectRatio),this._lensCenter=new He(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)})),this.onApplyObservable.add((e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])}))}getClassName(){return"VRDistortionCorrectionPostProcess"}}P.ShadersStore.vrMultiviewToSingleviewPixelShader="precision mediump sampler2DArray;\nvarying vec2 vUV;\nuniform sampler2DArray multiviewSampler;\nuniform int imageIndex;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\ngl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));\n}";class fs extends dr{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}}function _s(e,t){const i=new Nt(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}Z.prototype.createMultiviewRenderTargetTexture=function(e,t){const i=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=i.createFramebuffer();const r=new o(this,s.Unknown,!0);return r.width=e,r.height=t,r.isMultiview=!0,n._colorTextureArray=i.createTexture(),i.bindTexture(i.TEXTURE_2D_ARRAY,n._colorTextureArray),i.texStorage3D(i.TEXTURE_2D_ARRAY,1,i.RGBA8,e,t,2),n._depthStencilTextureArray=i.createTexture(),i.bindTexture(i.TEXTURE_2D_ARRAY,n._depthStencilTextureArray),i.texStorage3D(i.TEXTURE_2D_ARRAY,1,i.DEPTH24_STENCIL8,e,t,2),r.isReady=!0,n.setTextures(r),n._depthStencilTexture=r,n},Z.prototype.bindMultiviewFramebuffer=function(e){const t=e,i=this._gl,n=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(n.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,t.samples,0,2),n.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,t.samples,0,2)):(n.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),n.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,0,2))},Fi.prototype._useMultiviewToSingleView=!1,Fi.prototype._multiviewTexture=null,Fi.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new fs(this.getScene(),{width:e,height:t})):this._multiviewTexture=new fs(this.getScene(),{width:e,height:t})};const ps=mi.prototype.createSceneUniformBuffer;mi.prototype._transformMatrixR=Qe.Zero(),mi.prototype._multiviewSceneUbo=null,mi.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=_s(this.getEngine(),"scene_multiview")},mi.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?_s(this.getEngine(),e):ps.bind(this)(e)},mi.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,Ze.Matrix[0]),hi.GetRightPlaneToRef(Ze.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))},mi.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{})),this.onApplyObservable.add((e=>{n._scene.activeCamera&&n._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",n._multiviewTexture)}))}}function gs(e,t){const i=t.vrCameraMetrics||us.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new Ti(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new Qe,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new Ti(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new Qe,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new ms("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(p.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new ds("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new ds("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}Mi.AddNodeConstructor("VRDeviceOrientationFreeCamera",((e,t)=>()=>new vs(e,Ye.Zero(),t)));class vs extends cs{constructor(e,t,i,n=!0,r=us.GetDefault()){super(e,t,i),this._setRigMode=gs.bind(null,this),r.compensateDistortion=n,this.setCameraRigMode(Fi.RIG_MODE_VR,{vrCameraMetrics:r})}getClassName(){return"VRDeviceOrientationFreeCamera"}}class Es{constructor(e,t,i,n=0,r=1,s=2,a=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=Es.GAMEPAD,this._leftStickAxisX=n,this._leftStickAxisY=r,this._rightStickAxisX=s,this._rightStickAxisY=a,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}get isConnected(){return this._isConnected}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}Es.GAMEPAD=0,Es.GENERIC=1,Es.XBOX=2,Es.POSE_ENABLED=3,Es.DUALSHOCK=4;class Ts extends Es{constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new n,this.onButtonUpObservable=new n,this.type=Es.GENERIC,this._buttons=new Array(i.buttons.length)}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;er.x)return!1}else if(s=1/this.direction.x,a=(n.x-this.origin.x)*s,o=(r.x-this.origin.x)*s,o===-1/0&&(o=1/0),a>o&&(l=a,a=o,o=l),h=Math.max(a,h),c=Math.min(o,c),h>c)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yr.y)return!1}else if(s=1/this.direction.y,a=(n.y-this.origin.y)*s,o=(r.y-this.origin.y)*s,o===-1/0&&(o=1/0),a>o&&(l=a,a=o,o=l),h=Math.max(a,h),c=Math.min(o,c),h>c)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zr.z)return!1}else if(s=1/this.direction.z,a=(n.z-this.origin.z)*s,o=(r.z-this.origin.z)*s,o===-1/0&&(o=1/0),a>o&&(l=a,a=o,o=l),h=Math.max(a,h),c=Math.min(o,c),h>c)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,n=e.center.y-this.origin.y,r=e.center.z-this.origin.z,s=i*i+n*n+r*r,a=e.radius+t,o=a*a;if(s<=o)return!0;const l=i*this.direction.x+n*this.direction.y+r*this.direction.z;return!(l<0)&&s-l*l<=o}intersectsTriangle(e,t,i){const n=Cs._TmpVector3[0],r=Cs._TmpVector3[1],s=Cs._TmpVector3[2],a=Cs._TmpVector3[3],o=Cs._TmpVector3[4];t.subtractToRef(e,n),i.subtractToRef(e,r),Ye.CrossToRef(this.direction,r,s);const l=Ye.Dot(n,s);if(0===l)return null;const h=1/l;this.origin.subtractToRef(e,a);const c=Ye.Dot(a,s)*h;if(c<0||c>1)return null;Ye.CrossToRef(a,n,o);const u=Ye.Dot(this.direction,o)*h;if(u<0||c+u>1)return null;const d=Ye.Dot(r,o)*h;return d>this.length?null:new wi(1-c-u,c,d)}intersectsPlane(e){let t;const i=Ye.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;{const n=Ye.Dot(e.normal,this.origin);return t=(-e.d-n)/i,t<0?t<-9.99999997475243e-7?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const e=(this.origin.y-t)/this.direction.y;return e>0?null:new Ye(this.origin.x+this.direction.x*-e,t,this.origin.z+this.direction.z*-e)}case"x":{const e=(this.origin.x-t)/this.direction.x;return e>0?null:new Ye(t,this.origin.y+this.direction.y*-e,this.origin.z+this.direction.z*-e)}case"z":{const e=(this.origin.z-t)/this.direction.z;return e>0?null:new Ye(this.origin.x+this.direction.x*-e,this.origin.y+this.direction.y*-e,t)}default:return null}}intersectsMesh(e,t){const i=Ze.Matrix[0];return e.getWorldMatrix().invertToRef(i),this._tmpRay?Cs.TransformToRef(this,i,this._tmpRay):this._tmpRay=Cs.Transform(this,i),e.intersects(this._tmpRay,t)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let n=0;nt.distance?1:0}intersectionSegment(e,t,i){const n=this.origin,r=Ze.Vector3[0],s=Ze.Vector3[1],a=Ze.Vector3[2],o=Ze.Vector3[3];t.subtractToRef(e,r),this.direction.scaleToRef(Cs._Rayl,a),n.addToRef(a,s),e.subtractToRef(n,o);const l=Ye.Dot(r,r),h=Ye.Dot(r,a),c=Ye.Dot(a,a),u=Ye.Dot(r,o),d=Ye.Dot(a,o),f=l*c-h*h;let _,p,m=f,g=f;fm&&(_=m,p=d+h,g=c)),p<0?(p=0,-u<0?_=0:-u>l?_=m:(_=-u,m=l)):p>g&&(p=g,-u+h<0?_=0:-u+h>l?_=m:(_=-u+h,m=l));const v=Math.abs(_)0&&E<=this.length&&R.lengthSquared()=e.distance?null:h:null},mi.prototype._internalPick=function(e,t,i,n,r){let s=null;for(let a=0;a(this._tempPickingRay||(this._tempPickingRay=Cs.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null),this._tempPickingRay)),i,n,!0);return s&&(s.ray=this.createPickingRay(e,t,Qe.Identity(),r||null)),s},Object.defineProperty(mi.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),mi.prototype.pick=function(e,t,i,n,r,s,a=!1){const o=this._internalPick(((i,n)=>(this._tempPickingRay||(this._tempPickingRay=Cs.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null,!1,n),this._tempPickingRay)),i,n,!1,s);return o&&(o.ray=this.createPickingRay(e,t,Qe.Identity(),r||null)),o},mi.prototype.pickWithRay=function(e,t,i,n){const r=this._internalPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=Qe.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Cs.Zero()),Cs.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i,!1,n);return r&&(r.ray=e),r},mi.prototype.multiPick=function(e,t,i,n,r){return this._internalMultiPick((i=>this.createPickingRay(e,t,i,n||null)),i,r)},mi.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=Qe.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Cs.Zero()),Cs.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i)},Fi.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new Cs(Ye.Zero(),Ye.Zero(),e),e,t,i)},Fi.prototype.getForwardRayToRef=function(e,t=100,i,n){return i||(i=this.getWorldMatrix()),e.length=t,n?e.origin.copyFrom(n):e.origin.copyFrom(this.position),Ze.Vector3[2].set(0,0,this._scene.useRightHandedSystem?-1:1),Ye.TransformNormalToRef(Ze.Vector3[2],i,Ze.Vector3[3]),Ye.NormalizeToRef(Ze.Vector3[3],e.direction),e},function(e){e[e.VIVE=0]="VIVE",e[e.OCULUS=1]="OCULUS",e[e.WINDOWS=2]="WINDOWS",e[e.GEAR_VR=3]="GEAR_VR",e[e.DAYDREAM=4]="DAYDREAM",e[e.GENERIC=5]="GENERIC"}(Rs||(Rs={}));class Ss{static InitiateController(e){for(const t of this._ControllerFactories)if(t.canCreate(e))return t.create(e);if(this._DefaultControllerFactory)return this._DefaultControllerFactory(e);throw"The type of gamepad you are trying to load needs to be imported first or is not supported."}}Ss._ControllerFactories=[],Ss._DefaultControllerFactory=null;class Is extends Es{constructor(e){super(e.id,e.index,e),this.isXR=!1,this._deviceRoomPosition=Ye.Zero(),this._deviceRoomRotationQuaternion=new qe,this.devicePosition=Ye.Zero(),this.deviceRotationQuaternion=new qe,this.deviceScaleFactor=1,this._trackPosition=!0,this._maxRotationDistFromHeadset=Math.PI/5,this._draggedRoomRotation=0,this._leftHandSystemQuaternion=new qe,this._deviceToWorld=Qe.Identity(),this._pointingPoseNode=null,this._workingMatrix=Qe.Identity(),this._meshAttachedObservable=new n,this.type=Es.POSE_ENABLED,this.controllerType=Rs.GENERIC,this.position=Ye.Zero(),this.rotationQuaternion=new qe,this._calculatedPosition=Ye.Zero(),this._calculatedRotation=new qe,qe.RotationYawPitchRollToRef(Math.PI,0,0,this._leftHandSystemQuaternion)}_disableTrackPosition(e){this._trackPosition&&(this._calculatedPosition.copyFrom(e),this._trackPosition=!1)}update(){super.update(),this._updatePoseAndMesh()}_updatePoseAndMesh(){if(this.isXR)return;const e=this.browserGamepad.pose;if(this.updateFromDevice(e),!this._trackPosition&&f.LastCreatedScene&&f.LastCreatedScene.activeCamera&&f.LastCreatedScene.activeCamera.devicePosition){const e=f.LastCreatedScene.activeCamera;if(e._computeDevicePosition(),this._deviceToWorld.setTranslation(e.devicePosition),e.deviceRotationQuaternion){e._deviceRoomRotationQuaternion.toEulerAnglesToRef(Ze.Vector3[0]);const t=Math.atan2(Math.sin(Ze.Vector3[0].y-this._draggedRoomRotation),Math.cos(Ze.Vector3[0].y-this._draggedRoomRotation));if(Math.abs(t)>this._maxRotationDistFromHeadset){const e=t-(t<0?-this._maxRotationDistFromHeadset:this._maxRotationDistFromHeadset);this._draggedRoomRotation+=e;const i=Math.sin(-e),n=Math.cos(-e);this._calculatedPosition.x=this._calculatedPosition.x*n-this._calculatedPosition.z*i,this._calculatedPosition.z=this._calculatedPosition.x*i+this._calculatedPosition.z*n}}}Ye.TransformCoordinatesToRef(this._calculatedPosition,this._deviceToWorld,this.devicePosition),this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix),qe.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation),this._mesh&&(this._mesh.position.copyFrom(this.devicePosition),this._mesh.rotationQuaternion&&this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion))}updateFromDevice(e){if(!this.isXR&&e){this.rawPose=e,e.position&&(this._deviceRoomPosition.copyFromFloats(e.position[0],e.position[1],-e.position[2]),this._mesh&&this._mesh.getScene().useRightHandedSystem&&(this._deviceRoomPosition.z*=-1),this._trackPosition&&this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor,this._calculatedPosition),this._calculatedPosition.addInPlace(this.position));const t=this.rawPose;e.orientation&&t.orientation&&4===t.orientation.length&&(this._deviceRoomRotationQuaternion.copyFromFloats(t.orientation[0],t.orientation[1],-t.orientation[2],-t.orientation[3]),this._mesh&&(this._mesh.getScene().useRightHandedSystem?(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1):this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion,this._deviceRoomRotationQuaternion)),this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion,this._calculatedRotation))}}attachToMesh(e){if(this._mesh&&(this._mesh.parent=null),this._mesh=e,this._poseControlledCamera&&(this._mesh.parent=this._poseControlledCamera),this._mesh.rotationQuaternion||(this._mesh.rotationQuaternion=new qe),!this.isXR&&(this._updatePoseAndMesh(),this._pointingPoseNode)){const e=[];let t=this._pointingPoseNode;for(;t.parent;)e.push(t.parent),t=t.parent;e.reverse().forEach((e=>{e.computeWorldMatrix(!0)}))}this._meshAttachedObservable.notifyObservers(e)}attachToPoseControlledCamera(e){this._poseControlledCamera=e,this._mesh&&(this._mesh.parent=this._poseControlledCamera)}dispose(){this._mesh&&this._mesh.dispose(),this._mesh=null,super.dispose()}get mesh(){return this._mesh}getForwardRay(e=100){if(!this.mesh)return new Cs(Ye.Zero(),new Ye(0,0,1),e);const t=this._pointingPoseNode?this._pointingPoseNode.getWorldMatrix():this.mesh.getWorldMatrix(),i=t.getTranslation(),n=new Ye(0,0,-1),r=Ye.TransformNormal(n,t),s=Ye.Normalize(r);return new Cs(i,s,e)}}function xs(e,t){if(t.vrDisplay){const i=t.vrDisplay.getEyeParameters("left"),n=t.vrDisplay.getEyeParameters("right");e._rigCameras[0].viewport=new Ti(0,0,.5,1),e._rigCameras[0].setCameraRigParameter("left",!0),e._rigCameras[0].setCameraRigParameter("specs",t.specs),e._rigCameras[0].setCameraRigParameter("eyeParameters",i),e._rigCameras[0].setCameraRigParameter("frameData",t.frameData),e._rigCameras[0].setCameraRigParameter("parentCamera",t.parentCamera),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new Qe,e._rigCameras[0].getProjectionMatrix=e._getWebVRProjectionMatrix,e._rigCameras[0].parent=e,e._rigCameras[0]._getViewMatrix=e._getWebVRViewMatrix,e._rigCameras[1].viewport=new Ti(.5,0,.5,1),e._rigCameras[1].setCameraRigParameter("eyeParameters",n),e._rigCameras[1].setCameraRigParameter("specs",t.specs),e._rigCameras[1].setCameraRigParameter("frameData",t.frameData),e._rigCameras[1].setCameraRigParameter("parentCamera",t.parentCamera),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new Qe,e._rigCameras[1].getProjectionMatrix=e._getWebVRProjectionMatrix,e._rigCameras[1].parent=e,e._rigCameras[1]._getViewMatrix=e._getWebVRViewMatrix}}Is.POINTING_POSE="POINTING_POSE",Object.defineProperty(Z.prototype,"isInVRExclusivePointerMode",{get:function(){return this._vrExclusivePointerMode},enumerable:!0,configurable:!0}),Z.prototype._prepareVRComponent=function(){this._vrSupported=!1,this._vrExclusivePointerMode=!1,this.onVRDisplayChangedObservable=new n,this.onVRRequestPresentComplete=new n,this.onVRRequestPresentStart=new n},Z.prototype.isVRDevicePresent=function(){return!!this._vrDisplay},Z.prototype.getVRDevice=function(){return this._vrDisplay},Z.prototype.initWebVR=function(){return this.initWebVRAsync(),this.onVRDisplayChangedObservable},Z.prototype.initWebVRAsync=function(){const e=()=>{const e={vrDisplay:this._vrDisplay,vrSupported:this._vrSupported};this.onVRDisplayChangedObservable.notifyObservers(e),this._webVRInitPromise=new Promise((t=>{t(e)}))};if(!this._onVrDisplayConnect){this._onVrDisplayConnect=t=>{this._vrDisplay=t.display,e()},this._onVrDisplayDisconnect=()=>{this._vrDisplay.cancelAnimationFrame(this._frameHandler),this._vrDisplay=void 0,this._frameHandler=Z.QueueNewFrame(this._boundRenderFunction),e()},this._onVrDisplayPresentChange=()=>{this._vrExclusivePointerMode=this._vrDisplay&&this._vrDisplay.isPresenting};const t=this.getHostWindow();t&&(t.addEventListener("vrdisplayconnect",this._onVrDisplayConnect),t.addEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),t.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange))}return this._webVRInitPromise=this._webVRInitPromise||this._getVRDisplaysAsync(),this._webVRInitPromise.then(e),this._webVRInitPromise},Z.prototype._getVRDisplaysAsync=function(){return new Promise((e=>{navigator.getVRDisplays?navigator.getVRDisplays().then((t=>{this._vrSupported=!0,this._vrDisplay=t[0],e({vrDisplay:this._vrDisplay,vrSupported:this._vrSupported})})):(this._vrDisplay=void 0,this._vrSupported=!1,e({vrDisplay:this._vrDisplay,vrSupported:this._vrSupported}))}))},Z.prototype.enableVR=function(e){if(this._vrDisplay&&!this._vrDisplay.isPresenting){const t=()=>{this.onVRRequestPresentComplete.notifyObservers(!0),this._onVRFullScreenTriggered()},i=()=>{this.onVRRequestPresentComplete.notifyObservers(!1)};this.onVRRequestPresentStart.notifyObservers(this);const n={highRefreshRate:!!this.vrPresentationAttributes&&this.vrPresentationAttributes.highRefreshRate,foveationLevel:this.vrPresentationAttributes?this.vrPresentationAttributes.foveationLevel:1,multiview:(this.getCaps().multiview||this.getCaps().oculusMultiview)&&e.useMultiview};this._vrDisplay.requestPresent([{source:this.getRenderingCanvas(),attributes:n,...n}]).then(t).catch(i)}},Z.prototype._onVRFullScreenTriggered=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting){this._oldSize=new Ei(this.getRenderWidth(),this.getRenderHeight()),this._oldHardwareScaleFactor=this.getHardwareScalingLevel();const e=this._vrDisplay.getEyeParameters("left");this.setHardwareScalingLevel(1),this.setSize(2*e.renderWidth,e.renderHeight)}else this.setHardwareScalingLevel(this._oldHardwareScaleFactor),this.setSize(this._oldSize.width,this._oldSize.height)},Z.prototype.disableVR=function(){this._vrDisplay&&this._vrDisplay.isPresenting&&this._vrDisplay.exitPresent().then((()=>this._onVRFullScreenTriggered())).catch((()=>this._onVRFullScreenTriggered())),l()&&(window.removeEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted),window.removeEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted),this._onVrDisplayConnect&&(window.removeEventListener("vrdisplayconnect",this._onVrDisplayConnect),this._onVrDisplayDisconnect&&window.removeEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),this._onVrDisplayPresentChange&&window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),this._onVrDisplayConnect=null,this._onVrDisplayDisconnect=null))},Z.prototype._connectVREvents=function(e,t){if(this._onVRDisplayPointerRestricted=()=>{e&&e.requestPointerLock()},this._onVRDisplayPointerUnrestricted=()=>{if(t)t.exitPointerLock&&t.exitPointerLock();else{const e=this.getHostWindow();e.document&&e.document.exitPointerLock&&e.document.exitPointerLock()}},l()){const e=this.getHostWindow();e.addEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted,!1),e.addEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted,!1)}},Z.prototype._submitVRFrame=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting)try{this._vrDisplay.submitFrame()}catch(e){Pe.Warn("webVR submitFrame has had an unexpected failure: "+e)}},Z.prototype.isVRPresenting=function(){return this._vrDisplay&&this._vrDisplay.isPresenting},Z.prototype._requestVRFrame=function(){this._frameHandler=Z.QueueNewFrame(this._boundRenderFunction,this._vrDisplay)},Mi.AddNodeConstructor("WebVRFreeCamera",((e,t)=>()=>new ys(e,Ye.Zero(),t))),Mi.AddNodeConstructor("WebVRGamepadCamera",((e,t)=>()=>new ys(e,Ye.Zero(),t)));class ys extends ls{constructor(e,t,i,r={}){super(e,t,i),this._webVROptions=r,this._vrDevice=null,this.rawPose=null,this._specsVersion="1.1",this._attached=!1,this._descendants=[],this._deviceRoomPosition=Ye.Zero(),this._deviceRoomRotationQuaternion=qe.Identity(),this._standingMatrix=null,this.devicePosition=Ye.Zero(),this.deviceRotationQuaternion=qe.Identity(),this.deviceScaleFactor=1,this._deviceToWorld=Qe.Identity(),this._worldToDevice=Qe.Identity(),this.controllers=[],this.onControllersAttachedObservable=new n,this.onControllerMeshLoadedObservable=new n,this.onPoseUpdatedFromDeviceObservable=new n,this._poseSet=!1,this.rigParenting=!0,this._defaultHeight=void 0,this._setRigMode=xs.bind(null,this),this._detachIfAttached=()=>{const e=this.getEngine().getVRDevice();e&&!e.isPresenting&&this.detachControl()},this._workingVector=Ye.Zero(),this._oneVector=Ye.One(),this._workingMatrix=Qe.Identity(),this._tmpMatrix=new Qe,this._cache.position=Ye.Zero(),r.defaultHeight&&(this._defaultHeight=r.defaultHeight,this.position.y=this._defaultHeight),this.minZ=.1,5===arguments.length&&(this._webVROptions=arguments[4]),null==this._webVROptions.trackPosition&&(this._webVROptions.trackPosition=!0),null==this._webVROptions.controllerMeshes&&(this._webVROptions.controllerMeshes=!0),null==this._webVROptions.defaultLightingOnControllers&&(this._webVROptions.defaultLightingOnControllers=!0),this.rotationQuaternion=new qe,this._webVROptions&&this._webVROptions.positionScale&&(this.deviceScaleFactor=this._webVROptions.positionScale);const s=this.getEngine();this._onVREnabled=e=>{e&&this.initControllers()},s.onVRRequestPresentComplete.add(this._onVREnabled),s.initWebVR().add((e=>{e.vrDisplay&&this._vrDevice!==e.vrDisplay&&(this._vrDevice=e.vrDisplay,this.setCameraRigMode(Fi.RIG_MODE_WEBVR,{parentCamera:this,vrDisplay:this._vrDevice,frameData:this._frameData,specs:this._specsVersion}),this._attached&&this.getEngine().enableVR(this._webVROptions))})),"undefined"!=typeof VRFrameData&&(this._frameData=new VRFrameData),r.useMultiview&&(this.getScene().getEngine().getCaps().multiview?(this._useMultiviewToSingleView=!0,this._rigPostProcess=new ms("VRMultiviewToSingleview",this,1)):(p.Warn("Multiview is not supported, falling back to standard rendering"),this._useMultiviewToSingleView=!1)),this.getScene().onBeforeCameraRenderObservable.add((e=>{e.parent===this&&this.rigParenting&&(this._descendants=this.getDescendants(!0,(e=>{const t=this.controllers.some((t=>t._mesh===e)),i=-1!==this._rigCameras.indexOf(e);return!t&&!i})),this._descendants.forEach((t=>{t.parent=e})))})),this.getScene().onAfterCameraRenderObservable.add((e=>{e.parent===this&&this.rigParenting&&this._descendants.forEach((e=>{e.parent=this}))}))}deviceDistanceToRoomGround(){return this._standingMatrix?(this._standingMatrix.getTranslationToRef(this._workingVector),this._deviceRoomPosition.y+this._workingVector.y):this._defaultHeight||0}useStandingMatrix(e=(e=>{})){this.getEngine().initWebVRAsync().then((t=>{t.vrDisplay&&t.vrDisplay.stageParameters&&t.vrDisplay.stageParameters.sittingToStandingTransform&&this._webVROptions.trackPosition?(this._standingMatrix=new Qe,Qe.FromFloat32ArrayToRefScaled(t.vrDisplay.stageParameters.sittingToStandingTransform,0,1,this._standingMatrix),this.getScene().useRightHandedSystem||this._standingMatrix&&this._standingMatrix.toggleModelMatrixHandInPlace(),e(!0)):e(!1)}))}useStandingMatrixAsync(){return new Promise((e=>{this.useStandingMatrix((t=>{e(t)}))}))}dispose(){this._detachIfAttached(),this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled),this._updateCacheWhenTrackingDisabledObserver&&this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver),super.dispose()}getControllerByName(e){for(const t of this.controllers)if(t.hand===e)return t;return null}get leftController(){return this._leftController||(this._leftController=this.getControllerByName("left")),this._leftController}get rightController(){return this._rightController||(this._rightController=this.getControllerByName("right")),this._rightController}getForwardRay(e=100){return this.leftCamera?super.getForwardRay(e,this.leftCamera.getWorldMatrix(),this.leftCamera.globalPosition):super.getForwardRay(e)}_checkInputs(){this._vrDevice&&this._vrDevice.isPresenting&&(this._vrDevice.getFrameData(this._frameData),this.updateFromDevice(this._frameData.pose)),super._checkInputs()}updateFromDevice(e){e&&e.orientation&&4===e.orientation.length&&(this.rawPose=e,this._deviceRoomRotationQuaternion.copyFromFloats(e.orientation[0],e.orientation[1],-e.orientation[2],-e.orientation[3]),this.getScene().useRightHandedSystem&&(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1),this._webVROptions.trackPosition&&this.rawPose.position&&(this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0],this.rawPose.position[1],-this.rawPose.position[2]),this.getScene().useRightHandedSystem&&(this._deviceRoomPosition.z*=-1)),this._poseSet=!0)}attachControl(e){e=Pe.BackCompatCameraNoPreventDefault(arguments),super.attachControl(e),this._attached=!0,e=!Fi.ForceAttachControlToAlwaysPreventDefault&&e,this._vrDevice&&this.getEngine().enableVR(this._webVROptions);const t=this._scene.getEngine().getHostWindow();t&&t.addEventListener("vrdisplaypresentchange",this._detachIfAttached)}detachControl(){this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),super.detachControl(),this._attached=!1,this.getEngine().disableVR(),window.removeEventListener("vrdisplaypresentchange",this._detachIfAttached)}getClassName(){return"WebVRFreeCamera"}resetToCurrentRotation(){this._vrDevice.resetPose()}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];e.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),t.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),e.position.copyFrom(this._deviceRoomPosition),t.position.copyFrom(this._deviceRoomPosition)}_correctPositionIfNotTrackPosition(e,t=!1){this.rawPose&&this.rawPose.position&&!this._webVROptions.trackPosition&&(Qe.TranslationToRef(this.rawPose.position[0],this.rawPose.position[1],-this.rawPose.position[2],this._tmpMatrix),t||this._tmpMatrix.invert(),this._tmpMatrix.multiplyToRef(e,e))}_updateCache(e){this.rotationQuaternion.equals(this._cache.rotationQuaternion)&&this.position.equals(this._cache.position)||(this._updateCacheCalled||(this._updateCacheCalled=!0,this.update()),this.rotationQuaternion.toRotationMatrix(this._workingMatrix),Ye.TransformCoordinatesToRef(this._deviceRoomPosition,this._workingMatrix,this._workingVector),this.devicePosition.subtractToRef(this._workingVector,this._workingVector),Qe.ComposeToRef(this._oneVector,this.rotationQuaternion,this._workingVector,this._deviceToWorld),this._deviceToWorld.getTranslationToRef(this._workingVector),this._workingVector.addInPlace(this.position),this._workingVector.subtractInPlace(this._cache.position),this._deviceToWorld.setTranslation(this._workingVector),this._deviceToWorld.invertToRef(this._worldToDevice),this.controllers.forEach((e=>{e._deviceToWorld.copyFrom(this._deviceToWorld),this._correctPositionIfNotTrackPosition(e._deviceToWorld),e.update()}))),e||super._updateCache(),this._updateCacheCalled=!1}_computeDevicePosition(){Ye.TransformCoordinatesToRef(this._deviceRoomPosition,this._deviceToWorld,this.devicePosition)}update(){this._computeDevicePosition(),Qe.FromQuaternionToRef(this._deviceRoomRotationQuaternion,this._workingMatrix),this._workingMatrix.multiplyToRef(this._deviceToWorld,this._workingMatrix),qe.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this._poseSet&&this.onPoseUpdatedFromDeviceObservable.notifyObservers(null),super.update()}_getViewMatrix(){return Qe.Identity()}_getWebVRViewMatrix(){const e=this._cameraRigParams.parentCamera;e._updateCache();const t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftViewMatrix:this._cameraRigParams.frameData.rightViewMatrix;return Qe.FromArrayToRef(t,0,this._webvrViewMatrix),this.getScene().useRightHandedSystem||this._webvrViewMatrix.toggleModelMatrixHandInPlace(),this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix),Ye.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),1!==e.deviceScaleFactor&&(this._webvrViewMatrix.invert(),e.deviceScaleFactor&&(this._webvrViewMatrix.multiplyAtIndex(12,e.deviceScaleFactor),this._webvrViewMatrix.multiplyAtIndex(13,e.deviceScaleFactor),this._webvrViewMatrix.multiplyAtIndex(14,e.deviceScaleFactor)),this._webvrViewMatrix.invert()),e._correctPositionIfNotTrackPosition(this._webvrViewMatrix,!0),e._worldToDevice.multiplyToRef(this._webvrViewMatrix,this._webvrViewMatrix),this._workingMatrix=this._workingMatrix||Qe.Identity(),this._webvrViewMatrix.invertToRef(this._workingMatrix),this._workingMatrix.multiplyToRef(e.getWorldMatrix(),this._workingMatrix),this._workingMatrix.getTranslationToRef(this._globalPosition),this._markSyncedWithParent(),this._webvrViewMatrix}_getWebVRProjectionMatrix(){const e=this.parent;e._vrDevice.depthNear=e.minZ,e._vrDevice.depthFar=e.maxZ;const t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftProjectionMatrix:this._cameraRigParams.frameData.rightProjectionMatrix;return Qe.FromArrayToRef(t,0,this._projectionMatrix),this.getScene().useRightHandedSystem||this._projectionMatrix.toggleProjectionMatrixHandInPlace(),this._projectionMatrix}initControllers(){this.controllers.length=0;const e=this.getScene().gamepadManager;this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{if(e.type===Es.POSE_ENABLED){const t=e;t.defaultModel&&t.defaultModel.setEnabled(!1),"right"===t.hand&&(this._rightController=null),"left"===t.hand&&(this._leftController=null);const i=this.controllers.indexOf(t);-1!==i&&this.controllers.splice(i,1)}})),this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{if(e.type===Es.POSE_ENABLED){const t=e;if(this._webVROptions.trackPosition||(t._disableTrackPosition(new Ye("left"==t.hand?-.15:.15,-.5,.25)),this._updateCacheWhenTrackingDisabledObserver||(this._updateCacheWhenTrackingDisabledObserver=this._scene.onBeforeRenderObservable.add((()=>{this._updateCache()})))),t.deviceScaleFactor=this.deviceScaleFactor,t._deviceToWorld.copyFrom(this._deviceToWorld),this._correctPositionIfNotTrackPosition(t._deviceToWorld),this._webVROptions.controllerMeshes&&(t.defaultModel?t.defaultModel.setEnabled(!0):t.initControllerMesh(this.getScene(),(e=>{if(e.scaling.scaleInPlace(this.deviceScaleFactor),this.onControllerMeshLoadedObservable.notifyObservers(t),this._webVROptions.defaultLightingOnControllers){this._lightOnControllers||(this._lightOnControllers=new Yr("vrControllersLight",new Ye(0,1,0),this.getScene()));const t=function(e,i){const n=e.getChildren();n&&0!==n.length&&n.forEach((e=>{i.includedOnlyMeshes.push(e),t(e,i)}))};this._lightOnControllers.includedOnlyMeshes.push(e),t(e,this._lightOnControllers)}}))),t.attachToPoseControlledCamera(this),-1===this.controllers.indexOf(t)){this.controllers.push(t);let e=!1;for(let t=0;t=2&&this.onControllersAttachedObservable.notifyObservers(this.controllers)}}}))}}class Ms extends Is{constructor(e){super(e),this.onTriggerStateChangedObservable=new n,this.onMainButtonStateChangedObservable=new n,this.onSecondaryButtonStateChangedObservable=new n,this.onPadStateChangedObservable=new n,this.onPadValuesChangedObservable=new n,this.pad={x:0,y:0},this._changes={pressChanged:!1,touchChanged:!1,valueChanged:!1,changed:!1},this._buttons=new Array(e.buttons.length),this.hand=e.hand}onButtonStateChange(e){this._onButtonStateChange=e}get defaultModel(){return this._defaultModel}update(){super.update();for(let e=0;e\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}";class Ds extends nr{constructor(e,t,i=null,n,r,s,a=0,o){super(e,"imageProcessing",[],[],t,i,n,r,s,null,a,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},o?(o.applyByPostProcess=!0,this._attachImageProcessingConfiguration(o,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null;const t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){const i=t.scenes;e=i[i.length-1]}else e=f.LastCreatedScene;this._imageProcessingConfiguration=e?e.imageProcessingConfiguration:new bt}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateParameters()}))),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const t in this._defines)this._defines[t]&&(e+=`#define ${t};\r\n`);const t=["textureSampler"],i=["scale"];bt&&(bt.PrepareSamplers(t,this._defines),bt.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}var Ns,Fs;et([ct()],Ds.prototype,"_fromLinearSpace",void 0),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.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Ns||(Ns={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Fs||(Fs={}));class Ls extends Es{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new n,this.onButtonUpObservable=new n,this.onPadDownObservable=new n,this.onPadUpObservable=new n,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=Es.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,Ns.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,Ns.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,Ns.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,Ns.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,Ns.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,Ns.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,Ns.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,Ns.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Ns.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Ns.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Fs.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Fs.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Fs.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Fs.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class ws{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new n,l()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new n((e=>{for(const t in this._babylonGamepads){const i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}})),this._onGamepadConnectedEvent=e=>{const t=e.gamepad;if(t.index in this._babylonGamepads&&this._babylonGamepads[t.index].isConnected)return;let i;this._babylonGamepads[t.index]?(i=this._babylonGamepads[t.index],i.browserGamepad=t,i._isConnected=!0):i=this._addNewGamepad(t),this.onGamepadConnectedObservable.notifyObservers(i),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=e=>{const t=e.gamepad;for(const e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){const t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=Es.XBOX){for(const t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach((e=>{e.dispose()})),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);const i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),n=-1!==e.id.search("Xbox One");return t=n||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new Ps(e.id,e.index,e,n):i?new Ls(e.id,e.index,e):e.pose?Ss.InitiateController(e):new Ts(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._scene||this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){this._updateGamepadObjects();for(const e in this._babylonGamepads){const t=this._babylonGamepads[e];if(t&&t.isConnected)try{t.update()}catch(e){-1===this._loggedErrors.indexOf(t.index)&&(Pe.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&!this._scene&&Z.QueueNewFrame((()=>{this._checkGamepadsStatus()}))}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t{e.type!==Es.POSE_ENABLED&&(this.gamepad&&e.type!==Es.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(Es.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){const e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):Qe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const n=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*n,0,-t.y*n),Ye.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}}et([ct()],Bs.prototype,"gamepadAngularSensibility",void 0),et([ct()],Bs.prototype,"gamepadMoveSensibility",void 0),Un.FreeCameraGamepadInput=Bs;class Us{constructor(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40,this._yAxisScale=1}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{e.type!==Es.POSE_ENABLED&&(this.gamepad&&e.type!==Es.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(Es.XBOX)}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){const i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){const i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}const i=this.gamepad.leftStick;if(i&&0!=i.y){const e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}et([ct()],Us.prototype,"gamepadRotationSensibility",void 0),et([ct()],Us.prototype,"gamepadMoveSensibility",void 0),Un.ArcRotateCameraGamepadInput=Us,Object.defineProperty(mi.prototype,"gamepadManager",{get:function(){if(!this._gamepadManager){this._gamepadManager=new ws(this);let e=this._getComponent(zt.NAME_GAMEPAD);e||(e=new Vs(this),this._addComponent(e))}return this._gamepadManager},enumerable:!0,configurable:!0}),os.prototype.addGamepad=function(){return this.add(new Bs),this},Wn.prototype.addGamepad=function(){return this.add(new Us),this};class Vs{constructor(e){this.name=zt.NAME_GAMEPAD,this.scene=e}register(){this.scene._beforeCameraUpdateStage.registerStep(zt.STEP_BEFORECAMERAUPDATE_GAMEPAD,this,this._beforeCameraUpdate)}rebuild(){}dispose(){const e=this.scene._gamepadManager;e&&(e.dispose(),this.scene._gamepadManager=null)}_beforeCameraUpdate(){const e=this.scene._gamepadManager;e&&e._isMonitoring&&e._checkGamepadsStatus()}}const ks=Object.freeze(new qe(0,0,0,0)),Gs=Object.freeze(Ye.Zero()),zs=Object.freeze(He.Zero()),Xs=Object.freeze(Ei.Zero()),Ws=Object.freeze(tt.Black());class Hs{constructor(e,t,i,n){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._ratioOffset=0,this._previousDelay=0,this._previousRatio=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=n,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===Fn.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=Qe.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,0!==this._minFrame){const e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(const t of this._target)this._preparePath(t,e),this._getOriginalValues(e),e++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const r=t.getEvents();r&&r.length>0&&r.forEach((e=>{this._events.push(e._clone())})),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}_preparePath(e,t=0){const i=this._animation.targetPropertyPath;if(i.length>1){let n=e[i[0]];for(let e=1;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let i=0;it[t.length-1].frame&&(e=t[t.length-1].frame);const i=this._events;if(i.length)for(let t=0;tthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const h=i-t;let c;const u=e*(a.framePerSecond*r)/1e3+this._ratioOffset;let d,f=0;if(this._previousDelay=e,this._previousRatio=u,!n&&i>=t&&u>=h)l=!1,f=a._getKeyValue(this._maxValue);else if(!n&&t>=i&&u<=h)l=!1,f=a._getKeyValue(this._minValue);else if(this._animationState.loopMode!==Fn.ANIMATIONLOOPMODE_CYCLE){const e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=Fn.ANIMATIONLOOPMODE_CYCLE;const n=a._interpolate(t,this._animationState),r=a._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),a.dataType){case Fn.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=r-n;break;case Fn.ANIMATIONTYPE_QUATERNION:case Fn.ANIMATIONTYPE_VECTOR3:case Fn.ANIMATIONTYPE_VECTOR2:case Fn.ANIMATIONTYPE_SIZE:case Fn.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=r.subtract(n)}this._highLimitsCache[e]=r}f=this._highLimitsCache[e],c=this._offsetsCache[e]}if(void 0===c)switch(a.dataType){case Fn.ANIMATIONTYPE_FLOAT:c=0;break;case Fn.ANIMATIONTYPE_QUATERNION:c=ks;break;case Fn.ANIMATIONTYPE_VECTOR3:c=Gs;break;case Fn.ANIMATIONTYPE_VECTOR2:c=zs;break;case Fn.ANIMATIONTYPE_SIZE:c=Xs;break;case Fn.ANIMATIONTYPE_COLOR3:c=Ws}if(this._host&&this._host.syncRoot){const e=this._host.syncRoot;d=t+(i-t)*((e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame))}else d=u>0&&t>i||u<0&&t0&&this.currentFrame>d||r<0&&this.currentFrame0?0:a.getKeys().length-1}this._currentFrame=d,this._animationState.repeatCount=0===h?0:u/h>>0,this._animationState.highLimitValue=f,this._animationState.offsetValue=c;const p=a._interpolate(d,this._animationState);if(this.setValue(p,s),_.length)for(let e=0;e<_.length;e++)if(h>0&&d>=_[e].frame&&_[e].frame>=t||h<0&&d<=_[e].frame&&_[e].frame<=t){const t=_[e];t.isDone||(t.onlyOnce&&(_.splice(e,1),e--),t.isDone=!0,t.action(d))}return l||(this._stopped=!0),l}}class Ys extends Mi{constructor(e,t,i=null,n=null,r=null,s=null,a=null){super(e,t.getScene()),this.name=e,this.children=new Array,this.animations=new Array,this._index=null,this._absoluteTransform=new Qe,this._invertedAbsoluteTransform=new Qe,this._scalingDeterminant=1,this._worldTransform=new Qe,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=n?n.clone():Qe.Identity(),this._restPose=r||this._localMatrix.clone(),this._baseMatrix=s||this._localMatrix.clone(),this._index=a,t.bones.push(this),this.setParent(i,!1),(s||n)&&this._updateDifferenceMatrix()}get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){this._needToCompose=!1,e.updateFlag!==this._localMatrix.updateFlag&&(this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}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=Ze.Vector3[0],i=Ze.Quaternion[0],n=Ze.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:qe.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=Ye.Zero(),this._localRotation=qe.Zero(),this._localPosition=Ye.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,Qe.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-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(r)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const n=this._runtimeAnimations;for(let i=n.length-1;i>=0;i--){const r=n[i];e&&r.animation.name!=e||t&&!t(r.target)||(r.dispose(),n.splice(i,1))}0==n.length&&(this._scene._activeAnimatables.splice(i,1),this._raiseOnAnimationEnd())}}else{const e=this._scene._activeAnimatables.indexOf(this);if(e>-1){this._scene._activeAnimatables.splice(e,1);const t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add((()=>{e(this)}),void 0,void 0,this,!0)}))}_animate(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;let t=!1;const i=this._runtimeAnimations;let n;for(n=0;n0)return;this._animationTimeLast=e}this.deltaTime=this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;const t=this._activeAnimatables;if(0===t.length)return;this._animationTime+=this.deltaTime;const i=this._animationTime;for(let e=0;ei&&r>0&&(r*=-1),o&&this.stopAnimation(e,void 0,l),a||(a=new Ks(this,e,t,i,n,r,s,void 0,h,c));const u=!l||l(e);if(e.animations&&u&&a.appendAnimations(e,e.animations),e.getAnimatables){const c=e.getAnimatables();for(let e=0;en&&s>0)s*=-1;else if(n>i&&s<0){const e=n;n=i,i=e}return new Ks(this,e,i,n,r,s,a,t,o,l)},mi.prototype.beginDirectHierarchyAnimation=function(e,t,i,n,r,s,a,o,l,h=!1){const c=e.getDescendants(t),u=[];u.push(this.beginDirectAnimation(e,i,n,r,s,a,o,l,h));for(const e of c)u.push(this.beginDirectAnimation(e,i,n,r,s,a,o,l,h));return u},mi.prototype.getAnimatableByTarget=function(e){for(let t=0;t0?l:-l,r),o.scaleAndAddToRef(l,i)}r.normalize()}for(let t=0;t0)r.copyFrom(n);else if(1===e.animations.length){if(qe.SlerpToRef(n,i.currentValue,Math.min(1,e.totalWeight),r),0===e.totalAdditiveWeight)return r}else if(e.animations.length>1){let i,s,a=1;if(e.totalWeight<1){const t=1-e.totalWeight;i=[],s=[],i.push(n),s.push(t)}else{if(2===e.animations.length&&(qe.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],s=[],a=e.totalWeight}for(let t=0;t=a&&m.frame<=o&&(n?(v=m.value.clone(),d?(g=v.getTranslation(),v.setTranslation(g.scaleInPlace(f))):_&&r?(g=v.getTranslation(),v.setTranslation(g.multiplyInPlace(r))):v=m.value):v=m.value,p.push({frame:m.frame+i,value:v}));return this.animations[0].createRange(t,a+i,o+i),!0};class qs{constructor(e,t,i,n,r){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=n,this.createRenderTargetTextureProvider=r}get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}}class Qs{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new o(this._engine,s.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new z(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,n,r,s){if(!this._engine)throw new Error("Engine is disposed");const a={width:e,height:t},o=s?new fs(this._scene,a):new dr("XR renderTargetTexture",a,this._scene),l=o.renderTarget;if(l._samples=o.samples,!i&&n||(l._framebuffer=i),n)if(s)l._colorTextureArray=n;else{const e=this._createInternalTexture(a,n);l.setTexture(e,0),o._texture=e}return r&&(s?l._depthStencilTextureArray=r:l._depthStencilTexture=this._createInternalTexture(a,r)),o.disableRescaling(),"undefined"!=typeof XRWebGLBinding&&(o.skipInitialClear=!0),this._renderTargetTextures.push(o),o}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.length=0}}class js extends qs{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new Zs(e.scene,this))),this.layer=e}}class Zs extends Qs{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const n=this._framebufferDimensions.framebufferWidth,r=this._framebufferDimensions.framebufferHeight;return e.x=i.x/n,e.y=i.y/r,e.width=i.width/n,e.height=i.height/r,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,n=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&n===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,n),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=n),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class Js{static GetDefaults(e){const t=new Js;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class $s{constructor(e,t=Js.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new n,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add((()=>{this._addCanvas()})),e.onXRSessionEnded.add((()=>{this._removeCanvas()}))}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new js(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then((()=>{}),(()=>{Pe.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")})).then((()=>t())):Promise.resolve(t())}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce((()=>{this._setCanvasSize(!0)}))}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class ea extends qs{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new ta(e,this))),this.layer=e}}class ta extends Qs{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}}class ia{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}}class na{constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new n,this.onXRReferenceSpaceChanged=new n,this.onXRSessionEnded=new n,this.onXRSessionInit=new n,this.inXRFrameLoop=!1,this.inXRSession=!1,this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){var e;this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),null===(e=this._engine)||void 0===e||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}exitXRAsync(){return this.session&&this.inXRSession?(this.inXRSession=!1,this.session.end().catch((()=>{p.Warn("Could not end XR session.")}))):Promise.resolve()}trySetViewportForView(e,t){var i;return(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.trySetViewportForView(e,t))||!1}getRenderTargetTextureForEye(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForEye(e))||null}getRenderTargetTextureForView(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForView(e))||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new ia(this):((e=e||Js.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new $s(this,e))}initializeAsync(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then((t=>(this.session=t,this._sessionMode=e,this.onXRSessionInit.notifyObservers(t),this.inXRSession=!0,this.session.addEventListener("end",(()=>{var e;this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&(null===(e=this._baseLayerRTTProvider)||void 0===e||e.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null}),{once:!0}),this.session)))}isSessionSupportedAsync(e){return na.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){var e;this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:this.session.requestAnimationFrame.bind(this.session),renderFunction:(e,t)=>{var i;this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t&&(this.inXRFrameLoop=!0,this._engine.framebufferDimensionsObject=(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.getFramebufferDimensions())||null,this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1))}},this._engine.framebufferDimensionsObject=(null===(e=this._baseLayerRTTProvider)||void 0===e?void 0:e.getFramebufferDimensions())||null,"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then((e=>e),(e=>(p.Error("XR.requestReferenceSpace failed for the following reason: "),p.Error(e),p.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then((e=>{const t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)}),(e=>{throw p.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))))).then((e=>this.session.requestReferenceSpace("viewer").then((t=>(this.viewerReferenceSpace=t,e))))).then((e=>(this.referenceSpace=this.baseReferenceSpace=e,this.referenceSpace)))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){var t,i;this.isNative&&(null===(t=this._baseLayerRTTProvider)||void 0===t||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=(null===(i=this._baseLayerWrapper)||void 0===i?void 0:i.createRenderTargetTextureProvider(this))||null}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new ea(e.baseLayer):new js(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);const t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then((e=>{const t=void 0===e||e;return Promise.resolve(t)})).catch((e=>(p.Warn(e),Promise.resolve(!1)))):Promise.resolve(!1)}get isNative(){var e;return null!==(e=this._xrNavigator.xr.native)&&void 0!==e&&e}get currentFrameRate(){var e;return null===(e=this.session)||void 0===e?void 0:e.frameRate}get supportedFrameRates(){var e;return null===(e=this.session)||void 0===e?void 0:e.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():!this.inXRSession&&t||this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.isFixedFoveationSupported)||!1}get fixedFoveation(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.fixedFoveation)||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}}var ra,sa;function aa(e){const t=e.height||2;let i=0===e.diameterTop?0:e.diameterTop||e.diameter||1,n=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;i=i||1e-5,n=n||1e-5;const r=e.tessellation||24,s=e.subdivisions||1,a=!!e.hasRings,o=!!e.enclose,l=0===e.cap?0:e.cap||gn.CAP_ALL,h=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,c=0===e.sideOrientation?0:e.sideOrientation||Li.DEFAULTSIDE,u=e.faceUV||new Array(3),d=e.faceColors,f=2+(1+(1!==h&&o?2:0))*(a?s:1);let _;for(_=0;_{const s=e?i/2:n/2;if(0===s)return;let a,o,l;const c=e?u[f-1]:u[0];let _=null;d&&(_=e?d[f-1]:d[0]);const T=m.length/3,C=e?t/2:-t/2,R=new Ye(0,C,0);m.push(R.x,R.y,R.z),g.push(0,e?1:-1,0);const A=c.y+.5*(c.w-c.y);v.push(c.x+.5*(c.z-c.x),bi.UseOpenGLOrientationForUV?1-A:A),_&&E.push(_.r,_.g,_.b,_.a);const b=new He(.5,.5);for(l=0;l<=r;l++){a=2*Math.PI*l*h/r;const t=Math.cos(-a),i=Math.sin(-a);o=new Ye(t*s,C,i*s);const n=new He(t*b.x+.5,i*b.y+.5);m.push(o.x,o.y,o.z),g.push(0,e?1:-1,0);const u=c.y+(c.w-c.y)*n.y;v.push(c.x+(c.z-c.x)*n.x,bi.UseOpenGLOrientationForUV?1-u:u),_&&E.push(_.r,_.g,_.b,_.a)}for(l=0;l(void 0!==a&&a instanceof mi||(void 0!==a&&(l=o||gn.DEFAULTSIDE,o=a),a=s,s=1),oa(e,{height:t,diameterTop:i,diameterBottom:n,tessellation:r,subdivisions:s,sideOrientation:l,updatable:o},a)),Li.CreateTorus=la,gn.CreateTorus=(e,t,i,n,r,s,a)=>ha(e,{diameter:t,thickness:i,tessellation:n,sideOrientation:a,updatable:s},r),gn._GroundMeshParser=(e,t)=>ca.Parse(e,t);class ca extends gn{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),n=Ze.Matrix[5];i.invertToRef(n);const r=Ze.Vector3[8];if(Ye.TransformCoordinatesFromFloatsToRef(e,0,t,n,r),e=r.x,t=r.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const s=this._getFacetAt(e,t),a=-(s.x*e+s.z*t+s.w)/s.y;return Ye.TransformCoordinatesFromFloatsToRef(0,a,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new Ye(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const n=this.getWorldMatrix(),r=Ze.Matrix[5];n.invertToRef(r);const s=Ze.Vector3[8];if(Ye.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const a=this._getFacetAt(e,t);return Ye.TransformNormalFromFloatsToRef(a.x,a.y,a.z,n,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),n=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[n*this._subdivisionsX+i];let s;return s=te.maxHeight){h=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(s=0;s<=e.subdivisions;s++)for(a=0;a<=e.subdivisions;a++){const t=new Ye(a*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-s)*e.height/e.subdivisions-e.height/2),c=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[c]/255,d=e.buffer[c+1]/255,f=e.buffer[c+2]/255;const _=e.buffer[c+3]/255;h&&(u=1-u,d=1-d,f=1-f);const p=u*o.r+d*o.g+f*o.b;t.y=_>=l?e.minHeight+(e.maxHeight-e.minHeight)*p:e.minHeight-ke,i.push(t.x,t.y,t.z),n.push(0,0,0),r.push(a/e.subdivisions,1-s/e.subdivisions)}for(s=0;s=e.minHeight,c=i[3*r+1]>=e.minHeight,u=i[3*o+1]>=e.minHeight;h&&c&&u&&(t.push(n),t.push(r),t.push(o)),i[3*l+1]>=e.minHeight&&h&&u&&(t.push(l),t.push(n),t.push(o))}Li.ComputeNormals(i,t,n);const c=new Li;return c.indices=t,c.positions=i,c.normals=n,c.uvs=r,c}function _a(e,t={},i){const n=new ca(e,i);return n._setReady(!1),n._subdivisionsX=t.subdivisionsX||t.subdivisions||1,n._subdivisionsY=t.subdivisionsY||t.subdivisions||1,n._width=t.width||1,n._height=t.height||1,n._maxX=n._width/2,n._maxZ=n._height/2,n._minX=-n._maxX,n._minZ=-n._maxZ,ua(t).applyToMesh(n,t.updatable),n._setReady(!0),n}Li.CreateGround=ua,Li.CreateTiledGround=da,Li.CreateGroundFromHeightMap=fa,gn.CreateGround=(e,t,i,n,r,s)=>_a(e,{width:t,height:i,subdivisions:n,updatable:s},r),gn.CreateTiledGround=(e,t,i,n,r,s,a,o,l)=>function(e,t,i=null){const n=new gn(e,i);return da(t).applyToMesh(n,t.updatable),n}(e,{xmin:t,zmin:i,xmax:n,zmax:r,subdivisions:s,precision:a,updatable:l},o),gn.CreateGroundFromHeightMap=(e,t,i,n,r,s,a,o,l,h,c)=>function(e,t,i={},n=null){const r=i.width||10,s=i.height||10,a=i.subdivisions||1,o=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new tt(.3,.59,.11),c=i.alphaFilter||0,u=i.updatable,d=i.onReady;n=n||f.LastCreatedScene;const _=new ca(e,n);return _._subdivisionsX=a,_._subdivisionsY=a,_._width=r,_._height=s,_._maxX=_._width/2,_._maxZ=_._height/2,_._minX=-_._maxX,_._minZ=-_._maxZ,_._setReady(!1),Pe.LoadImage(t,(e=>{const t=e.width,i=e.height;if(n.isDisposed)return;const f=null==n?void 0:n.getEngine().resizeImageBitmap(e,t,i);fa({width:r,height:s,subdivisions:a,minHeight:o,maxHeight:l,colorFilter:h,buffer:f,bufferWidth:t,bufferHeight:i,alphaFilter:c}).applyToMesh(_,u),d&&d(_),_._setReady(!0)}),(()=>{}),n.offlineProvider),_}(e,t,{width:i,height:n,subdivisions:r,minHeight:s,maxHeight:a,updatable:l,onReady:h,alphaFilter:c},o);class pa{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=pa._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=ha("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const t=new er("targetMat",e);t.specularColor=tt.Black(),t.emissiveColor=new tt(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new Cs(Ye.Zero(),new Ye(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}}pa._IdCounter=0;class ma extends pa{constructor(e,t,i){super(t,i),this.webVRController=e,this._laserPointer=oa("laserPointer",{updatable:!1,height:1,diameterTop:.004,diameterBottom:2e-4,tessellation:20,subdivisions:1},t);const n=new er("laserPointerMat",t);if(n.emissiveColor=new tt(.7,.7,.7),n.alpha=.6,this._laserPointer.material=n,this._laserPointer.rotation.x=Math.PI/2,this._laserPointer.position.z=-.5,this._laserPointer.isVisible=!1,this._laserPointer.isPickable=!1,!e.mesh){const i=new gn("preloadControllerMesh",t),n=new gn(Is.POINTING_POSE,t);n.rotation.x=-.7,i.addChild(n),e.attachToMesh(i)}this._setLaserPointerParent(e.mesh),this._meshAttachedObserver=e._meshAttachedObservable.add((e=>{this._setLaserPointerParent(e)}))}_getForwardRay(e){return this.webVRController.getForwardRay(e)}_activatePointer(){super._activatePointer(),this._laserPointer.isVisible=!0}_deactivatePointer(){super._deactivatePointer(),this._laserPointer.isVisible=!1}_setLaserPointerColor(e){this._laserPointer.material.emissiveColor=e}_setLaserPointerLightingDisabled(e){this._laserPointer.material.disableLighting=e}_setLaserPointerParent(e){const t=e=>{e.isPickable=!1,e.getChildMeshes().forEach((e=>{t(e)}))};t(e);const i=e.getChildren(void 0,!1);let n=e;this.webVRController._pointingPoseNode=null;for(let e=0;e=0){n=i[e],this.webVRController._pointingPoseNode=n;break}this._laserPointer.parent=n}_updatePointerDistance(e=100){this._laserPointer.scaling.y=e,this._laserPointer.position.z=-e/2}dispose(){super.dispose(),this._laserPointer.dispose(),this._meshAttachedObserver&&this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)}}class ga extends pa{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new Cs(Ye.Zero(),Ye.Forward())}}class va{constructor(e,t={}){if(this.webVROptions=t,this._webVRsupported=!1,this._webVRready=!1,this._webVRrequesting=!1,this._webVRpresenting=!1,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new n,this.onAfterEnteringVRObservable=new n,this.onExitingVRObservable=new n,this.onControllerMeshLoadedObservable=new n,this._useCustomVRButton=!1,this._teleportationRequested=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=va.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new Ye(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new Ye(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._leftController=null,this._rightController=null,this._gazeColor=new tt(.7,.7,.7),this._laserColor=new tt(.7,.7,.7),this._pickedLaserColor=new tt(.2,.2,1),this._pickedGazeColor=new tt(0,0,1),this.onNewMeshSelected=new n,this.onMeshSelectedWithController=new n,this.onNewMeshPicked=new n,this.onBeforeCameraTeleport=new n,this.onAfterCameraTeleport=new n,this.onSelectedMeshUnselected=new n,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._interactionsRequested=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight(),this._fullscreenVRpresenting&&this._webVRready&&this.exitVR()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._leftController&&this._leftController._activePointer&&this._castRayAndSelectObject(this._leftController),this._rightController&&this._rightController._activePointer&&this._castRayAndSelectObject(this._rightController),this._noControllerIsActive&&(this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock)?this._castRayAndSelectObject(this._cameraGazer):this._cameraGazer._gazeTracker.isVisible=!1},this._onNewGamepadConnected=e=>{if(e.type!==Es.POSE_ENABLED)e.leftStick&&e.onleftstickchanged((e=>{this._teleportationInitialized&&this.teleportationEnabled&&(!this._leftController&&!this._rightController||this._leftController&&!this._leftController._activePointer&&this._rightController&&!this._rightController._activePointer)&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))})),e.rightStick&&e.onrightstickchanged((e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)})),e.type===Es.XBOX&&(e.onbuttondown((e=>{this._interactionsEnabled&&e===As.A&&this._cameraGazer._selectionPointerDown()})),e.onbuttonup((e=>{this._interactionsEnabled&&e===As.A&&this._cameraGazer._selectionPointerUp()})));else{const t=e,i=new ma(t,this._scene,this._cameraGazer._gazeTracker);"right"===t.hand||this._leftController&&this._leftController.webVRController!=t?this._rightController=i:this._leftController=i,this._tryEnableInteractionOnController(i)}},this._tryEnableInteractionOnController=e=>{this._interactionsRequested&&!e._interactionsEnabled&&this._enableInteractionOnController(e),this._teleportationRequested&&!e._teleportationEnabled&&this._enableTeleportationOnController(e)},this._onNewGamepadDisconnected=e=>{e instanceof Ms&&("left"===e.hand&&null!=this._leftController&&(this._leftController.dispose(),this._leftController=null),"right"===e.hand&&null!=this._rightController&&(this._rightController.dispose(),this._rightController=null))},this._workingVector=Ye.Zero(),this._workingQuaternion=qe.Identity(),this._workingMatrix=Qe.Identity(),p.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement(),"getVRDisplays"in navigator||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),void 0===t.defaultHeight&&(t.defaultHeight=1.7),t.useCustomVRButton&&(this._useCustomVRButton=!0,t.customVRButton&&(this._btnVR=t.customVRButton)),t.rayLength&&(this._rayLength=t.rayLength),this._defaultHeight=t.defaultHeight,t.positionScale&&(this._rayLength*=t.positionScale,this._defaultHeight*=t.positionScale),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new Ye(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new cs("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof Bn&&this._scene.activeCamera.rotation)){const e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(qe.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?na.IsSessionSupportedAsync("immersive-vr").then((i=>{i?(p.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then((t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new ga((()=>this.xr.baseExperience.camera),e),this.xr.baseExperience.onStateChangedObservable.add((e=>{switch(e){case ra.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case ra.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case ra.IN_XR:this._hasEnteredVR=!0;break;case ra.NOT_IN_XR:this._hasEnteredVR=!1}}))}))):this._completeVRInit(e,t)})):this._completeVRInit(e,t)}get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get onControllerMeshLoaded(){return this.onControllerMeshLoadedObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._leftController&&this._leftController._gazeTracker&&this._leftController._gazeTracker.dispose(),this._rightController&&this._rightController._gazeTracker&&this._rightController._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker",this._leftController&&(this._leftController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")),this._rightController&&(this._rightController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")))}get leftControllerGazeTrackerMesh(){return this._leftController?this._leftController._gazeTracker:null}get rightControllerGazeTrackerMesh(){return this._rightController?this._rightController._gazeTracker:null}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1))}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e,e?(this._rightController&&this._rightController._activatePointer(),this._leftController&&this._leftController._activatePointer()):(this._rightController&&(this._rightController._deactivatePointer(),this._rightController._gazeTracker.isVisible=!1),this._leftController&&(this._leftController._deactivatePointer(),this._leftController._gazeTracker.isVisible=!1))}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._webVRready?this._webVRCamera:this._scene.activeCamera}get webVRCamera(){return this._webVRCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated||null!==this._leftController&&this._leftController._teleportationRequestInitiated||null!==this._rightController&&this._rightController._teleportationRequestInitiated}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(t.useMultiview&&(t.vrDeviceOrientationCameraMetrics||(t.vrDeviceOrientationCameraMetrics=us.GetDefault()),t.vrDeviceOrientationCameraMetrics.multiviewEnabled=!0),this._vrDeviceOrientationCamera=new vs("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._webVRCamera=new ys("WebVRHelper",this._position,this._scene,t),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new ga((()=>this.currentVRCamera),e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let e=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";e+=".babylonVRicon.vrdisplaypresenting { display: none; }";const t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(()=>{this.isInVRMode?this._scene.getEngine().disableVR():this.enterVR()}));const i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera?this._displayVRButton():this._scene.getEngine().onVRDisplayChangedObservable.add((e=>{e.vrDisplay&&this._displayVRButton()})),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())}),Wt.POINTERDOUBLETAP,!1),this._onVRDisplayChangedBind=e=>this._onVRDisplayChanged(e),this._onVrDisplayPresentChangeBind=()=>this._onVrDisplayPresentChange(),this._onVRRequestPresentStart=()=>{this._webVRrequesting=!0,this._updateButtonVisibility()},this._onVRRequestPresentComplete=()=>{this._webVRrequesting=!1,this._updateButtonVisibility()},e.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChangedBind),e.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),e.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),i.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),e.onDisposeObservable.add((()=>{this.dispose()})),this._webVRCamera.onControllerMeshLoadedObservable.add((e=>this._onDefaultMeshLoaded(e))),this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected),this._updateButtonVisibility(),this._circleEase=new Mn,this._circleEase.setEasingMode(yn.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add((t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===Wt.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===Wt.POINTERUP&&this._cameraGazer._selectionPointerUp())})),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}_onDefaultMeshLoaded(e){this._leftController&&this._leftController.webVRController==e&&e.mesh&&this._leftController._setLaserPointerParent(e.mesh),this._rightController&&this._rightController.webVRController==e&&e.mesh&&this._rightController._setLaserPointerParent(e.mesh);try{this.onControllerMeshLoadedObservable.notifyObservers(e)}catch(e){p.Warn("Error in your custom logic onControllerMeshLoaded: "+e)}}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===ra.IN_XR||this._webVRpresenting||this._fullscreenVRpresenting}_onVrDisplayPresentChange(){const e=this._scene.getEngine().getVRDevice();if(e){const t=this._webVRpresenting;this._webVRpresenting=e.isPresenting,t&&!this._webVRpresenting&&this.exitVR()}else p.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");this._updateButtonVisibility()}_onVRDisplayChanged(e){this._webVRsupported=e.vrSupported,this._webVRready=!!e.vrDisplay,this._webVRpresenting=e.vrDisplay&&e.vrDisplay.isPresenting,this._updateButtonVisibility()}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){const e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode?this._btnVR.className+=" vrdisplaypresenting":(this._webVRready&&(this._btnVR.className+=" vrdisplayready"),this._webVRsupported&&(this._btnVR.className+=" vrdisplaysupported"),this._webVRrequesting&&(this._btnVR.className+=" vrdisplayrequesting")))}enterVR(){if(this.xr)this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){p.Warn("Error in your custom logic onEnteringVR: "+e)}if(this._scene.activeCamera){if(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=qe.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this.webVRCamera){const e=this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y,t=qe.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y-e,i=this.webVRCamera.rotationQuaternion.toEulerAngles().y;this.webVRCamera.rotationQuaternion=qe.FromEulerAngles(0,i+t,0)}this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)}this._webVRrequesting||(this._webVRready?this._webVRpresenting||(this._scene.getEngine().onVRRequestPresentComplete.addOnce((e=>{this.onAfterEnteringVRObservable.notifyObservers({success:e})})),this._webVRCamera.position=this._position,this._scene.activeCamera=this._webVRCamera):this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce((()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})}))),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._displayLaserPointer&&[this._leftController,this._rightController].forEach((e=>{e&&e._activatePointer()})),this._hasEnteredVR=!0)}}exitVR(){if(this.xr)this.xr.baseExperience.exitXRAsync();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){p.Warn("Error in your custom logic onExitingVR: "+e)}this._webVRpresenting&&this._scene.getEngine().disableVR(),this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1)),this._scene.getEngine().resize(),[this._leftController,this._rightController].forEach((e=>{e&&e._deactivatePointer()})),this._hasEnteredVR=!1;const e=this._scene.getEngine();e._onVrDisplayPresentChange&&e._onVrDisplayPresentChange()}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this._interactionsRequested=!0,this.xr)return void(this.xr.baseExperience.state===ra.IN_XR&&this.xr.pointerSelection.attach());this._leftController&&this._enableInteractionOnController(this._leftController),this._rightController&&this._enableInteractionOnController(this._rightController),this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>!!(this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}get _noControllerIsActive(){return!(this._leftController&&this._leftController._activePointer||this._rightController&&this._rightController._activePointer)}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e))}removeFloorMesh(e){if(!this._floorMeshesCollection)return;const t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this._teleportationRequested=!0,this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const t=e.floorMeshes||[];if(!t.length){const i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr)return t.forEach((e=>{this.xr.teleportation.addFloorMesh(e)})),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){const t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};return void this._scene.registerBeforeRender(t)}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction),null!=this._leftController&&this._enableTeleportationOnController(this._leftController),null!=this._rightController&&this._enableTeleportationOnController(this._rightController);const t=new bt;t.vignetteColor=new it(0,0,0,0),t.vignetteEnabled=!0,this._postProcessMove=new Ds("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,t),this._webVRCamera.detachPostProcess(this._postProcessMove),this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&(this._createTeleportationCircles(),this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))}}_enableInteractionOnController(e){e.webVRController.mesh&&(e._interactionsEnabled=!0,this.isInVRMode&&this._displayLaserPointer&&e._activatePointer(),this.webVROptions.laserToggle&&e.webVRController.onMainButtonStateChangedObservable.add((t=>{this._displayLaserPointer&&1===t.value&&(e._activePointer?e._deactivatePointer():e._activatePointer(),this.displayGaze&&(e._gazeTracker.isVisible=e._activePointer))})),e.webVRController.onTriggerStateChangedObservable.add((t=>{let i=e;this._noControllerIsActive&&(i=this._cameraGazer),i._pointerDownOnMeshAsked?t.valuethis._padSensibilityUp&&i._selectionPointerDown()})))}_checkTeleportWithRay(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;let e=qe.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;this.currentVRCamera.devicePosition&&this.currentVRCamera.deviceRotationQuaternion&&(e=this.currentVRCamera.deviceRotationQuaternion,i=this.currentVRCamera.devicePosition),e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,qe.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),Ye.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const n=new Cs(i,this._workingVector),r=this._scene.pickWithRay(n,this._raySelectionPredicate);r&&r.pickedPoint&&r.pickedMesh&&this._isTeleportationFloor(r.pickedMesh)&&r.distance<5&&this.teleportCamera(r.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_enableTeleportationOnController(e){e.webVRController.mesh&&(e._interactionsEnabled||this._enableInteractionOnController(e),e._interactionsEnabled=!0,e._teleportationEnabled=!0,e.webVRController.controllerType===Rs.VIVE&&(e._dpadPressed=!1,e.webVRController.onPadStateChangedObservable.add((t=>{e._dpadPressed=t.pressed,e._dpadPressed||(e._rotationLeftAsked=!1,e._rotationRightAsked=!1,e._teleportationBackRequestInitiated=!1)}))),e.webVRController.onPadValuesChangedObservable.add((t=>{this.teleportationEnabled&&(this._checkTeleportBackwards(t,e),this._checkTeleportWithRay(t,e)),this._checkRotate(t,e)})))}_createTeleportationCircles(){this._teleportationTarget=_a("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=new Os("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;const t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();const i=new er("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;const n=ha("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);n.isPickable=!1,n.parent=this._teleportationTarget;const r=new Fn("animationInnerCircle","position.y",30,Fn.ANIMATIONTYPE_FLOAT,Fn.ANIMATIONLOOPMODE_CYCLE),s=[];s.push({frame:0,value:0}),s.push({frame:30,value:.4}),s.push({frame:60,value:0}),r.setKeys(s);const a=new On;a.setEasingMode(yn.EASINGMODE_EASEINOUT),r.setEasingFunction(a),n.animations=[],n.animations.push(r),this._scene.beginAnimation(n,0,60,!0),this._hideTeleportationTarget()}_displayTeleportationTarget(){this._teleportActive=!0,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!0,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!0))}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof ls))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=qe.FromRotationMatrix(Qe.RotationY(Math.PI/4*this._rotationAngle)),i=new Fn("animationRotation","rotationQuaternion",90,Fn.ANIMATIONTYPE_QUATERNION,Fn.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),n.push({frame:6,value:t}),i.setKeys(n),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const r=new Fn("animationPP","vignetteWeight",90,Fn.ANIMATIONTYPE_FLOAT,Fn.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:0}),s.push({frame:3,value:4}),s.push({frame:6,value:0}),r.setKeys(s),r.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(r);const a=new Fn("animationPP2","vignetteStretch",90,Fn.ANIMATIONTYPE_FLOAT,Fn.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:3,value:10}),o.push({frame:6,value:0}),a.setKeys(o),a.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(a),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,6,!1,1,(()=>{this._webVRCamera.detachPostProcess(this._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}_moveTeleportationSelectorTo(e,t,i){if(e.pickedPoint){t._teleportationRequestInitiated&&(this._displayTeleportationTarget(),this._haloCenter.copyFrom(e.pickedPoint),this._teleportationTarget.position.copyFrom(e.pickedPoint));const n=this._convertNormalToDirectionOfRay(e.getNormal(!0,!1),i);if(n){const e=Ye.Cross(gi.Y,n),t=Ye.Cross(n,e);Ye.RotationFromAxisToRef(t,n,e,this._teleportationTarget.rotation)}this._teleportationTarget.position.y+=.1}}teleportCamera(e){if(!(this.currentVRCamera instanceof ls))return;let t,i;if(this.webVRCamera.leftCamera?(this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition),this._workingVector.subtractInPlace(this.webVRCamera.position),e.subtractToRef(this._workingVector,this._workingVector)):this._workingVector.copyFrom(e),this.isInVRMode?this._workingVector.y+=this.webVRCamera.deviceDistanceToRoomGround()*this._webVRCamera.deviceScaleFactor:this._workingVector.y+=this._defaultHeight,this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==va.TELEPORTATIONMODE_CONSTANTSPEED){i=90;const e=Ye.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];const n=new Fn("animationCameraTeleportation","position",90,Fn.ANIMATIONTYPE_VECTOR3,Fn.ANIMATIONLOOPMODE_CONSTANT),r=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];n.setKeys(r),n.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(n),this._postProcessMove.animations=[];const s=Math.round(i/2),a=new Fn("animationPP","vignetteWeight",90,Fn.ANIMATIONTYPE_FLOAT,Fn.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:s,value:8}),o.push({frame:i,value:0}),a.setKeys(o),this._postProcessMove.animations.push(a);const l=new Fn("animationPP2","vignetteStretch",90,Fn.ANIMATIONTYPE_FLOAT,Fn.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:s,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,i,!1,t,(()=>{this._webVRCamera.detachPostProcess(this._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,(()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)})),this._hideTeleportationTarget()}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(Ye.Dot(e,t.direction))>8)}static _GetRGBArrayBuffer(e,t,i,n,r,s,a,o){const l=new Uint8Array(n),h=new Uint8Array(r,i);let c=0;for(let i=0;i>8&255,S>>16&255,S>>24&255)))}var S;const I=Ia._ExtractLongWordOrder(u[23]),x=Ia._ExtractLongWordOrder(u[24]),y=Ia._ExtractLongWordOrder(u[25]),M=Ia._ExtractLongWordOrder(u[26]);b&&(C=e._getRGBABufferInternalSizedFormat(n.textureType)),v=1,u[2]&Ea&&!1!==r&&(v=Math.max(1,u[7]));const P=o||0,O=e.getCaps();for(let r=P;r0?n.sphericalPolynomial=Pr.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}}Ia.StoreLODInAlphaChannel=!1,K.prototype.createPrefilteredCubeTexture=function(e,t,i,n,r=null,a=null,l,h=null,c=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(r&&r(null));const a=e.texture;if(c?e.info.sphericalPolynomial&&(a._sphericalPolynomial=e.info.sphericalPolynomial):a._sphericalPolynomial=new yr,a._source=s.CubePrefiltered,this.getCaps().textureLOD)return void(r&&r(a));const l=this._gl,h=e.width;if(!h)return;const u=[];for(let r=0;r<3;r++){const c=1-r/2,d=n,f=Be.Log2(h)*i+n,_=d+(f-d)*c,m=Math.round(Math.min(Math.max(_,0),f)),g=new o(this,s.Temp);if(g.type=a.type,g.format=a.format,g.width=Math.pow(2,Math.max(Be.Log2(h)-m,0)),g.height=g.width,g.isCube=!0,g._cachedWrapU=0,g._cachedWrapV=0,this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,g,!0),g.samplingMode=2,l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,l.LINEAR),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,l.LINEAR),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),e.isDDS){const t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),Ia.UploadDDSLevels(this,g,i,t,!0,6,m)}else p.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null);const v=new Ri(t);v._isCube=!0,v._texture=g,g.isReady=!0,u.push(v)}a._lodTextureHigh=u[2],a._lodTextureMid=u[1],a._lodTextureLow=u[0],r&&r(a)}),a,l,h,c,i,n)},Z._TextureLoaders.push(new class{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,n){const r=t.getEngine();let s,a=!1,o=1e3;if(Array.isArray(e))for(let i=0;i1)&&t.generateMipMaps,r._unpackFlipY(s.isCompressed),Ia.UploadDDSLevels(r,t,n,s,a,6,-1,i),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:r.generateMipMapsForCubemap(t)}else{const n=e;s=Ia.GetDDSInfo(n),t.width=s.width,t.height=s.height,i&&(s.sphericalPolynomial=new yr),a=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(s.isCompressed),Ia.UploadDDSLevels(r,t,n,s,a,6),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:r.generateMipMapsForCubemap(t,!1)}r._setCubeMapTextureParams(t,a,o),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n({isDDS:!0,width:t.width,info:s,data:e,texture:t})}loadData(e,t,i){const n=Ia.GetDDSInfo(e),r=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps&&n.width>>n.mipmapCount-1==1;i(n.width,n.height,r,n.isFourCC,(()=>{Ia.UploadDDSLevels(t.getEngine(),t,e,n,r,1)}))}});P.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}";const xa="image/png",ya=[134,22,135,150,246,214,150,54];function Ma(e){if(e.version>2)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "2".`);return 2===e.version?e:e={...e,version:2,imageType:xa}}function Pa(e,t,i){const n=(i=Ma(i)).specular;return n?(e._lodGenerationScale=n.lodGenerationScale,function(e,t,i=xa){if(!Pe.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");const n=Be.ILog2(e.width)+1,r=e.getEngine();let a=!1,l=!1,h=null,c=null,u=null;const d=r.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,r.updateTextureSamplingMode(3,e),d.textureLOD?r._features.supportRenderAndCopyToLodForFloatTextures?d.textureHalfFloatRender&&d.textureHalfFloatLinearFiltering?(a=!0,e.type=2):d.textureFloatRender&&d.textureFloatLinearFiltering&&(a=!0,e.type=1):a=!1:(a=!1,l=!0,u={}),a)h=new nr("rgbdDecode","rgbdDecode",null,null,1,null,3,r,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,c=r.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,l){const t=3,i=e._lodGenerationScale,a=e._lodGenerationOffset;for(let l=0;lOa(t,r,a,h,_,s,n,l,u,c,e)));else{const t=new Image;t.src=_,p=new Promise(((i,o)=>{t.onload=()=>{Oa(t,r,a,h,_,s,n,l,u,c,e).then((()=>i())).catch((e=>{o(e)}))},t.onerror=e=>{o(e)}}))}f.push(p)}if(t.length{c&&(r._releaseTexture(e),c._swapAndDie(e)),h&&h.dispose(),l&&(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))}))}(e,function(e,t){const i=(t=Ma(t)).specular;let n=Be.Log2(t.width);if(n=Math.round(n)+1,i.mipmaps.length!==6*n)throw new Error(`Unsupported specular mipmaps number "${i.mipmaps.length}"`);const r=new Array(n);for(let t=0;t{if(i){const i=t.createTexture(null,!0,!0,null,1,null,(e=>{d(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,s,a),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(r),u())}))}else{if(t._uploadImageToTexture(c,e,s,a),o){const i=l[a];i&&t._uploadImageToTexture(i._texture,e,s,0)}u()}}))}Z._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,n,r){if(Array.isArray(e))return;const s=function(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;for(let e=0;e{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()}),(e=>{null==r||r("Can not upload environment levels",e)}))}catch(e){null==r||r("Can not upload environment file",e)}}else r&&r("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}});class Da{constructor(e,t){if(this.data=e,this.isInvalid=!1,!Da.IsValid(e))return this.isInvalid=!0,void p.Error("texture missing KTX identifier");const i=Uint32Array.BYTES_PER_ELEMENT,n=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),r=67305985===n.getUint32(0,!0);this.glType=n.getUint32(1*i,r),this.glTypeSize=n.getUint32(2*i,r),this.glFormat=n.getUint32(3*i,r),this.glInternalFormat=n.getUint32(4*i,r),this.glBaseInternalFormat=n.getUint32(5*i,r),this.pixelWidth=n.getUint32(6*i,r),this.pixelHeight=n.getUint32(7*i,r),this.pixelDepth=n.getUint32(8*i,r),this.numberOfArrayElements=n.getUint32(9*i,r),this.numberOfFaces=n.getUint32(10*i,r),this.numberOfMipmapLevels=n.getUint32(11*i,r),this.bytesOfKeyValueData=n.getUint32(12*i,r),0===this.glType?(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0!==this.pixelHeight&&0===this.pixelDepth?0===this.numberOfArrayElements?this.numberOfFaces===t?this.loadType=Da.COMPRESSED_2D:p.Error("number of faces expected"+t+", but found "+this.numberOfFaces):p.Error("texture arrays not currently supported"):p.Error("only 2D textures currently supported")):p.Error("only compressed formats currently supported")}uploadLevels(e,t){switch(this.loadType){case Da.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case Da.TEX_2D:case Da.COMPRESSED_3D:case Da.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=Da.HEADER_LEN+this.bytesOfKeyValueData,n=this.pixelWidth,r=this.pixelHeight;const s=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}}Da.HEADER_LEN=64,Da.COMPRESSED_2D=0,Da.COMPRESSED_3D=1,Da.TEX_2D=2,Da.TEX_3D=3;class Na{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 Fa extends Na{constructor(e,t,i=Fa.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))}))}))}}function La(e){return e?Pe.GetAbsoluteUrl(e):null}function wa(e){null!==e.wasmUASTCToASTC&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),null!==e.wasmUASTCToBC7&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),null!==e.wasmUASTCToRGBA_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),null!==e.wasmUASTCToRGBA_SRGB&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),null!==e.wasmUASTCToR8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),null!==e.wasmUASTCToRG8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),null!==e.jsMSCTranscoder&&(KTX2DECODER.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),null!==e.wasmMSCTranscoder&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),null!==e.wasmZSTDDecoder&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)}Fa.DefaultOptions={idleTimeElapsedBeforeRelease:1e3};class Ba{constructor(e,t=Ba.DefaultNumWorkers){this._engine=e,Ba._Initialize(t)}static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(Ba._WorkerPoolPromise||Ba._DecoderModulePromise)return;const t={jsDecoderModule:Pe.GetAbsoluteUrl(this.URLConfig.jsDecoderModule),wasmUASTCToASTC:La(this.URLConfig.wasmUASTCToASTC),wasmUASTCToBC7:La(this.URLConfig.wasmUASTCToBC7),wasmUASTCToRGBA_UNORM:La(this.URLConfig.wasmUASTCToRGBA_UNORM),wasmUASTCToRGBA_SRGB:La(this.URLConfig.wasmUASTCToRGBA_SRGB),wasmUASTCToR8_UNORM:La(this.URLConfig.wasmUASTCToR8_UNORM),wasmUASTCToRG8_UNORM:La(this.URLConfig.wasmUASTCToRG8_UNORM),jsMSCTranscoder:La(this.URLConfig.jsMSCTranscoder),wasmMSCTranscoder:La(this.URLConfig.wasmMSCTranscoder),wasmZSTDDecoder:La(this.URLConfig.wasmZSTDDecoder)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?Ba._WorkerPoolPromise=new Promise((i=>{const n=`${wa}(${Ua})()`,r=URL.createObjectURL(new Blob([n],{type:"application/javascript"}));i(new Fa(e,(()=>new Promise(((e,i)=>{const n=new Worker(r),s=e=>{n.removeEventListener("error",s),n.removeEventListener("message",a),i(e)},a=t=>{"init"===t.data.action&&(n.removeEventListener("error",s),n.removeEventListener("message",a),e(n))};n.addEventListener("error",s),n.addEventListener("message",a),n.postMessage({action:"init",urls:t})})))))})):"undefined"==typeof KTX2DECODER?Ba._DecoderModulePromise=Pe.LoadScriptAsync(t.jsDecoderModule).then((()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,wa(t),new KTX2DECODER.KTX2Decoder))):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,Ba._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}uploadAsync(e,t,i){const n=this._engine.getCaps(),r={astc:!!n.astc,bptc:!!n.bptc,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,etc1:!!n.etc1};if(Ba._WorkerPoolPromise)return Ba._WorkerPoolPromise.then((n=>new Promise(((s,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),s()}catch(e){a({message:e})}else a({message:e.data.msg});o()}};n.addEventListener("error",l),n.addEventListener("message",h);const c=new Uint8Array(e.byteLength);c.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),n.postMessage({action:"decode",data:c,caps:r,options:i},[c.buffer])}))}))));if(Ba._DecoderModulePromise)return Ba._DecoderModulePromise.then((i=>new Promise(((r,s)=>{i.decode(e,n).then((e=>{this._createTexture(e,t),r()})).catch((e=>{s({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 Ua(){let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{const i=t.data.urls;importScripts(i.jsDecoderModule),wa(i),e=new KTX2DECODER.KTX2Decoder,postMessage({action:"init"});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})}))}}}Ba.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},Ba.DefaultNumWorkers=Ba.GetDefaultNumWorkers(),Z._TextureLoaders.unshift(new class{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,n){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const r=t.getEngine(),s=new Da(e,6),a=s.numberOfMipmapLevels>1&&t.generateMipMaps;r._unpackFlipY(!0),s.uploadLevels(t,t.generateMipMaps),t.width=s.pixelWidth,t.height=s.pixelHeight,r._setCubeMapTextureParams(t,a,s.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()}loadData(e,t,i,n){if(Da.IsValid(e)){t._invertVScale=!t.invertY;const n=new Da(e,1),r=function(e){switch(e){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}(n.glInternalFormat);r?(t.format=r,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=n.glInternalFormat,i(n.pixelWidth,n.pixelHeight,t.generateMipMaps,!0,(()=>{n.uploadLevels(t,t.generateMipMaps)}),n.isInvalid)}else Ba.IsValid(e)?new Ba(t.getEngine()).uploadAsync(e,t,n).then((()=>{i(t.width,t.height,t.generateMipMaps,!0,(()=>{}),!1)}),(e=>{p.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,(()=>{}),!0)})):(p.Error("texture missing KTX identifier"),i(0,0,!1,!1,(()=>{}),!0))}});class Va extends ls{constructor(e,t,i){super(e,Ye.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=qe.Identity(),this._referencedPosition=new Ye,this._trackingState=sa.NOT_TRACKING,this.onBeforeCameraTeleport=new n,this.onAfterCameraTeleport=new n,this.onTrackingStateChanged=new n,this.compensateOnFirstFrame=!0,this.minZ=.1,this.rotationQuaternion=new qe,this.cameraRigMode=Fi.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._xrSessionManager.onXRSessionInit.add((()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame})),this._xrSessionManager.onXRFrameObservable.add((()=>{this._firstFrame&&this._updateFromXRSession(),this._updateReferenceSpace(),this._updateFromXRSession()}),void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new Ti(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new Ti(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){e&&e!==this&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,qe.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace())}getClassName(){return"WebXRCamera"}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e)return void this._setTrackingState(sa.NOT_TRACKING);const t=e.emulatedPosition?sa.TRACKING_LOST:sa.TRACKING;if(this._setTrackingState(t),this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ){const e={depthFar:this.maxZ||1e4,depthNear:this.minZ};this._xrSessionManager.updateRenderState(e),this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ}if(e.transform){const t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;const i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z),this._referenceQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach(((e,t)=>{var i;const n=this.rigCameras[t];n.isLeftCamera||n.isRightCamera||("right"===e.eye?n._isRightCamera=!0:"left"===e.eye&&(n._isLeftCamera=!0));const r=e.transform.position,s=e.transform.orientation;n.parent=this.parent,n.position.set(r.x,r.y,r.z),n.rotationQuaternion.set(s.x,s.y,s.z,s.w),this._scene.useRightHandedSystem||(n.position.z*=-1,n.rotationQuaternion.z*=-1,n.rotationQuaternion.w*=-1),Qe.FromFloat32ArrayToRefScaled(e.projectionMatrix,0,1,n._projectionMatrix),this._scene.useRightHandedSystem||n._projectionMatrix.toggleProjectionMatrixHandInPlace(),0===t&&this._projectionMatrix.copyFrom(n._projectionMatrix);const a=this._xrSessionManager.getRenderTargetTextureForView(e);this._renderingMultiview=(null===(i=null==a?void 0:a._texture)||void 0===i?void 0:i.isMultiview)||!1,this._renderingMultiview?0==t&&(this._xrSessionManager.trySetViewportForView(this.viewport,e),this.outputRenderTarget=a):(this._xrSessionManager.trySetViewportForView(n.viewport,e),n.outputRenderTarget=a||this._xrSessionManager.getRenderTargetTextureForView(e)),n.layerMask=this.layerMask}))}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.lengthe;){const e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=Ze.Matrix[0],t=Ze.Matrix[1],i=Ze.Matrix[2];Qe.ComposeToRef(Va._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),Qe.ComposeToRef(Va._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const n=new XRRigidTransform({x:this._referencedPosition.x,y:this._referencedPosition.y,z:this._referencedPosition.z},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(n)}}}Va._ScaleReadOnly=Ye.One();class ka{}ka.ANCHOR_SYSTEM="xr-anchor-system",ka.BACKGROUND_REMOVER="xr-background-remover",ka.HIT_TEST="xr-hit-test",ka.MESH_DETECTION="xr-mesh-detection",ka.PHYSICS_CONTROLLERS="xr-physics-controller",ka.PLANE_DETECTION="xr-plane-detection",ka.POINTER_SELECTION="xr-controller-pointer-selection",ka.TELEPORTATION="xr-controller-teleportation",ka.FEATURE_POINTS="xr-feature-points",ka.HAND_TRACKING="xr-hand-tracking",ka.IMAGE_TRACKING="xr-image-tracking",ka.NEAR_INTERACTION="xr-near-interaction",ka.DOM_OVERLAY="xr-dom-overlay",ka.MOVEMENT="xr-controller-movement",ka.LIGHT_ESTIMATION="xr-light-estimation",ka.EYE_TRACKING="xr-eye-tracking",ka.WALKING_LOCOMOTION="xr-walking-locomotion",ka.LAYERS="xr-layers";class Ga{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)}))})),this._xrSessionManager.onXRSessionEnded.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)}))}))}static AddWebXRFeature(e,t,i=1,n=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),n&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,n){const r=this._AvailableFeatures[e][t];if(!r)throw new Error("feature not found");return r(i,n)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&t.featureImplementation.attach()}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.detach()}disableFeature(e){const t="string"==typeof e?e:e.Name,i=this._features[t];return!(!i||!i.enabled||(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],0))}dispose(){this.getEnabledFeatures().forEach((e=>{this.disableFeature(e)}))}enableFeature(e,t="latest",i={},n=!0,r=!0){const s="string"==typeof e?e:e.Name;let a=0;if("string"==typeof t){if(!t)throw new Error(`Error in provided version - ${s} (${t})`);if(a="stable"===t?Ga.GetStableVersionOfFeature(s):"latest"===t?Ga.GetLatestVersionOfFeature(s):+t,-1===a||isNaN(a))throw new Error(`feature not found - ${s} (${t})`)}else a=t;const o=Ga._ConflictingFeatures[s];if(void 0!==o&&-1!==this.getEnabledFeatures().indexOf(o))throw new Error(`Feature ${s} cannot be enabled while ${o} is enabled.`);const l=this._features[s],h=Ga.ConstructFeature(s,a,this._xrSessionManager,i);if(!h)throw new Error(`feature not found - ${s}`);l&&this.disableFeature(s);const c=h();if(c.dependsOn){const e=c.dependsOn.every((e=>!!this._features[e]));if(!e)throw new Error(`Dependant features missing. Make sure the following features are enabled - ${c.dependsOn.join(", ")}`)}if(c.isCompatible())return this._features[s]={featureImplementation:c,enabled:!0,version:a,required:r},n?this._xrSessionManager.session&&!this._features[s].featureImplementation.attached&&this.attachFeature(s):this._features[s].featureImplementation.disableAutoAttach=!0,this._features[s].featureImplementation;if(r)throw new Error("required feature not compatible");return Pe.Warn(`Feature ${s} not compatible with the current environment/browser and was not enabled.`),c}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){const t=this.getEnabledFeatures();for(const i of t){const t=this._features[i],n=t.featureImplementation.xrNativeFeatureName;if(n&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(n)&&e.requiredFeatures.push(n)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(n)&&e.optionalFeatures.push(n))),t.featureImplementation.getXRSessionInitExtension){const i=await t.featureImplementation.getXRSessionInitExtension();e={...e,...i}}}return e}}Ga._AvailableFeatures={},Ga._ConflictingFeatures={[ka.TELEPORTATION]:ka.MOVEMENT,[ka.MOVEMENT]:ka.TELEPORTATION},Mi.AddNodeConstructor("TouchCamera",((e,t)=>()=>new za(e,Ye.Zero(),t)));class za extends ls{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}}Mi.AddNodeConstructor("FreeCamera",((e,t)=>()=>new Xa(e,Ye.Zero(),t)));class Xa extends za{get gamepadAngularSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}Fi._CreateDefaultParsedCamera=(e,t)=>new Xa(e,Ye.Zero(),t);class Wa{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new n,this.onStateChangedObservable=new n,this.state=ra.NOT_IN_XR,this.sessionManager=new na(e),this.camera=new Va("webxr",e,this.sessionManager),this.featuresManager=new Ga(this.sessionManager),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}static CreateAsync(e){const t=new Wa(e);return t.sessionManager.initializeAsync().then((()=>(t._supported=!0,t))).catch((e=>{throw t._setState(ra.NOT_IN_XR),t.dispose(),e}))}dispose(){var e;this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),null===(e=this._spectatorCamera)||void 0===e||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),n={}){var r,s,a;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(ra.ENTERING_XR),"viewer"!==t&&"local"!==t&&(n.optionalFeatures=n.optionalFeatures||[],n.optionalFeatures.push(t)),n=await this.featuresManager._extendXRSessionInitObject(n),"immersive-ar"===e&&"unbounded"!==t&&p.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,n),await this.sessionManager.setReferenceSpaceTypeAsync(t);const o=await i.initializeXRLayerAsync(this.sessionManager.session),l={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};return this.featuresManager.getEnabledFeature(ka.LAYERS)||(l.baseLayer=o),this.sessionManager.updateRenderState(l),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(null===(s=null===(r=this._nonVRCamera)||void 0===r?void 0:r.inputs)||void 0===s?void 0:s.attachedToElement),null===(a=this._nonVRCamera)||void 0===a||a.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1)),this.sessionManager.onXRSessionEnded.addOnce((()=>{this.state!==ra.EXITING_XR&&this._setState(ra.EXITING_XR),this.camera.rigCameras.forEach((e=>{e.outputRenderTarget=null})),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(ra.NOT_IN_XR)})),this.sessionManager.onXRFrameObservable.addOnce((()=>{this._setState(ra.IN_XR)})),this.sessionManager}catch(e){throw console.log(e),console.log(e.message),this._setState(ra.NOT_IN_XR),e}}exitXRAsync(){return this.state!==ra.IN_XR?Promise.resolve():(this._setState(ra.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const t=1/((null==e?void 0:e.fps)?e.fps:1e3)*1e3,i=(null==e?void 0:e.preferredCameraIndex)?null==e?void 0:e.preferredCameraIndex:0,n=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=t&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[i].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[i].absoluteRotation))};if(this._spectatorMode){if(i>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const e=()=>{this.state===ra.IN_XR?(this._spectatorCamera=new Xa("webxr-spectator",Ye.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new qe,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(n),this._scene.onAfterRenderCameraObservable.add((e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)}))):this.state===ra.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(n),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}else this.sessionManager.onXRFrameObservable.removeCallback(n),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class Ha{constructor(e,t,i=-1,r=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=r,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new n,this.onButtonStateChangedObservable=new n}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return 0!==this._axesIndices.length}isButton(){return-1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}var Ya;Ha.BUTTON_TYPE="button",Ha.SQUEEZE_TYPE="squeeze",Ha.THUMBSTICK_TYPE="thumbstick",Ha.TOUCHPAD_TYPE="touchpad",Ha.TRIGGER_TYPE="trigger",function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(Ya||(Ya={}));class Ka{static get ForceFullSceneLoadingForIncremental(){return Ki.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Ki.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Ki.ShowLoadingScreen}static set ShowLoadingScreen(e){Ki.ShowLoadingScreen=e}static get loggingLevel(){return Ki.loggingLevel}static set loggingLevel(e){Ki.loggingLevel=e}static get CleanBoneMatrixWeights(){return Ki.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Ki.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return Ka._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){return Ka._RegisteredPlugins[e]||(p.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"),Ka.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in Ka._RegisteredPlugins){const i=Ka._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Ka._RegisteredPlugins[t]}return Ka.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 Ka._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,r,s,a){const o=Ka._GetDirectLoad(e.url),l=a?Ka._GetPluginForExtension(a):o?Ka._GetPluginForDirectLoad(e.url):Ka._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(Ka.OnPluginActivatedObservable.notifyObservers(h),o&&(h.canDirectLoad&&h.canDirectLoad(e.url)||!Te(e.url))){if(h.directLoad){const e=h.directLoad(t,o);e.then?e.then((e=>{i(h,e)})).catch((e=>{r("Error in directLoad of _loadData: "+e,e)})):i(h,e)}else i(h,o);return h}const c=l.isBinary,u=(e,n)=>{t.isDisposed?r("Scene has been disposed"):i(h,e,n)};let d=null,f=!1;const _=h.onDisposeObservable;_&&_.add((()=>{f=!0,d&&(d.abort(),d=null),s()}));const p=()=>{if(f)return;const i=(e,t)=>{r(null==e?void 0:e.statusText,t)},s=e.file||e.url;d=h.loadFile?h.loadFile(t,s,u,n,c,i):t._loadFile(s,u,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&&Z.OfflineProviderFactory?t.offlineProvider=Z.OfflineProviderFactory(e.url,p,m.disableManifestCheck):p(),h}static _GetFileInfo(e,t){let i,n,r=null;if(t)if(t.name){const e=t;i=`file:${e.name}`,n=e.name,r=e}else if("string"==typeof t&&t.startsWith("data:"))i=t,n="";else{const r=t;if("/"===r.substr(0,1))return Pe.Error("Wrong sceneFilename parameter"),null;i=e+r,n=r}else i=e,n=Pe.GetFilename(e),e=Pe.GetFolderPath(e);return{url:i,rootUrl:e,name:n,file:r}}static GetPluginForExtension(e){return Ka._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!Ka._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){const t=e.extensions;Ka._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{Ka._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}}))}}static ImportMesh(e,t,i="",n=f.LastCreatedScene,r=null,s=null,a=null,o=null){if(!n)return p.Error("No scene available to import mesh to"),null;const l=Ka._GetFileInfo(t,i);if(!l)return null;const h={};n.addPendingData(h);const c=()=>{n.removePendingData(h)},u=(e,t)=>{const i=Ka._FormatErrorMessage(l,e,t);a?a(n,i,new re(i,ne,t)):p.Error(i),c()},d=s?e=>{try{s(e)}catch(e){u("Error in onProgress callback: "+e,e)}}:void 0,_=(e,t,i,s,a,o,c)=>{if(n.importedMeshesFiles.push(l.url),r)try{r(e,t,i,s,a,o,c)}catch(e){u("Error in onSuccess callback: "+e,e)}n.removePendingData(h)};return Ka._LoadData(l,n,((t,i,r)=>{if(t.rewriteRootURL&&(l.rootUrl=t.rewriteRootURL(l.rootUrl,r)),t.importMesh){const r=t,s=new Array,a=new Array,o=new Array;if(!r.importMesh(e,n,i,l.rootUrl,s,a,o,u))return;n.loadingPluginName=t.name,_(s,a,o,[],[],[],[])}else t.importMeshAsync(e,n,i,l.rootUrl,d,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)}))}),d,u,c,o)}static ImportMeshAsync(e,t,i="",n=f.LastCreatedScene,r=null,s=null){return new Promise(((a,o)=>{Ka.ImportMesh(e,t,i,n,((e,t,i,n,r,s,o)=>{a({meshes:e,particleSystems:t,skeletons:i,animationGroups:n,transformNodes:r,geometries:s,lights:o})}),r,((e,t,i)=>{o(i||new Error(t))}),s)}))}static Load(e,t="",i=f.LastCreatedEngine,n=null,r=null,s=null,a=null){return i?Ka.Append(e,t,new mi(i),n,r,s,a):(Pe.Error("No engine available"),null)}static LoadAsync(e,t="",i=f.LastCreatedEngine,n=null,r=null){return new Promise(((s,a)=>{Ka.Load(e,t,i,(e=>{s(e)}),n,((e,t,i)=>{a(i||new Error(t))}),r)}))}static Append(e,t="",i=f.LastCreatedScene,n=null,r=null,s=null,a=null){if(!i)return p.Error("No scene available to append to"),null;const o=Ka._GetFileInfo(e,t);if(!o)return null;const l={};i.addPendingData(l);const h=()=>{i.removePendingData(l)};Ka.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1})));const c=(e,t)=>{const n=Ka._FormatErrorMessage(o,e,t);s?s(i,n,new re(n,ne,t)):p.Error(n),h()},u=r?e=>{try{r(e)}catch(e){c("Error in onProgress callback",e)}}:void 0,d=()=>{if(n)try{n(i)}catch(e){c("Error in onSuccess callback",e)}i.removePendingData(l)};return Ka._LoadData(o,i,((e,t)=>{if(e.load){if(!e.load(i,t,o.rootUrl,c))return;i.loadingPluginName=e.name,d()}else e.loadAsync(i,t,o.rootUrl,u,o.name).then((()=>{i.loadingPluginName=e.name,d()})).catch((e=>{c(e.message,e)}))}),u,c,h,a)}static AppendAsync(e,t="",i=f.LastCreatedScene,n=null,r=null){return new Promise(((s,a)=>{Ka.Append(e,t,i,(e=>{s(e)}),n,((e,t,i)=>{a(i||new Error(t))}),r)}))}static LoadAssetContainer(e,t="",i=f.LastCreatedScene,n=null,r=null,s=null,a=null){if(!i)return p.Error("No scene available to load asset container to"),null;const o=Ka._GetFileInfo(e,t);if(!o)return null;const l={};i.addPendingData(l);const h=()=>{i.removePendingData(l)},c=(e,t)=>{const n=Ka._FormatErrorMessage(o,e,t);s?s(i,n,new re(n,ne,t)):p.Error(n),h()},u=r?e=>{try{r(e)}catch(e){c("Error in onProgress callback",e)}}:void 0,d=e=>{if(n)try{n(e)}catch(e){c("Error in onSuccess callback",e)}i.removePendingData(l)};return Ka._LoadData(o,i,((e,t)=>{if(e.loadAssetContainer){const n=e.loadAssetContainer(i,t,o.rootUrl,c);if(!n)return;i.loadingPluginName=e.name,d(n)}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,o.rootUrl,u,o.name).then((t=>{i.loadingPluginName=e.name,d(t)})).catch((e=>{c(e.message,e)})):c("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),u,c,h,a)}static LoadAssetContainerAsync(e,t="",i=f.LastCreatedScene,n=null,r=null){return new Promise(((s,a)=>{Ka.LoadAssetContainer(e,t,i,(e=>{s(e)}),n,((e,t,i)=>{a(i||new Error(t))}),r)}))}static ImportAnimations(e,t="",i=f.LastCreatedScene,n=!0,r=Ya.Clean,s=null,a=null,o=null,l=null,h=null){if(!i)return void p.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(r){case Ya.Clean:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case Ya.Stop:i.animationGroups.forEach((e=>{e.stop()}));break;case Ya.Sync:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case Ya.NoSync:break;default:return void p.Error("Unknown animation group loading mode value '"+r+"'")}const c=i.animatables.length;this.LoadAssetContainer(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(c),s),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),a&&a(i)}),o,l,h)}static ImportAnimationsAsync(e,t="",i=f.LastCreatedScene,n=!0,r=Ya.Clean,s=null,a=null,o=null,l=null,h=null){return new Promise(((a,l)=>{Ka.ImportAnimations(e,t,i,n,r,s,(e=>{a(e)}),o,((e,t,i)=>{l(i||new Error(t))}),h)}))}}Ka.NO_LOGGING=0,Ka.MINIMAL_LOGGING=1,Ka.SUMMARY_LOGGING=2,Ka.DETAILED_LOGGING=3,Ka.OnPluginActivatedObservable=new n,Ka._RegisteredPlugins={},Ka._ShowingLoadingScreen=!1;class qa{constructor(e,t,i,r,s=!1,a){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=r,this._doNotLoadControllerMesh=s,this._controllerCache=a,this._initComponent=e=>{if(!e)return;const t=this.layout.components[e],i=t.type,n=t.gamepadIndices.button,r=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&r.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new Ha(e,i,n,r)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new n,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach((e=>this.getComponent(e).dispose())),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach((e=>{e.setEnabled(!1)})),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map((e=>this.components[e])).filter((t=>t.type===e))}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){const e=!this._getModelLoadingConstraints();let t=this._getGenericFilenameAndPath();return e?p.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise(((i,n)=>{const r=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const e=this._controllerCache.filter((e=>e.filename===t.filename&&e.path===t.path));if(e[0])return e[0].meshes.forEach((e=>e.setEnabled(!0))),void r(e[0].meshes)}Ka.ImportMesh("",t.path,t.filename,this.scene,(e=>{this._controllerCache&&this._controllerCache.push({...t,meshes:e}),r(e)}),null,((e,i)=>{p.Log(i),p.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),n(i)}))}))}updateFromXRFrame(e){this.getComponentIds().forEach((e=>this.getComponent(e).update(this.gamepadObject))),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren((e=>e.name===t),!1)[0]}_getImmediateChildByName(e,t){return e.getChildren((e=>e.name==t),!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh)return;if(!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const n=i?.5*t+.5:t;qe.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,n,e.valueMesh.rotationQuaternion),Ye.LerpToRef(e.minMesh.position,e.maxMesh.position,n,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new gn(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))})),this.rootMesh.rotationQuaternion=qe.FromEulerAngles(0,Math.PI,0)}}class Qa extends qa{constructor(e,t,i){super(e,ja[i],t,i),this.profileId=Qa.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new gn(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)})),this.rootMesh.rotationQuaternion=qe.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}Qa.ProfileId="generic-trigger";const ja={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};class Za extends qa{constructor(e,t,i,n,r){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,r),this._repositoryUrl=n,this.controllerCache=r,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach((e=>{this._touchDots[e].dispose()}))}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){const e=Ka.IsPluginForExtensionAvailable(".glb");return e||p.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach((i=>{const n=t.visualResponses[i];if("transform"===n.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,n.valueNodeName),minMesh:this._getChildByName(this.rootMesh,n.minNodeName),maxMesh:this._getChildByName(this.rootMesh,n.maxNodeName)};else{const r=t.type===Ha.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:n.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r)},t.type===Ha.TOUCHPAD_TYPE&&!this._touchDots[i]){const t=bn(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new er(i+"mat",this.scene),t.material.diffuseColor=tt.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}}))}))}_setRootMesh(e){let t;this.rootMesh=new gn(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{const t=this.getComponent(e);if(!t.hasChanges)return;const i=this._buttonMeshMapping[e],n=this.layout.components[e];Object.keys(n.visualResponses).forEach((e=>{const r=n.visualResponses[e];let s=t.value;if("xAxis"===r.componentProperty?s=t.axes.x:"yAxis"===r.componentProperty&&(s=t.axes.y),"transform"===r.valueNodeProperty)this._lerpTransform(i.states[e],s,"button"!==r.componentProperty);else{const n=i.states[e].valueMesh;n&&(n.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}}))}))}}const Ja=[];class $a{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const n=[];i&&n.push(i),n.push(...e.profiles||[]),n.length&&!n[0]&&n.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&n.push("oculus-touch-v2");const r=n.indexOf("windows-mixed-reality");if(-1!==r&&n.splice(r,0,"microsoft-mixed-reality"),n.length||n.push("generic-trigger"),this.UseOnlineRepository){const i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,r=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,n,e,t).catch((()=>r.call(this,n,e,t)))}return this._LoadProfilesFromAvailableControllers(n,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=Pe.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then((e=>JSON.parse(e.toString()))),this._ProfilesList}static ClearControllerCache(){Ja.forEach((e=>{e.meshes.forEach((e=>{e.dispose(!1,!0)}))})),Ja.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then((()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList())).then((t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=Pe.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then((e=>JSON.parse(e)))),this._ProfileLoadingPromises[e]))).then((e=>new Za(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:Ja)))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let n=0;nnew Qa(t,e.gamepad,e.handedness))),$a.DefaultFallbacks();let eo=0;class to{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new Ye,this._disposed=!1,this.onDisposeObservable=new n,this.onMeshLoadedObservable=new n,this.onMotionControllerInitObservable=new n,this._uniqueId=`controller-${eo++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new Ji(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new qe,this.inputSource.gripSpace&&(this.grip=new Ji(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new qe),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&$a.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then((e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then((e=>{var t;e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach((e=>e.renderingGroupId=this._options.renderingGroupId))),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&(null===(t=this.motionController)||void 0===t||t.dispose())}))}),(()=>{Pe.Warn("Could not find a matching motion controller for the registered input source")}))}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){const i=t&&this.grip?this.grip:this.pointer;Ye.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i){const n=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=n,n){const e=n.transform.position;this.pointer.position.set(e.x,e.y,e.z);const t=n.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent}if(this.inputSource.gripSpace&&this.grip){const n=e.getPose(this.inputSource.gripSpace,t);if(n){const e=n.transform.position,t=n.transform.orientation;this.grip.position.set(e.x,e.y,e.z),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent}this.motionController&&this.motionController.updateFromXRFrame(e)}}class io{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new n,this.onControllerRemovedObservable=new n,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add((()=>{this._addAndRemoveControllers([],this.controllers.map((e=>e.inputSource)))})),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add((e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)})),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add((e=>{this.controllers.forEach((t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera)}))})),this._options.customControllersRepositoryURL&&($a.BaseRepositoryUrl=this._options.customControllersRepositoryURL),$a.UseOnlineRepository=!this._options.disableOnlineControllerRepository,$a.UseOnlineRepository)try{$a.UpdateProfilesList().catch((()=>{$a.UseOnlineRepository=!1}))}catch(e){$a.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map((e=>e.inputSource));for(const t of e)if(-1===i.indexOf(t)){const e=new to(this.xrSessionManager.scene,t,{...this._options.controllerOptions||{},forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation});this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}const n=[],r=[];this.controllers.forEach((e=>{-1===t.indexOf(e.inputSource)?n.push(e):r.push(e)})),this.controllers=n,r.forEach((e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()}))}dispose(){this.controllers.forEach((e=>{e.dispose()})),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),$a.ClearControllerCache()}}class no{constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this.xrNativeFeatureName=""}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,(e=>this._onXRFrame(e))),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach((e=>{e.observable.remove(e.observer)})),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0}isCompatible(){return!0}_addNewAttachObserver(e,t){this._removeOnDetach.push({observable:e,observer:e.add(t)})}}class ro{constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new n,this.utilityLayerScene=new mi(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add((t=>{if(!this.utilityLayerScene.activeCamera)return;if(!this.pickingEnabled)return;if(!this.processAllEvents&&t.type!==Wt.POINTERMOVE&&t.type!==Wt.POINTERUP&&t.type!==Wt.POINTERDOWN&&t.type!==Wt.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const i=t.event;if(e.isPointerCaptured(i.pointerId))return void(this._pointerCaptures[i.pointerId]=!1);const n=i=>{let n=null;if(t.nearInteractionPickingInfo)n=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new wt;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)n=t.originalPickingInfo;else{let r=null;this._renderCamera&&(r=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),n=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),r&&(i._activeCamera=r)}return n},r=n(this.utilityLayerScene);if(!t.ray&&r&&(t.ray=r.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=Wt.POINTERDOWN)return t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new Kt(t.type,t.event,r),t.type),void(t.type===Wt.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1));if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)r&&r.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new Kt(t.type,t.event,r),t.type),t.skipOnPointerObservable=!0);else{const i=n(e),s=t.event;i&&r&&(0===r.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,s),t.skipOnPointerObservable=!0):t.type===Wt.POINTERDOWN?this._pointerCaptures[s.pointerId]=!0:t.type!==Wt.POINTERMOVE&&t.type!==Wt.POINTERUP||(this._lastPointerEvents[s.pointerId]&&(this.onPointerOutObservable.notifyObservers(s.pointerId),delete this._lastPointerEvents[s.pointerId]),this._notifyObservers(t,i,s)):!this._pointerCaptures[s.pointerId]&&(r.distance0)):!this._pointerCaptures[s.pointerId]&&r.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,s),t.skipOnPointerObservable=!0):(t.type!==Wt.POINTERMOVE&&t.type!==Wt.POINTERUP||this._lastPointerEvents[s.pointerId]&&(this.onPointerOutObservable.notifyObservers(s.pointerId),delete this._lastPointerEvents[s.pointerId]),this._notifyObservers(t,r,s))),t.type===Wt.POINTERUP&&this._pointerCaptures[s.pointerId]&&(this._pointerCaptures[s.pointerId]=!1))}})),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add((e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((()=>{this.dispose()})),this._updateCamera()}getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new Yr("shared gizmo light",new Ye(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=tt.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==ro._DefaultUtilityLayer?ro._CreateDefaultUtilityLayerFromScene(f.LastCreatedScene):ro._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return ro._DefaultUtilityLayer=new ro(e),ro._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{ro._DefaultUtilityLayer=null})),ro._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==ro._DefaultKeepDepthUtilityLayer&&(ro._DefaultKeepDepthUtilityLayer=new ro(f.LastCreatedScene),ro._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,ro._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{ro._DefaultKeepDepthUtilityLayer=null}))),ro._DefaultKeepDepthUtilityLayer}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new Kt(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){const e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}ro._DefaultUtilityLayer=null,ro._DefaultKeepDepthUtilityLayer=null;class so extends no{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;const{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new Cs(new Ye,new Ye),disabledByNearInteraction:!1,id:so._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new Ye,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new tt(.9,.9,.9),this.laserPointerDefaultColor=new tt(.7,.7,.7),this.selectionMeshDefaultColor=new tt(.8,.8,.8),this.selectionMeshPickedColor=new tt(.3,.3,1),this._identityMatrix=Qe.Identity(),this._screenCoordinatesRef=Ye.Zero(),this._viewportRef=new Ti(0,0,0,0),this._scene=this._xrSessionManager.scene}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){const e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new Cs(new Ye,new Ye),disabledByNearInteraction:!1,id:so._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i{const t=this._controllers[e];if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||t.disabledByNearInteraction)return t.selectionMesh.isVisible=!1,t.laserPointer.isVisible=!1,void(t.pick=null);let i;if(t.laserPointer.isVisible=this.displayLaserPointer,t.xrController)i=t.xrController.pointer.position,t.xrController.getWorldPointerRayToRef(t.tmpRay);else{if(!t.webXRCamera)return;i=t.webXRCamera.position,t.webXRCamera.getForwardRayToRef(t.tmpRay)}if(this._options.maxPointerDistance&&(t.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&i){const e=this._xrSessionManager.scene,n=this._options.xrInput.xrCamera;n&&(n.viewport.toGlobalToRef(e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight(),this._viewportRef),Ye.ProjectToRef(i,this._identityMatrix,e.getTransformMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,t.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let n=null;this._utilityLayerScene&&(n=this._utilityLayerScene.pickWithRay(t.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const r=this._scene.pickWithRay(t.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);n&&n.hit?r&&r.hit?n.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,s.isVisible=!1,t.pick.hit)if(this._pickingMoved(r,t.pick))o&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,l)),o=!1,a=0;else if(a>i/10&&(s.isVisible=!0),a+=this._scene.getEngine().getDeltaTime(),a>=i)this._scene.simulatePointerDown(t.pick,l),o=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),s.isVisible=!1;else{const e=1-a/i;s.scaling.set(e,e,e)}else o=!1,a=0;this._scene.simulatePointerMove(t.pick,l),r=t.pick}})),void 0!==this._options.renderingGroupId&&(s.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce((()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&o&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),s.dispose()}))}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const n={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{this._augmentPointerInit(n,t.id,t.screenCoordinates),!t.pick||this._options.disablePointerUpOnTouchOut&&i||(i?this._scene.simulatePointerMove(t.pick,n):(this._scene.simulatePointerDown(t.pick,n),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,n)))})),e.onDisposeObservable.addOnce((()=>{this._augmentPointerInit(n,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame((()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,n),t.finalPointerUpTriggered=!0)}))}))}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))})),e.inputSource.gamepad){const n=n=>{this._options.overrideButtonId&&(t.selectionComponent=n.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=n.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((n=>{if(n.changes.pressed){const r=n.changes.pressed.current;t.pick?(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),r?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)):!r||this._options.enablePointerSelectionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)}}))};e.motionController?n(e.motionController):e.onMotionControllerInitObservable.add(n)}else{const e=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)},n=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)};t.eventListeners={selectend:n,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",n)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(Ye.Dot(e,t.direction)){const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame((()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new wt,e),t.finalPointerUpTriggered=!0}))}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce((()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){Pe.Warn("controller already detached.")}}))}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||ro.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():oa("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const n=new er("laserPointerMat",t);n.emissiveColor=this.laserPointerDefaultColor,n.alpha=.7,i.material=n,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const r=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():ha("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);r.bakeCurrentTransformIntoVertices(),r.isPickable=!1,r.isVisible=!1;const s=new er("targetMat",t);return s.specularColor=tt.Black(),s.emissiveColor=this.selectionMeshDefaultColor,s.backFaceCulling=!1,r.material=s,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:r}}_pickingMoved(e,t){var i;if(!e.hit||!t.hit)return!0;if(!(e.pickedMesh&&e.pickedPoint&&t.pickedMesh&&t.pickedPoint))return!0;if(e.pickedMesh!==t.pickedMesh)return!0;null===(i=e.pickedPoint)||void 0===i||i.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const n=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance;return this._tmpVectorForPickCompare.length()>n}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}var ao,oo,lo,ho,co,uo,fo,_o;so._IdCounter=200,so.Name=ka.POINTER_SELECTION,so.Version=1,Ga.AddWebXRFeature(so.Name,((e,t)=>()=>new so(e,t)),so.Version,!0),function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"}(ao||(ao={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(oo||(oo={}));class po{constructor(){this.supportUniformBuffers=!1,this.attributes=new Array,this.uniforms=new Array,this.constants=new Array,this.samplers=new Array,this.functions={},this.extensions={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}finalize(e){const t=e.sharedData.emitComments,i=this.target===oo.Fragment;this.compilationString=`\r\n${t?"//Entry point\r\n":""}void main(void) {\r\n${this.compilationString}`,this._constantDeclaration&&(this.compilationString=`\r\n${t?"//Constants\r\n":""}${this._constantDeclaration}\r\n${this.compilationString}`);let n="";for(const e in this.functions)n+=this.functions[e]+"\r\n";this.compilationString=`\r\n${n}\r\n${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString}\r\n${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString}\r\n${this._injectAtEnd}`),this.compilationString=`${this.compilationString}\r\n}`,this.sharedData.varyingDeclaration&&(this.compilationString=`\r\n${t?"//Varyings\r\n":""}${this.sharedData.varyingDeclaration}\r\n${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=`\r\n${t?"//Samplers\r\n":""}${this._samplerDeclaration}\r\n${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=`\r\n${t?"//Uniforms\r\n":""}${this._uniformDeclaration}\r\n${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=`\r\n${t?"//Attributes\r\n":""}${this._attributeDeclaration}\r\n${this.compilationString}`),this.compilationString="precision highp float;\r\n"+this.compilationString;for(const e in this.extensions){const t=this.extensions[e];this.compilationString=`\r\n${t}\r\n${this.compilationString}`}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e]?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2D ${e};\r\n`,this.samplers.push(e))}_getGLType(e){switch(e){case ao.Float:return"float";case ao.Int:return"int";case ao.Vector2:return"vec2";case ao.Color3:case ao.Vector3:return"vec3";case ao.Color4:case ao.Vector4:return"vec4";case ao.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i}\r\n${t}\r\n#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+"\r\n"+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\r\n`;let n=O.IncludesShadersStore[e]+"\r\n";if(this.sharedData.emitComments&&(n=t+"\r\n"+n),!i)return n;if(i.replaceStrings)for(let e=0;e${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\r\n`:this.functions[r]=`#include<${e}>${(null==i?void 0:i.substitutionVars)?"("+(null==i?void 0:i.substitutionVars)+")":""}\r\n`,void(this.sharedData.emitComments&&(this.functions[r]=t+"\r\n"+this.functions[r]));if(this.functions[r]=O.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[r]=t+"\r\n"+this.functions[r]),i.removeIfDef&&(this.functions[r]=this.functions[r].replace(/^\s*?#ifdef.+$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#endif.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#else.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[r]=this.functions[r].replace(/^\s*?attribute.+$/gm,"")),i.removeUniforms&&(this.functions[r]=this.functions[r].replace(/^\s*?uniform.+$/gm,"")),i.removeVaryings&&(this.functions[r]=this.functions[r].replace(/^\s*?varying.+$/gm,"")),i.replaceStrings)for(let e=0;ee.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===oo.Vertex)return!0;if((e.ownerBlock.target===oo.Neutral||e.ownerBlock.target===oo.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isDirectlyConnectedToVertexOutput)))return!0}return!1}get isConnectedInVertexShader(){if(this.target===oo.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===oo.Vertex)return!0;if(e.target===oo.Vertex)return!0;if((e.ownerBlock.target===oo.Neutral||e.ownerBlock.target===oo.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInVertexShader)))return!0}return!1}get isConnectedInFragmentShader(){if(this.target===oo.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===oo.Fragment)return!0;if((e.ownerBlock.target===oo.Neutral||e.ownerBlock.target===oo.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInFragmentShader)))return!0}return!1}createCustomInputBlock(){return null}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===lo.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===oo.Fragment){if(i.target===oo.Vertex)return lo.TargetIncompatible;for(const e of i.outputs)if(e.ownerBlock.target!=oo.Neutral&&e.isConnectedInVertexShader)return lo.TargetIncompatible}if(this.type!==e.type&&e.innerType!==ao.AutoDetect)return go.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&go.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?lo.Compatible:lo.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return lo.TypeIncompatible;let n=i,r=t;return this.direction===ho.Input&&(n=t,r=i),n.isAnAncestorOf(r)?lo.HierarchyIssue:lo.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear()}}class vo{constructor(e,t=oo.Vertex,i=!1,n=!1){this._isFinalMerger=!1,this._isInput=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===oo.Neutral,this._isFinalMerger=i,this._isInput=n,this._name=e,this.uniqueId=ci.UniqueId}get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){0==(this._target&e)&&(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===oo.Neutral}initialize(e){}bind(e,t,i,n){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return-1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}registerInput(e,t,i=!1,n,r){return(r=null!=r?r:new go(e,this,ho.Input)).type=t,r.isOptional=i,n&&(r.target=n),this._inputs.push(r),this}registerOutput(e,t,i,n){return(n=null!=n?n:new go(e,this,ho.Output)).type=t,i&&(n.target=i),this._outputs.push(n),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!(t.connectedPoint||e&&e.type!==t.type&&t.type!==ao.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===oo.Neutral||0!=(e.target&t.target))return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return-1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){if(i.ownerBlock===e)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),n=!0;for(;n;){const r=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&r&&i.canConnectTo(r))i.connectTo(r),n=!1;else{if(!i)throw"Unable to find a compatible match";i=this.getSiblingOutput(i)}}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,n){}provideFallbacks(e,t){}initializeDefines(e,t,i,n=!1){}prepareDefines(e,t,i,n=!1,r){}autoConfigure(e){}replaceRepeatableContent(e,t,i,n){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some((e=>e.isDirectlyConnectedToVertexOutput))||this.target===oo.Vertex||this.target!==oo.VertexAndFragment&&this.target!==oo.Neutral||!this._outputs.some((e=>e.isConnectedInVertexShader)))}isReady(e,t,i,n=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,n){e.build(t,n);const r=null!=t._vertexState,s=e._buildTarget===oo.Vertex&&e.target!==oo.VertexAndFragment;if(r&&(0==(e.target&e._buildTarget)||0==(e.target&i.target)||this.target!==oo.VertexAndFragment&&s)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const e=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+e.associatedVariableName,t._getGLType(e.type))&&(t._vertexState.compilationString+=`${"v_"+e.associatedVariableName} = ${e.associatedVariableName};\r\n`),i.associatedVariableName="v_"+e.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){const t=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];for(const i of t)if(e===i)return!1;return!0}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(const t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==oo.Neutral){if(0==(i.target&this.target))continue;if(0==(i.target&e.target))continue}const n=i.connectedPoint.ownerBlock;n&&n!==this&&this._processBuild(n,e,i,t)}if(this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&console.log(`${e.target===oo.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case oo.Vertex:e.sharedData.checks.emitVertex=!0;break;case oo.Fragment:e.sharedData.checks.emitFragment=!0}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=`\r\n//${this.name}\r\n`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(0!=(i.target&e.target))for(const n of i.endpoints){const i=n.ownerBlock;i&&0!=(i.target&e.target)&&-1!==t.indexOf(i)&&this._processBuild(i,e,n,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector};\r\n${e}.visibleOnFrame = ${this.visibleOnFrame};\r\n${e}.target = ${this.target};\r\n`}_dumpCode(e,t){let i;t.push(this);const n=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=n||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=n+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName),i=`\r\n// ${this.getClassName()}\r\n`,this.comments&&(i+=`// ${this.comments}\r\n`),i+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\r\n`,i+=this._dumpPropertiesCode();for(const n of this.inputs){if(!n.isConnected)continue;const r=n.connectedPoint.ownerBlock;-1===t.indexOf(r)&&(i+=r._dumpCode(e,t))}for(const n of this.outputs)if(n.hasEndpoints)for(const r of n.endpoints){const n=r.ownerBlock;n&&-1===t.indexOf(n)&&(i+=n._dumpCode(e,t))}return i}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const n=i.connectedPoint,r=n.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(n.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\r\n`}return t}clone(e,t=""){const i=this.serialize(),n=xe(i.customType);if(n){const r=new n;return r._deserialize(i,e,t),r}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){var n;this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=null!==(n=e.target)&&void 0!==n?n:this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class Eo extends vo{constructor(e){super(e,oo.Neutral),this.complementW=1,this.complementZ=0,this.target=oo.Vertex,this.registerInput("vector",ao.AutoDetect),this.registerInput("transform",ao.Matrix),this.registerOutput("output",ao.Vector4),this.registerOutput("xyz",ao.Vector3),this._inputs[0].onConnectionObservable.add((e=>{if(e.ownerBlock.isInput){const t=e.ownerBlock;"normal"!==t.name&&"tangent"!==t.name||(this.complementW=0)}}))}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform;if(t.connectedPoint){if(0===this.complementW){const n=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",n),e.sharedData.blocksWithDefines.push(this);const r=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${r} = mat3(${i.associatedVariableName});\r\n`,e.compilationString+="#ifdef NONUNIFORMSCALING\r\n",e.compilationString+=`${r} = transposeMat3(inverseMat3(${r}));\r\n`,e.compilationString+="#endif\r\n",t.connectedPoint.type){case ao.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\r\n`;break;case ao.Vector3:case ao.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\r\n`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${r} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\r\n`}}else{const n=i.associatedVariableName;switch(t.connectedPoint.type){case ao.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${n} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\r\n`;break;case ao.Vector3:case ao.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${n} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\r\n`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${n} * ${t.associatedVariableName};\r\n`}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz;\r\n`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){const e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ};\r\n`;return e+=`${this._codeVariableName}.complementW = ${this.complementW};\r\n`,e}}Ie("BABYLON.TransformBlock",Eo);class To extends vo{constructor(e){super(e,oo.Vertex,!0),this.registerInput("vector",ao.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e){for(const t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName};\r\n`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+="vFragmentDepth = 1.0 + gl_Position.w;\r\n",e.compilationString+="gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n"),this}}function Co(e,t=co.Boolean,i="PROPERTIES",n){return(r,s)=>{let a=r._propStore;a||(a=[],r._propStore=a),a.push({propertyName:s,displayName:e,type:t,groupName:i,options:null!=n?n:{}})}}Ie("BABYLON.VertexOutputBlock",To),function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List"}(co||(co={}));class Ro extends vo{constructor(e){super(e,oo.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",ao.Color4,!0),this.registerInput("rgb",ao.AutoDetect,!0),this.registerInput("a",ao.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(ao.Color3|ao.Vector3|ao.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){this.useLogarithmicDepth&&i&&sn.BindLogDepth(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,n=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||n.isConnected,e.sharedData.blocksWithDefines.push(this),this.useLogarithmicDepth&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const r=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",r),t.connectedPoint)n.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${n.associatedVariableName});\r\n`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName};\r\n`;else if(i.connectedPoint){let t="1.0";n.connectedPoint&&(t=n.associatedVariableName),i.connectedPoint.type===ao.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t});\r\n`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${t});\r\n`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName}\r\n`,e.compilationString+="gl_FragColor = toLinearSpace(gl_FragColor);\r\n",e.compilationString+="#endif\r\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\r\n`,e.compilationString+="gl_FragColor = toGammaSpace(gl_FragColor);\r\n",e.compilationString+="#endif\r\n",this.useLogarithmicDepth&&(e.compilationString+="gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n"),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\r\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\r\n`,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\r\n`,e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){var n;super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=null!==(n=e.useLogarithmicDepth)&&void 0!==n&&n}}et([Co("Convert to gamma space",co.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Ro.prototype,"convertToGammaSpace",void 0),et([Co("Convert to linear space",co.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Ro.prototype,"convertToLinearSpace",void 0),et([Co("Use logarithmic depth",co.Boolean,"PROPERTIES")],Ro.prototype,"useLogarithmicDepth",void 0),Ie("BABYLON.FragmentOutputBlock",Ro),function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(uo||(uo={})),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(fo||(fo={})),function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime"}(_o||(_o={}));const Ao={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},bo={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},So={particle_texturemask:!0};class Io extends vo{constructor(e,t=oo.Vertex,i=ao.AutoDetect){super(e,t,!1,!0),this._mode=uo.Undefined,this._animationType=_o.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new n,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}get type(){if(this._type===ao.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=ao.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=ao.Vector2,this._type;case"Vector3":return this._type=ao.Vector3,this._type;case"Vector4":return this._type=ao.Vector4,this._type;case"Color3":return this._type=ao.Color3,this._type;case"Color4":return this._type=ao.Color4,this._type;case"Matrix":return this._type=ao.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=ao.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=ao.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=ao.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=ao.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case fo.World:case fo.WorldView:case fo.WorldViewProjection:case fo.View:case fo.ViewProjection:case fo.Projection:return this._type=ao.Matrix,this._type;case fo.CameraPosition:return this._type=ao.Vector3,this._type;case fo.FogColor:return this._type=ao.Color3,this._type;case fo.DeltaTime:case fo.MaterialAlpha:return this._type=ao.Float,this._type;case fo.CameraParameters:return this._type=ao.Vector4,this._type}}return this._type}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=uo.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===ao.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=uo.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=uo.Uniform}get associatedVariableName(){return this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===uo.Undefined}get isUniform(){return this._mode===uo.Uniform}set isUniform(e){this._mode=e?uo.Uniform:uo.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===uo.Attribute}set isAttribute(e){this._mode=e?uo.Attribute:uo.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===uo.Varying}set isVarying(e){this._mode=e?uo.Varying:uo.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=uo.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case _o.Time:this.type===ao.Float&&(this.value+=.01*e.getAnimationRatio());break;case _o.RealTime:this.type===ao.Float&&(this.value=(H.Now-e.getEngine().startTime)/1e3)}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)}\r\n`:`#ifdef ${e}\r\n`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case ao.Float:this.value=0;break;case ao.Vector2:this.value=He.Zero();break;case ao.Vector3:this.value=Ye.Zero();break;case ao.Vector4:this.value=Ke.Zero();break;case ao.Color3:this.value=tt.White();break;case ao.Color4:this.value=new it(1,1,1,1);break;case ao.Matrix:this.value=Qe.Identity()}}_emitConstant(e){switch(this.type){case ao.Float:return`${e._emitFloat(this.value)}`;case ao.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case ao.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case ao.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case ao.Color3:return nt.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&nt.Color3[0].toGammaSpaceToRef(nt.Color3[0]),this.convertToLinearSpace&&nt.Color3[0].toLinearSpaceToRef(nt.Color3[0]),`vec3(${nt.Color3[0].r}, ${nt.Color3[0].g}, ${nt.Color3[0].b})`;case ao.Color4:return nt.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&nt.Color4[0].toGammaSpaceToRef(nt.Color4[0]),this.convertToLinearSpace&&nt.Color4[0].toLinearSpaceToRef(nt.Color4[0]),`vec4(${nt.Color4[0].r}, ${nt.Color4[0].g}, ${nt.Color4[0].b}, ${nt.Color4[0].a})`}return""}get _noContextSwitch(){return bo[this.name]}_emit(e,t){var i;if(this.isUniform){if(this.associatedVariableName||(this.associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;return e.constants.push(this.associatedVariableName),void(e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)};\r\n`)}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t)),e._uniformDeclaration+=`uniform ${e._getGLType(this.type)} ${this.associatedVariableName};\r\n`,t&&(e._uniformDeclaration+="#endif\r\n");const i=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case fo.WorldView:i.needWorldViewMatrix=!0;break;case fo.WorldViewProjection:i.needWorldViewProjectionMatrix=!0}else this._animationType!==_o.None&&e.sharedData.animatedInputs.push(this)}else if(this.isAttribute){if(this.associatedVariableName=null!==(i=Ao[this.name])&&void 0!==i?i:this.name,this.target===oo.Vertex&&e._vertexState)return void(bo[this.name]?So[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):this._emit(e._vertexState,t));if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),bo[this.name]?So[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e._attributeDeclaration+=`attribute ${e._getGLType(this.type)} ${this.associatedVariableName};\r\n`,t&&(e._attributeDeclaration+="#endif\r\n"))}}_transmitWorld(e,t,i,n){if(!this._systemValue)return;const r=this.associatedVariableName;switch(this._systemValue){case fo.World:e.setMatrix(r,t);break;case fo.WorldView:e.setMatrix(r,i);break;case fo.WorldViewProjection:e.setMatrix(r,n)}}_transmit(e,t,i){if(this.isAttribute)return;const n=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case fo.World:case fo.WorldView:case fo.WorldViewProjection:return;case fo.View:e.setMatrix(n,t.getViewMatrix());break;case fo.Projection:e.setMatrix(n,t.getProjectionMatrix());break;case fo.ViewProjection:e.setMatrix(n,t.getTransformMatrix());break;case fo.CameraPosition:t.bindEyePosition(e,n,!0);break;case fo.FogColor:e.setColor3(n,t.fogColor);break;case fo.DeltaTime:e.setFloat(n,t.deltaTime/1e3);break;case fo.CameraParameters:t.activeCamera&&e.setFloat4(n,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case fo.MaterialAlpha:e.setFloat(n,i.alpha)}return}const r=this._valueCallback?this._valueCallback():this._storedValue;if(null!==r)switch(this.type){case ao.Float:e.setFloat(n,r);break;case ao.Int:e.setInt(n,r);break;case ao.Color3:nt.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&nt.Color3[0].toGammaSpaceToRef(nt.Color3[0]),this.convertToLinearSpace&&nt.Color3[0].toLinearSpaceToRef(nt.Color3[0]),e.setColor3(n,nt.Color3[0]);break;case ao.Color4:nt.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&nt.Color4[0].toGammaSpaceToRef(nt.Color4[0]),this.convertToLinearSpace&&nt.Color4[0].toLinearSpaceToRef(nt.Color4[0]),e.setDirectColor4(n,nt.Color4[0]);break;case ao.Vector2:e.setVector2(n,r);break;case ao.Vector3:e.setVector3(n,r);break;case ao.Vector4:e.setVector4(n,r);break;case ao.Matrix:e.setMatrix(n,r)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}");\r\n`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${fo[this._systemValue]});\r\n`;if(this.isUniform){const t=[];let i="";switch(this.type){case ao.Float:i=`${this.value}`;break;case ao.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case ao.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case ao.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case ao.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case ao.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case ao.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===ao.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${_o[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\r\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){const e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===uo.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,"tangent"===e.name&&e.mode===uo.Attribute&&e.type===ao.Vector3&&(this._type=ao.Vector4),e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=xe(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}Ie("BABYLON.InputBlock",Io);class xo extends vo{constructor(e){super(e,oo.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",ao.AutoDetect,!1,oo.VertexAndFragment),this.registerOutput("rgba",ao.Color4,oo.Neutral),this.registerOutput("rgb",ao.Color3,oo.Neutral),this.registerOutput("r",ao.Float,oo.Neutral),this.registerOutput("g",ao.Float,oo.Neutral),this.registerOutput("b",ao.Float,oo.Neutral),this.registerOutput("a",ao.Float,oo.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ao.Vector2|ao.Vector3|ao.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?oo.VertexAndFragment:oo.Fragment:oo.VertexAndFragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec2")),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\r\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===oo.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\r\n`}else this.uv.ownerBlock.target!==oo.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\r\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\r\n`}_writeOutput(e,t,i,n=!1){if(n){if(e.target===oo.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`}else this.uv.ownerBlock.target!==oo.Fragment?(e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n"):e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.blockingBlocks.indexOf(this)<0&&e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.indexOf(this)<0&&e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.indexOf(this)<0&&e.sharedData.blocksWithDefines.push(this),e.target!==oo.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Si.Parse(e.texture,t,i))}}Ie("BABYLON.CurrentScreenBlock",xo);class yo extends vo{constructor(e){super(e,oo.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",ao.AutoDetect,!1,oo.VertexAndFragment),this.registerOutput("rgba",ao.Color4,oo.Neutral),this.registerOutput("rgb",ao.Color3,oo.Neutral),this.registerOutput("r",ao.Float,oo.Neutral),this.registerOutput("g",ao.Float,oo.Neutral),this.registerOutput("b",ao.Float,oo.Neutral),this.registerOutput("a",ao.Float,oo.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ao.Vector2|ao.Vector3|ao.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e){if(!this.uv.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"particle_uv"===e.name));t||(t=new Io("uv"),t.setAsAttribute("particle_uv")),t.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_writeOutput(e,t,i){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n"}_buildBlock(e){if(super._buildBlock(e),e.target===oo.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName});\r\n`;for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Si.Parse(e.texture,t,i))}}Ie("BABYLON.ParticleTextureBlock",yo);class Mo extends vo{constructor(e){super(e,oo.Fragment),this._isUnique=!0,this.registerInput("color",ao.Color4,!1,oo.Fragment),this.registerOutput("rampColor",ao.Color4,oo.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==oo.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=`\n #ifdef RAMPGRADIENT\n vec4 baseColor = ${this.color.associatedVariableName};\n float alpha = ${this.color.associatedVariableName}.a;\n\n float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\n\n vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));\n baseColor.rgb *= rampColor.rgb;\n\n // Remapped alpha\n float finalAlpha = baseColor.a;\n baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);\n\n ${this._declareOutput(this.rampColor,e)} = baseColor;\n #else\n ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName};\n #endif\n `,this}}Ie("BABYLON.ParticleRampGradientBlock",Mo);class Po extends vo{constructor(e){super(e,oo.Fragment),this._isUnique=!0,this.registerInput("color",ao.Color4,!1,oo.Fragment),this.registerInput("alphaTexture",ao.Float,!1,oo.Fragment),this.registerInput("alphaColor",ao.Float,!1,oo.Fragment),this.registerOutput("blendColor",ao.Color4,oo.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==oo.Vertex)return e.compilationString+=`\n #ifdef BLENDMULTIPLYMODE\n ${this._declareOutput(this.blendColor,e)};\n float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};\n ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);\n ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a;\n #else\n ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName};\n #endif\n `,this}}Ie("BABYLON.ParticleBlendMultiplyBlock",Po);class Oo extends vo{constructor(e){super(e,oo.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",ao.Vector4,!0),this.registerInput("xyz ",ao.Vector3,!0),this.registerInput("xy ",ao.Vector2,!0),this.registerInput("zw ",ao.Vector2,!0),this.registerInput("x",ao.Float,!0),this.registerInput("y",ao.Float,!0),this.registerInput("z",ao.Float,!0),this.registerInput("w",ao.Float,!0),this.registerOutput("xyzw",ao.Vector4),this.registerOutput("xyz",ao.Vector3),this.registerOutput("xy",ao.Vector2),this.registerOutput("zw",ao.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,n=this.z,r=this.w,s=this.xyIn,a=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],c=this._outputs[1],u=this._outputs[2],d=this._outputs[3];return l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${l.associatedVariableName}${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)};\r\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)};\r\n`)):o.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${o.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${o.associatedVariableName}${this._buildSwizzle(3)};\r\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\r\n`)):s.isConnected?(h.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${s.associatedVariableName}, ${a.associatedVariableName})${this._buildSwizzle(4)};\r\n`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${s.associatedVariableName}, ${n.isConnected?this._writeVariable(n):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${s.associatedVariableName}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(3)};\r\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${s.associatedVariableName}${this._buildSwizzle(2)};\r\n`),d.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)};\r\n`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${n.isConnected?this._writeVariable(n):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};\r\n`)):(h.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${a.associatedVariableName})${this._buildSwizzle(4)};\r\n`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(3)};\r\n`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)};\r\n`),d.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)};\r\n`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${n.isConnected?this._writeVariable(n):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};\r\n`)),this}serialize(){const e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){var n,r,s,a;super._deserialize(e,t,i),this.xSwizzle=null!==(n=e.xSwizzle)&&void 0!==n?n:"x",this.ySwizzle=null!==(r=e.ySwizzle)&&void 0!==r?r:"y",this.zSwizzle=null!==(s=e.zSwizzle)&&void 0!==s?s:"z",this.wSwizzle=null!==(a=e.wSwizzle)&&void 0!==a?a:"w"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}";\r\n`,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";\r\n`,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";\r\n`,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";\r\n`,e}}Ie("BABYLON.VectorMergerBlock",Oo);class Do extends vo{constructor(e){super(e,oo.Neutral),this.sourceRange=new He(-1,1),this.targetRange=new He(0,1),this.registerInput("input",ao.AutoDetect),this.registerInput("sourceMin",ao.Float,!0),this.registerInput("sourceMax",ao.Float,!0),this.registerInput("targetMin",ao.Float,!0),this.registerInput("targetMax",ao.Float,!0),this.registerOutput("output",ao.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),n=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),r=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),s=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${r} + (${this._inputs[0].associatedVariableName} - ${i}) * (${s} - ${r}) / (${n} - ${i});\r\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\r\n`;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\r\n`,e}serialize(){const e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=He.FromArray(e.sourceRange),this.targetRange=He.FromArray(e.targetRange)}}et([Co("From",co.Vector2)],Do.prototype,"sourceRange",void 0),et([Co("To",co.Vector2)],Do.prototype,"targetRange",void 0),Ie("BABYLON.RemapBlock",Do);class No extends vo{constructor(e){super(e,oo.Neutral),this.registerInput("left",ao.AutoDetect),this.registerInput("right",ao.AutoDetect),this.registerOutput("output",ao.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MultiplyBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};\r\n`,this}}var Fo;Ie("BABYLON.MultiplyBlock",No),function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture"}(Fo||(Fo={}));class Lo{constructor(){this.direction1=new Ye(0,1,0),this.direction2=new Ye(0,1,0),this.minEmitBox=new Ye(-.5,-.5,-.5),this.maxEmitBox=new Ye(.5,.5,.5)}startDirectionFunction(e,t,i,n){const r=Be.RandomRange(this.direction1.x,this.direction2.x),s=Be.RandomRange(this.direction1.y,this.direction2.y),a=Be.RandomRange(this.direction1.z,this.direction2.z);if(n)return t.x=r,t.y=s,void(t.z=a);Ye.TransformNormalFromFloatsToRef(r,s,a,e,t)}startPositionFunction(e,t,i,n){const r=Be.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),s=Be.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),a=Be.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(n)return t.x=r,t.y=s,void(t.z=a);Ye.TransformCoordinatesFromFloatsToRef(r,s,a,e,t)}clone(){const e=new Lo;return $.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){Ye.FromArrayToRef(e.direction1,0,this.direction1),Ye.FromArrayToRef(e.direction2,0,this.direction2),Ye.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),Ye.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class wo{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}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}startDirectionFunction(e,t,i,n){n?Ze.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),Ze.Vector3[0]).normalize();const r=Be.RandomRange(0,this.directionRandomizer),s=Be.RandomRange(0,this.directionRandomizer),a=Be.RandomRange(0,this.directionRandomizer);t.x=Ze.Vector3[0].x+r,t.y=Ze.Vector3[0].y+s,t.z=Ze.Vector3[0].z+a,t.normalize()}startPositionFunction(e,t,i,n){const r=Be.RandomRange(0,2*Math.PI);let s;this.emitFromSpawnPointOnly?s=1e-4:(s=Be.RandomRange(0,this.heightRange),s=1-s*s);let a=this._radius-Be.RandomRange(0,this._radius*this.radiusRange);a*=s;const o=a*Math.sin(r),l=a*Math.cos(r),h=s*this._height;if(n)return t.x=o,t.y=h,void(t.z=l);Ye.TransformCoordinatesFromFloatsToRef(o,h,l,e,t)}clone(){const e=new wo(this._radius,this._angle,this.directionRandomizer);return $.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 Bo{constructor(e=1,t=1,i=1,n=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=n,this._tempVector=Ye.Zero()}startDirectionFunction(e,t,i,n,r){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),Ye.TransformNormalToRef(this._tempVector,r,this._tempVector);const s=Be.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let a=Math.atan2(this._tempVector.x,this._tempVector.z);a+=Be.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=s,this._tempVector.x=Math.sin(a),this._tempVector.z=Math.cos(a),this._tempVector.normalize(),n?t.copyFrom(this._tempVector):Ye.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,n){const r=Be.RandomRange(-this.height/2,this.height/2),s=Be.RandomRange(0,2*Math.PI),a=Be.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),o=Math.sqrt(a)*this.radius,l=o*Math.cos(s),h=o*Math.sin(s);n?t.copyFromFloats(l,r,h):Ye.TransformCoordinatesFromFloatsToRef(l,r,h,e,t)}clone(){const e=new Bo(this.radius,this.directionRandomizer);return $.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 Uo extends Bo{constructor(e=1,t=1,i=1,n=new Ye(0,1,0),r=new Ye(0,1,0)){super(e,t,i),this.direction1=n,this.direction2=r}startDirectionFunction(e,t){const i=Be.RandomRange(this.direction1.x,this.direction2.x),n=Be.RandomRange(this.direction1.y,this.direction2.y),r=Be.RandomRange(this.direction1.z,this.direction2.z);Ye.TransformNormalFromFloatsToRef(i,n,r,e,t)}clone(){const e=new Uo(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return $.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 Vo{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,n){const r=i.position.subtract(e.getTranslation()).normalize(),s=Be.RandomRange(0,this.directionRandomizer),a=Be.RandomRange(0,this.directionRandomizer),o=Be.RandomRange(0,this.directionRandomizer);r.x+=s,r.y+=a,r.z+=o,r.normalize(),n?t.copyFrom(r):Ye.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,n){const r=this.radius-Be.RandomRange(0,this.radius*this.radiusRange),s=Be.RandomRange(0,1),a=Be.RandomRange(0,2*Math.PI),o=Math.acos(2*s-1),l=r*Math.cos(a)*Math.sin(o),h=r*Math.cos(o),c=r*Math.sin(a)*Math.sin(o);n?t.copyFromFloats(l,Math.abs(h),c):Ye.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),c,e,t)}clone(){const e=new Vo(this.radius,this.directionRandomizer);return $.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 ko{constructor(){this.direction1=new Ye(0,1,0),this.direction2=new Ye(0,1,0)}startDirectionFunction(e,t,i,n){const r=Be.RandomRange(this.direction1.x,this.direction2.x),s=Be.RandomRange(this.direction1.y,this.direction2.y),a=Be.RandomRange(this.direction1.z,this.direction2.z);n?t.copyFromFloats(r,s,a):Ye.TransformNormalFromFloatsToRef(r,s,a,e,t)}startPositionFunction(e,t,i,n){n?t.copyFromFloats(0,0,0):Ye.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new ko;return $.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){Ye.FromArrayToRef(e.direction1,0,this.direction1),Ye.FromArrayToRef(e.direction2,0,this.direction2)}}class Go{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,n){const r=i.position.subtract(e.getTranslation()).normalize(),s=Be.RandomRange(0,this.directionRandomizer),a=Be.RandomRange(0,this.directionRandomizer),o=Be.RandomRange(0,this.directionRandomizer);r.x+=s,r.y+=a,r.z+=o,r.normalize(),n?t.copyFrom(r):Ye.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,n){const r=this.radius-Be.RandomRange(0,this.radius*this.radiusRange),s=Be.RandomRange(0,1),a=Be.RandomRange(0,2*Math.PI),o=Math.acos(2*s-1),l=r*Math.cos(a)*Math.sin(o),h=r*Math.cos(o),c=r*Math.sin(a)*Math.sin(o);n?t.copyFromFloats(l,h,c):Ye.TransformCoordinatesFromFloatsToRef(l,h,c,e,t)}clone(){const e=new Go(this.radius,this.directionRandomizer);return $.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 zo extends Go{constructor(e=1,t=new Ye(0,1,0),i=new Ye(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=Be.RandomRange(this.direction1.x,this.direction2.x),n=Be.RandomRange(this.direction1.y,this.direction2.y),r=Be.RandomRange(this.direction1.z,this.direction2.z);Ye.TransformNormalFromFloatsToRef(i,n,r,e,t)}clone(){const e=new zo(this.radius,this.direction1,this.direction2);return $.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 Xo{constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=Ye.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 Ye(10,10,10),this.onAnimationEnd=null,this.blendMode=Xo.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 He(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new Ye(0,0,0),this._useLogarithmicDepth=!1,this.gravity=Ye.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 At,this.id=e,this.name=e}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:Ye.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:Ye.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:Ye.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:Ye.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}createPointEmitter(e,t){const i=new ko;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=new Vo(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=new Go(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new Ye(0,1,0),i=new Ye(0,1,0)){const n=new zo(e,t,i);return this.particleEmitterType=n,n}createCylinderEmitter(e=1,t=1,i=1,n=0){const r=new Bo(e,t,i,n);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,n=new Ye(0,1,0),r=new Ye(0,1,0)){const s=new Uo(e,t,i,n,r);return this.particleEmitterType=s,s}createConeEmitter(e=1,t=Math.PI/4){const i=new wo(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,n){const r=new Lo;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=n,r}}Xo.BLENDMODE_ONEONE=0,Xo.BLENDMODE_STANDARD=1,Xo.BLENDMODE_ADD=2,Xo.BLENDMODE_MULTIPLY=3,Xo.BLENDMODE_MULTIPLYADD=4;class Wo extends vo{constructor(e){super(e,oo.Neutral),this.registerInput("rgba",ao.Color4,!0),this.registerInput("rgb ",ao.Color3,!0),this.registerOutput("rgb",ao.Color3),this.registerOutput("r",ao.Float),this.registerOutput("g",ao.Float),this.registerOutput("b",ao.Float),this.registerOutput("a",ao.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],n=this._outputs[1],r=this._outputs[2],s=this._outputs[3],a=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb;\r\n`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.r;\r\n`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.g;\r\n`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.b;\r\n`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${t.associatedVariableName}.a;\r\n`),this}}Ie("BABYLON.ColorSplitterBlock",Wo);class Ho{constructor(e){this.name=zt.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=new Array}register(){this.scene._beforeClearStage.registerStep(zt.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){Pe.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}P.ShadersStore.proceduralVertexShader="attribute vec2 position;\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Yo extends Si{constructor(e,t,i,r,s=null,a=!0,o=!1,l=0){super(null,r,!a),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new n,this.onBeforeGenerationObservable=new n,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null;let h=(r=this.getScene()||f.LastCreatedScene)._getComponent(zt.NAME_PROCEDURALTEXTURE);h||(h=new Ho(r),r._addComponent(h)),r.proceduralTextures.push(this),this._fullEngine=r.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=l,this._generateMipMaps=a,this._drawWrapper=new X(this._fullEngine),this.setFragment(i),this._fallbackTexture=s;const c=this._createRtWrapper(o,t,a,l);this._texture=c.texture;const u=[];u.push(1,1),u.push(-1,1),u.push(-1,-1),u.push(1,-1),this._vertexBuffers[Lt.PositionKind]=new Lt(this._fullEngine,u,Lt.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,n){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:n}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:n}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then((e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId})):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData}_createIndexBuffer(){const e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[Lt.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===dr.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=dr.REFRESHRATE_RENDER_ONCE)}reset(){var e;null===(e=this._drawWrapper.effect)||void 0===e||e.dispose()}_getDefines(){return""}isReady(){const e=this._fullEngine;let t;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const i=this._getDefines();return!(!this._drawWrapper.effect||i!==this._cachedDefines||!this._drawWrapper.effect.isReady())||(t=void 0!==this._fragment.fragmentElement?{vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:{vertex:"procedural",fragment:this._fragment},this._cachedDefines!==i&&(this._cachedDefines=i,this._drawWrapper.effect=e.createEffect(t,[Lt.PositionKind],this._uniforms,this._samplers,i,void 0,void 0,(()=>{var e;null===(e=this._rtWrapper)||void 0===e||e.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0}))),this._drawWrapper.effect.isReady())}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const n=this._createRtWrapper(i,e,t,this._textureType);this._texture=n.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,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}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){var t,i;const n=this.getScene();if(!n)return;const r=this._fullEngine;if(r.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),r.setState(!1),!this.nodeMaterialSource){for(const e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(const e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(const e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(const e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(const e in this._colors4){const t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(const e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(const e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;null===(t=r._debugPushGroup)||void 0===t||t.call(r,`procedural texture generation for ${this.name}`,1);const s=r.currentViewport;if(this.isCube)for(let e=0;e<6;e++)r.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&r.clear(n.clearColor,!0,!1,!1),r.drawElementsType(hn.TriangleFillMode,0,6);else r.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&r.clear(n.clearColor,!0,!1,!1),r.drawElementsType(hn.TriangleFillMode,0,6);r.unBindFramebuffer(this._rtWrapper,this.isCube),s&&r.setViewport(s),this.isCube&&r.generateMipMapsForCubemap(this._texture),null===(i=r._debugPopGroup)||void 0===i||i.call(r,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){const e=this.getSize(),t=new Yo(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t}dispose(){const e=this.getScene();if(!e)return;const t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[Lt.PositionKind];i&&(i.dispose(),this._vertexBuffers[Lt.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}var Ko;et([ct()],Yo.prototype,"isEnabled",void 0),et([ct()],Yo.prototype,"autoClear",void 0),et([ct()],Yo.prototype,"_generateMipMaps",void 0),et([ct()],Yo.prototype,"_size",void 0),et([ct()],Yo.prototype,"refreshRate",null),Ie("BABYLON.ProceduralTexture",Yo),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees"}(Ko||(Ko={}));class qo extends vo{constructor(e){super(e,oo.Neutral),this.operation=Ko.Cos,this.registerInput("input",ao.AutoDetect),this.registerOutput("output",ao.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="";switch(this.operation){case Ko.Cos:i="cos";break;case Ko.Sin:i="sin";break;case Ko.Abs:i="abs";break;case Ko.Exp:i="exp";break;case Ko.Exp2:i="exp2";break;case Ko.Round:i="round";break;case Ko.Floor:i="floor";break;case Ko.Ceiling:i="ceil";break;case Ko.Sqrt:i="sqrt";break;case Ko.Log:i="log";break;case Ko.Tan:i="tan";break;case Ko.ArcTan:i="atan";break;case Ko.ArcCos:i="acos";break;case Ko.ArcSin:i="asin";break;case Ko.Fract:i="fract";break;case Ko.Sign:i="sign";break;case Ko.Radians:i="radians";break;case Ko.Degrees:i="degrees"}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName});\r\n`,this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${Ko[this.operation]};\r\n`}}Ie("BABYLON.TrigonometryBlock",qo);const Qo={effect:null,subMesh:null};class jo extends Ct{constructor(){super(),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.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!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.EXPOSURE=!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.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class Zo extends vn{constructor(e,t,i={}){super(e,t||f.LastCreatedScene),this._buildId=Zo._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new Qe,this._cachedWorldViewProjectionMatrix=new Qe,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new n,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=new Array,this._mode=Fo.Material,this.forceAlphaBlending=!1,this._options={emitComments:!1,...i},this._attachImageProcessingConfiguration(null)}static _BlockIsTextureBlock(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}getClassName(){return"NodeMaterial"}_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()}))))}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return Pe.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(const t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){const t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return 0!=(e.target&oo.Vertex)&&this._addVertexOutputNode(e),0!=(e.target&oo.Fragment)&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||(0!=(e.target&oo.Vertex)&&this._removeVertexOutputNode(e),0!=(e.target&oo.Fragment)&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=oo.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=oo.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_initializeBlock(e,t,i,n=!0){if(e.initialize(t),n&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){const t=e.getClassName();for(const e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const r of e.inputs){r.associatedVariableName="";const s=r.connectedPoint;if(s){const r=s.ownerBlock;r!==e&&((r.target===oo.VertexAndFragment||t.target===oo.Fragment&&r.target===oo.Vertex&&r._preparationId!==this._buildId)&&i.push(r),this._initializeBlock(r,t,i,n))}}for(const t of e.outputs)t.associatedVariableName=""}_resetDualBlocks(e,t){e.target===oo.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const n=i.connectedPoint;if(n){const i=n.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!0){this._buildWasSuccessful=!1;const n=this.getScene().getEngine(),r=this._mode===Fo.Particle;if(0===this._vertexOutputNodes.length&&!r)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new po,this._vertexCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._vertexCompilationState.target=oo.Vertex,this._fragmentCompilationState=new po,this._fragmentCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._fragmentCompilationState.target=oo.Fragment,this._sharedData=new mo,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=r;const s=[],a=[];for(const e of this._vertexOutputNodes)s.push(e),this._initializeBlock(e,this._vertexCompilationState,a,i);for(const e of this._fragmentOutputNodes)a.push(e),this._initializeBlock(e,this._fragmentCompilationState,s,i);this.optimize();for(const e of s)e.build(this._vertexCompilationState,s);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const e of a)this._resetDualBlocks(e,this._buildId-1);for(const e of a)e.build(this._fragmentCompilationState,a);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=Zo._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(console.log("Vertex shader:"),console.log(this._vertexCompilationState.compilationString),console.log("Fragment shader:"),console.log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const o=this.getScene().meshes;for(const e of o)if(e.subMeshes)for(const t of e.subMeshes){if(t.getMaterial()!==this)continue;if(!t.materialDefines)continue;const e=t.materialDefines;e.markAllAsDirty(),e.reset()}}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,n=t.TANGENT;t.NORMAL=e.isVerticesDataPresent(Lt.NormalKind),t.TANGENT=e.isVerticesDataPresent(Lt.TangentKind);let r=!1;for(let i=1;i<=6;++i){const n=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),r=r||t["UV"+i]!==n}(i!==t.NORMAL||n!==t.TANGENT||r)&&t.markAsAttributesDirty()}createPostProcess(e,t=1,i=1,n,r,s=0,a=5){return this.mode!==Fo.PostProcess?(console.log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,n,r,s,a)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,n=1,r,s,a=0,o=5){let l=this.name+this._buildId;const h=new jo,c=new Ji(l+"PostProcess",this.getScene());let u=this._buildId;return this._processDefines(c,h),O.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new nr(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,n,r,s,h.toString(),a,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,o),e.nodeMaterialSource=this,e.onApplyObservable.add((t=>{u!==this._buildId&&(delete O.ShadersStore[l+"VertexShader"],delete O.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),u=this._buildId),this._processDefines(c,h)&&(O.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),oe.SetImmediate((()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l)))),this._checkInternals(t)})),e}createProceduralTexture(e,t){if(this.mode!==Fo.ProceduralTexture)return console.log("Incompatible material mode"),null;let i=this.name+this._buildId;const n=new Yo(i,e,null,t),r=new Ji(i+"Procedural",this.getScene());r.reservedDataStore={hidden:!0};const s=new jo,a=this._processDefines(r,s);O.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[Lt.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,s.toString(),null==a?void 0:a.fallbacks,void 0);n.nodeMaterialSource=this,n._setEffect(o);let l=this._buildId;return n.onBeforeGenerationObservable.add((()=>{l!==this._buildId&&(delete O.ShadersStore[i+"VertexShader"],delete O.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,s.markAllAsDirty(),l=this._buildId);const e=this._processDefines(r,s);e&&(O.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),oe.SetImmediate((()=>{o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[Lt.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,s.toString(),null==e?void 0:e.fallbacks,void 0),n._setEffect(o)}))),this._checkInternals(o)})),n}_createEffectForParticles(e,t,i,n,r,s,a,o=""){let l=this.name+this._buildId+"_"+t;s||(s=new jo),a||(a=this.getScene().getMeshByName(this.name+"Particle"))||((a=new Ji(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId;const c=[];let u=o;if(!r){const o=this._processDefines(a,s);O.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(c,t),u=c.join("\n"),r=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,s.toString()+"\n"+u,null==o?void 0:o.fallbacks,i,n,e),e.setCustomEffect(r,t)}r.onBindObservable.add((r=>{h!==this._buildId&&(delete O.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,s.markAllAsDirty(),h=this._buildId),c.length=0,e.fillDefines(c,t);const d=c.join("\n");d!==u&&(s.markAllAsDirty(),u=d);const f=this._processDefines(a,s);if(f)return O.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),r=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,s.toString()+"\n"+u,null==f?void 0:f.fallbacks,i,n,e),e.setCustomEffect(r,t),void this._createEffectForParticles(e,t,i,n,r,s,a,o);this._checkInternals(r)}))}_checkInternals(e){if(this._sharedData.animatedInputs){const e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(const t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(const t of this._sharedData.bindableBlocks)t.bind(e,this);for(const t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){this.mode===Fo.Particle?(this._createEffectForParticles(e,Xo.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,Xo.BLENDMODE_MULTIPLY,t,i)):console.log("Incompatible material mode")}createAsShadowDepthWrapper(e){this.mode===Fo.Material?e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene()):console.log("Incompatible material mode")}_processDefines(e,t,i=!1,n){let r=null;const s=this.getScene();if(sn.PrepareDefinesForCamera(s,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach((n=>{n.initializeDefines(e,this,t,i)})),this._sharedData.blocksWithDefines.forEach((r=>{r.prepareDefines(e,this,t,i,n)})),t.isDirty){const i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach((i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)}));const n=[];this._sharedData.dynamicUniformBlocks.forEach((e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,n)}));const s=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach((e=>{-1===s.indexOf(e)&&s.push(e)}));const a=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach((e=>{-1===a.indexOf(e)&&a.push(e)}));const o=new Tn;this._sharedData.blocksWithFallbacks.forEach((t=>{t.provideFallbacks(e,o)})),r={lightDisposed:i,uniformBuffers:n,mergedUniforms:s,mergedSamplers:a,fallbacks:o}}return r}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const n=this.getScene();if(this._sharedData.animatedInputs){const e=n.getFrameId();if(this._animationFrame!==e){for(const e of this._sharedData.animatedInputs)e.animate(n);this._animationFrame=e}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new jo);const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const s=n.getEngine();if(this._prepareDefinesForAttributes(e,r),this._sharedData.blockingBlocks.some((t=>!t.isReady(e,this,r,i))))return!1;const a=this._processDefines(e,r,i,t);if(a){const e=t.effect,i=r.toString();let o=s.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:i,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:r.NUM_MORPH_INFLUENCERS}},s);if(o)if(this._onEffectCreatedObservable&&(Qo.effect=o,Qo.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Qo)),this.allowShaderHotSwapping&&e&&!o.isReady()){if(o=e,r.markAsUnprocessed(),a.lightDisposed)return r._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(o,r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,n.performancePriority!==di.BackwardCompatible&&(this.checkReadyOnlyOnce=!0),0))}get compiledShaders(){return`// Vertex shader\r\n${this._vertexCompilationState.compilationString}\r\n\r\n// Fragment shader\r\n${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){const t=this.getScene();if(!this._activeEffect)return;const i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(const t of this._sharedData.inputBlocks)t._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const n=this.getScene(),r=i.effect;if(!r)return;this._activeEffect=r,this.bindOnlyWorldMatrix(e);const s=this._mustRebind(n,r,t.visibility),a=this._sharedData;if(s){for(const e of a.bindableBlocks)e.bind(r,this,t,i);for(const e of a.forcedBindableBlocks)e.bind(r,this,t,i);for(const e of a.inputBlocks)e._transmit(r,n,this)}else if(!this.isFrozen)for(const e of a.forcedBindableBlocks)e.bind(r,this,t,i);this._afterBind(t,this._activeEffect)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter((e=>e.texture)).map((e=>e.texture))),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)Zo._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(const t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(const e of this.getTextureBlocks().filter((e=>e.texture)).map((e=>e.texture)))e.dispose();for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(){this.BJSNODEMATERIALEDITOR.NodeEditor.Show({nodeMaterial:this})}edit(e){return new Promise((t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),void 0===this.BJSNODEMATERIALEDITOR){const i=e&&e.editorURL?e.editorURL:Zo.EditorURL;Pe.LoadScript(i,(()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(),t()}))}else this._createNodeEditor(),t()}))}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;const e=new Io("Position");e.setAsAttribute("position");const t=new Io("World");t.setAsSystemValue(fo.World);const i=new Eo("WorldPos");e.connectTo(i),t.connectTo(i);const n=new Io("ViewProjection");n.setAsSystemValue(fo.ViewProjection);const r=new Eo("WorldPos * ViewProjectionTransform");i.connectTo(r),n.connectTo(r);const s=new To("VertexOutput");r.connectTo(s);const a=new Io("color");a.value=new it(.8,.8,.8,1);const o=new Ro("FragmentOutput");a.connectTo(o),this.addOutputNode(s),this.addOutputNode(o),this._mode=Fo.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Io("Position");e.setAsAttribute("position2d");const t=new Io("Constant1");t.isConstant=!0,t.value=1;const i=new Oo("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const n=new To("VertexOutput");i.connectTo(n);const r=new Io("Scale");r.visibleInInspector=!0,r.value=new He(1,1);const s=new Do("uv0");e.connectTo(s);const a=new No("UV scale");s.connectTo(a),r.connectTo(a);const o=new xo("CurrentScreen");a.connectTo(o),o.texture=new Si("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const l=new Ro("FragmentOutput");o.connectTo(l,{output:"rgba"}),this.addOutputNode(n),this.addOutputNode(l),this._mode=Fo.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Io("Position");e.setAsAttribute("position2d");const t=new Io("Constant1");t.isConstant=!0,t.value=1;const i=new Oo("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const n=new To("VertexOutput");i.connectTo(n);const r=new Io("Time");r.value=0,r.min=0,r.max=0,r.isBoolean=!1,r.matrixMode=0,r.animationType=_o.Time,r.isConstant=!1;const s=new Io("Color3");s.value=new tt(1,1,1),s.isConstant=!1;const a=new Ro("FragmentOutput"),o=new Oo("VectorMerger");o.visibleInInspector=!1;const l=new qo("Cos");l.operation=Ko.Cos,e.connectTo(o),r.output.connectTo(l.input),l.output.connectTo(o.z),o.xyzOut.connectTo(a.rgb),this.addOutputNode(n),this.addOutputNode(a),this._mode=Fo.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Io("uv");e.setAsAttribute("particle_uv");const t=new yo("ParticleTexture");e.connectTo(t);const i=new Io("Color");i.setAsAttribute("particle_color");const n=new No("Texture * Color");t.connectTo(n),i.connectTo(n);const r=new Mo("ParticleRampGradient");n.connectTo(r);const s=new Wo("ColorSplitter");i.connectTo(s);const a=new Po("ParticleBlendMultiply");r.connectTo(a),t.connectTo(a,{output:"a"}),s.connectTo(a,{output:"a"});const o=new Ro("FragmentOutput");a.connectTo(o),this.addOutputNode(o),this._mode=Fo.Particle}async loadAsync(e,t=""){return Zo.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const n=i.connectedPoint;if(n){const i=n.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}}}generateCode(){let e=[];const t=[],i=["const","var","let"];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,t);const n=[];for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,n);let r=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}");\r\n`;for(const n of t)n.isInput&&-1===e.indexOf(n)&&(r+=n._dumpCode(i,e));for(const t of n)t.isInput&&-1===e.indexOf(t)&&(r+=t._dumpCode(i,e));e=[],r+="\r\n// Connections\r\n";for(const t of this._vertexOutputNodes)r+=t._dumpCodeForOutputConnections(e);for(const t of this._fragmentOutputNodes)r+=t._dumpCodeForOutputConnections(e);r+="\r\n// Output nodes\r\n";for(const e of this._vertexOutputNodes)r+=`nodeMaterial.addOutputNode(${e._codeVariableName});\r\n`;for(const e of this._fragmentOutputNodes)r+=`nodeMaterial.addOutputNode(${e._codeVariableName});\r\n`;return r+="nodeMaterial.build();\r\n",r}serialize(e){const t=e?{}:Et.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(const n of e.outputs)for(const r of t.blocks){const s=i[r.id];if(s)for(const a of r.inputs)if(i[a.targetBlockId]!==e||a.targetConnectionName!==n.name);else{const e=s.getInputByName(a.inputName);if(!e||e.isConnected)continue;n.connectTo(e,!0),this._restoreConnections(s,t,i)}}}parseSerializedObject(e,t="",i=!1){var n;i||this.clear();const r={};for(const i of e.blocks){const e=xe(i.customType);if(e){const n=new e;n._deserialize(i,this.getScene(),t),r[i.id]=n,this.attachedBlocks.push(n)}}for(let t=0;tnew Zo(e,this.getScene(),this.options)),this);return n.id=e,n.name=e,n.parseSerializedObject(i),n._buildId=this._buildId,n.build(!1,!t),n}static Parse(e,t,i=""){const n=Et.Parse((()=>new Zo(e.name,t)),e,t,i);return n.parseSerializedObject(e,i),n.build(),n}static async ParseFromFileAsync(e,t,i,n="",r=!1,s){const a=null!=s?s:new Zo(e,i),o=await i._loadFileAsync(t),l=JSON.parse(o);return a.parseSerializedObject(l,n),r||a.build(),a}static ParseFromSnippetAsync(e,t=f.LastCreatedScene,i="",n,r=!1){return"_BLANK"===e?Promise.resolve(Zo.CreateDefault("blank",t)):new Promise(((s,a)=>{const o=new ee;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const l=JSON.parse(JSON.parse(o.responseText).jsonPayload),h=JSON.parse(l.nodeMaterial);n||((n=Et.Parse((()=>new Zo(e,t)),h,t,i)).uniqueId=t.getUniqueId()),n.parseSerializedObject(h),n.snippetId=e;try{r||n.build(),s(n)}catch(e){a(e)}}else a("Unable to load the snippet "+e)})),o.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),o.send()}))}static CreateDefault(e,t){const i=new Zo(e,t);return i.setToDefault(),i.build(),i}}var Jo,$o;Zo._BuildIdGenerator=0,Zo.EditorURL=`https://unpkg.com/babylonjs-node-editor@${Z.Version}/babylon.nodeEditor.js`,Zo.SnippetUrl="https://snippet.babylonjs.com",Zo.IgnoreTexturesAtLoadTime=!1,et([ct()],Zo.prototype,"ignoreAlpha",void 0),et([ct()],Zo.prototype,"maxSimultaneousLights",void 0),et([ct("mode")],Zo.prototype,"_mode",void 0),et([ct("comment")],Zo.prototype,"comment",void 0),et([ct()],Zo.prototype,"forceAlphaBlending",void 0),Ie("BABYLON.NodeMaterial",Zo),Yi.prototype._projectOnTrianglesToRef=function(e,t,i,n,r,s){const a=Ze.Vector3[0],o=Ze.Vector3[1];let l=1/0;for(let s=this.indexStart;s{if(this._controllers[e.uniqueId])return;const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:n}=this._generateNewTouchPointMesh(),r=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:n,currentAnimationState:Jo.DEHYDRATED,grabRay:new Cs(new Ye,new Ye),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:el._IdCounter++,pickedPointVisualCue:r},this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new tt(.8,.8,.8),this.selectionMeshPickedColor=new tt(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=$o.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case Jo.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===Jo.HOVER)break;case Jo.HOVER:if(e.touchCollisionMeshFunction(!0),t===Jo.TOUCH)break}else switch(e.currentAnimationState){case Jo.TOUCH:if(e.touchCollisionMeshFunction(!1),t===Jo.HOVER)break;case Jo.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===Jo.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var n;const r=this._controllers[e];r.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(Ze.Vector3[0]),r.grabRay.direction.copyFrom(Ze.Vector3[0]),this._options.nearInteractionControllerMode!==$o.CENTERED_IN_FRONT||(null===(n=r.xrController)||void 0===n?void 0:n.inputSource.hand)||(r.xrController.getWorldPointerRayToRef(this._tmpRay),r.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),r.grabRay.length=this._nearGrabLengthScale*this._hoverRadius,r.touchCollisionMesh.position.copyFrom(r.grabRay.origin)}_onXRFrame(e){Object.keys(this._controllers).forEach((t=>{var i;const n=this._controllers[t],r=null===(i=n.xrController)||void 0===i?void 0:i.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!n.xrController||!r&&(!this._options.nearInteractionControllerMode||!n.xrController.inputSource.gamepad))return void(n.pick=null);if(n.hoverInteraction=!1,n.nearInteraction=!1,!n.xrController)return;if(r){const i=r.get("index-finger-tip");if(i){const n=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(n&&n.transform){const e=this._scene.useRightHandedSystem?1:-1;Ze.Vector3[0].set(n.transform.position.x,n.transform.position.y,n.transform.position.z*e),Ze.Quaternion[0].set(n.transform.orientation.x,n.transform.orientation.y,n.transform.orientation.z*e,n.transform.orientation.w*e),this._processTouchPoint(t,Ze.Vector3[0],Ze.Quaternion[0])}}}else if(n.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==$o.DISABLED){let e=n.xrController.pointer;n.xrController.grip&&this._options.nearInteractionControllerMode===$o.CENTERED_ON_CONTROLLER&&(e=n.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}const s=(e,t)=>{let i=null;return i=t&&t.hit?e&&e.hit?t.distance{let t=new wt,i=!1;const n=e&&e.pickedPoint&&e.hit;return(null==e?void 0:e.pickedPoint)&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),n&&!i&&(t=e),t};if(!n.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(n,this._hoverRadius,this._utilityLayerScene,(e=>this._nearInteractionPredicate(e))));const i=s(this._pickWithSphere(n,this._hoverRadius,this._scene,(e=>this._nearInteractionPredicate(e))),t);if(i&&i.hit&&(e=a(i),e.hit&&(n.hoverInteraction=!0)),n.hoverInteraction){let t=null;const i=r?this._pickRadius:this._controllerPickRadius;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(n,i,this._utilityLayerScene,(e=>this._nearPickPredicate(e))));const o=a(s(this._pickWithSphere(n,i,this._scene,(e=>this._nearPickPredicate(e))),t));o.hit&&(e=o,n.nearInteraction=!0)}n.stalePick=n.pick,n.pick=e,n.pick&&n.pick.pickedPoint&&n.pick.hit?(n.meshUnderPointer=n.pick.pickedMesh,n.pickedPointVisualCue.position.copyFrom(n.pick.pickedPoint),n.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(n.id,!0)):(n.meshUnderPointer=null,n.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(n.id,!1))}let o=Jo.DEHYDRATED;n.grabInteraction||n.nearInteraction?o=Jo.TOUCH:n.hoverInteraction&&(o=Jo.HOVER),this._handleTransitionAnimation(n,o)}))}get _utilityLayerScene(){return this._options.customUtilityLayerScene||ro.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||ro.DefaultUtilityLayer.utilityLayerScene:this._scene,t=bn("nearInteraction",{diameter:.0105},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=qe.Identity();const i=new er("targetMat",e);return i.specularColor=tt.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.nearInteractionTargetMesh=null))}));const n=n=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),n&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i)):!n&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!n||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;n(t)}})):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;n(t)}})))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{const e=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i))},n=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)};t.eventListeners={selectend:n,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",n)}}_detachController(e){const t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach((e=>{const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame((()=>{const e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new wt,e)})),delete this._controllers[e],this._attachedController===e)){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||ro.DefaultUtilityLayer.utilityLayerScene:this._scene,t=bn("PickSphere",{diameter:1},e);t.isVisible=!1,this._options.motionControllerOrbMaterial?t.material=this._options.motionControllerOrbMaterial:Zo.ParseFromSnippetAsync("8RUNKL#3",e).then((e=>{t.material=e}));const i=new Pn;i.setEasingMode(yn.EASINGMODE_EASEINOUT);const n=new Ye(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius),r=this._controllerPickRadius*(4/3),s=new Ye(r,r,r),a=this._controllerPickRadius*(7/6),o=new Ye(a,a,a),l=.8*this._controllerPickRadius,h=new Ye(l,l,l),c=1.5*this._controllerPickRadius,u=[{frame:0,value:n},{frame:10,value:new Ye(c,c,c)},{frame:18,value:s}],d=[{frame:0,value:s},{frame:10,value:h},{frame:18,value:n}],f=[{frame:0,value:Ye.ZeroReadOnly},{frame:12,value:o},{frame:15,value:n}],_=[{frame:0,value:n},{frame:10,value:Ye.ZeroReadOnly},{frame:15,value:Ye.ZeroReadOnly}],p=new Fn("touch","scaling",60,Fn.ANIMATIONTYPE_VECTOR3,Fn.ANIMATIONLOOPMODE_CONSTANT),m=new Fn("release","scaling",60,Fn.ANIMATIONTYPE_VECTOR3,Fn.ANIMATIONLOOPMODE_CONSTANT),g=new Fn("hydrate","scaling",60,Fn.ANIMATIONTYPE_VECTOR3,Fn.ANIMATIONLOOPMODE_CONSTANT),v=new Fn("dehydrate","scaling",60,Fn.ANIMATIONTYPE_VECTOR3,Fn.ANIMATIONLOOPMODE_CONSTANT);return p.setEasingFunction(i),m.setEasingFunction(i),g.setEasingFunction(i),v.setEasingFunction(i),p.setKeys(u),m.setKeys(d),g.setKeys(f),v.setKeys(_),{touchCollisionMesh:t,touchCollisionMeshFunction:i=>{const n=i?p:m;e.beginDirectAnimation(t,[n],0,18,!1,1)},hydrateCollisionMeshFunction:i=>{const n=i?g:v;i&&(t.isVisible=!0),e.beginDirectAnimation(t,[n],0,15,!1,1,(()=>{i||(t.isVisible=!1)}))}}}_pickWithSphere(e,t,i,n){const r=new wt;if(r.distance=1/0,e.touchCollisionMesh&&e.xrController){const s=e.touchCollisionMesh.position,a=Ui.CreateFromCenterAndRadius(s,t);for(let t=0;th&&(l=0,o.copyFrom(t.center)),-1!==l&&l()=>new el(e,t)),el.Version,!0);class tl{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class il{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new n,this._onSessionGranted=e=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw Pe.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";const e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor";let n=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+("undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";n+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const r=document.createElement("style");r.appendChild(document.createTextNode(n)),document.getElementsByTagName("head")[0].appendChild(r);const s=document.createElement("button");s.className="babylonVRicon",s.title=`${e} - ${i}`,this._buttons.push(new tl(s,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",s.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}const i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce((()=>{this.dispose()})))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;const i=this._buttons.map((t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode)));e.onStateChangedObservable.add((e=>{e==ra.NOT_IN_XR&&this._updateButtons(null)})),(await Promise.all(i)).forEach(((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):Pe.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)}))}static async CreateAsync(e,t,i){const n=new il(e,i);return await n.setHelperAsync(t,i.renderTarget||void 0),n}async _enterXRWithButtonIndex(e=0){if(this._helper.state==ra.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==ra.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,n=i.title;i.title="Error entering XR session : "+n,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach((e=>{e.update(this._activeButton)})),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}gn._instancedMeshFactory=(e,t)=>{const i=new nl(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class nl extends Ji{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const e of t.getAnimationRanges())null!=e&&this.createAnimationRange(e.name,e.from,e.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}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&&p.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||p.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!==Pi.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new Qe);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,Ze.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(Ze.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(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&&(u.push(Lt.MatricesIndicesExtraKind),u.push(Lt.MatricesWeightsExtraKind));const t=e.skeleton;c.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),d.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 v=e?e.morphTargetManager:null;if(v){const e=v.supportsUVs&&-1!==c.indexOf("#define UV1"),t=v.supportsTangents&&-1!==c.indexOf("#define TANGENT"),i=v.supportsNormals&&-1!==c.indexOf("#define NORMAL");g=v.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"),v.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")),sn.PrepareAttributesForBakedVertexAnimation(u,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&&($i(_),en(this,l,c)),this.customShaderNameResolve&&(_=_.slice(),p=p.slice(),m=m.slice(),f=this.customShaderNameResolve(f,_,p,m,c,u));const E=o?i._getDrawWrapper():this._drawWrapper,T=null!==(n=null==E?void 0:E.effect)&&void 0!==n?n:null,C=null!==(r=null==E?void 0:E.defines)&&void 0!==r?r:null,R=c.join("\n");let A=T;return C!==R&&(A=h.createEffect(f,{attributes:u,uniformsNames:_,uniformBuffersNames:p,samplers:m,defines:R,fallbacks:d,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:g},shaderLanguage:this._options.shaderLanguage},h),o?i.setEffect(A,R,this._materialContext):E&&E.setEffect(A,R),this._onEffectCreatedObservable&&(rl.effect=A,rl.subMesh=null!==(s=null!=i?i:null==e?void 0:e.subMeshes[0])&&void 0!==s?s:null,this._onEffectCreatedObservable.notifyObservers(rl))),A._wasPreviouslyUsingInstances=!!t,null!==(a=!(null==A?void 0:A.isReady()))&&void 0!==a&&!a&&(T!==A&&l.resetCachedMaterial(),A._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 r;const s=n&&this._storeEffectOnSubMeshes,a=null!=i?i:s?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&&sn.BindMorphTargetParameters(t,a);const i=t.bakedVertexAnimationManager;i&&i.isEnabled&&(null===(r=t.bakedVertexAnimationManager)||void 0===r||r.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 sl(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 sl(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let r;for(r in e.stencil&&n.stencil.parse(e.stencil,t,i),e.textures)n.setTexture(r,Si.Parse(e.textures[r],t,i));for(r in e.textureArrays){const s=e.textureArrays[r],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(r,t)}for(r in e.colors4)n.setColor4(r,it.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const t=e.colors4Arrays[r].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>it.FromArray(e)));n.setColor4Array(r,t)}for(r in e.vectors2)n.setVector2(r,He.FromArray(e.vectors2[r]));for(r in e.vectors3)n.setVector3(r,Ye.FromArray(e.vectors3[r]));for(r in e.vectors4)n.setVector4(r,Ke.FromArray(e.vectors4[r]));for(r in e.quaternions)n.setQuaternion(r,qe.FromArray(e.quaternions[r]));for(r in e.matrices)n.setMatrix(r,Qe.FromArray(e.matrices[r]));for(r in e.matrixArray)n._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)n.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)n.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)n.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)n.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)n.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)n.setArray4(r,e.quaternionsArrays[r]);return n}static ParseFromFileAsync(e,t,i,n=""){return new Promise(((r,s)=>{const a=new ee;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const t=JSON.parse(a.responseText),s=this.Parse(t,i||f.LastCreatedScene,n);e&&(s.name=e),r(s)}else s("Unable to load the ShaderMaterial")})),a.open("GET",t),a.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((n,r)=>{const s=new ee;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){const r=JSON.parse(JSON.parse(s.responseText).jsonPayload),a=JSON.parse(r.shaderMaterial),o=this.Parse(a,t||f.LastCreatedScene,i);o.snippetId=e,n(o)}else r("Unable to load the snippet "+e)})),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()}))}}sl.SnippetUrl="https://snippet.babylonjs.com",sl.CreateFromSnippetAsync=sl.ParseFromSnippetAsync,Ie("BABYLON.ShaderMaterial",sl);P.ShadersStore.colorPixelShader="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n#define CUSTOM_FRAGMENT_MAIN_END\n}";P.ShadersStore.colorVertexShader="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\ngl_Position=viewProjection*worldPos;\n} else {\ngl_Position=viewProjectionR*worldPos;\n}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}",gn._LinesMeshParser=(e,t)=>al.Parse(e,t);class al extends gn{constructor(e,t=null,i=null,n=null,r,s,a,o){super(e,t,i,n,r),this.useVertexColor=s,this.useVertexAlpha=a,this.color=new tt(1,1,1),this.alpha=1,n&&(this.color=n.color.clone(),this.alpha=n.alpha,this.useVertexColor=n.useVertexColor,this.useVertexAlpha=n.useVertexAlpha),this.intersectionThreshold=.1;const l={attributes:[Lt.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===a?l.needAlphaBlending=!1:l.defines.push("#define VERTEXALPHA"),s?(l.defines.push("#define VERTEXCOLOR"),l.attributes.push(Lt.ColorKind)):(l.uniforms.push("color"),this._color4=new it),o?this.material=o:(this.material=new sl("colorShader",this.getScene(),"color",l,!1),this.material.doNotSerialize=!0)}_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=hn.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(this._userInstancedBuffersStorage?this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,i),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const n=this.getScene().getEngine();return this._unIndexed?n.drawArraysType(hn.LineListDrawMode,e.verticesStart,e.verticesCount,i):n.drawElementsType(hn.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new al(e,this.getScene(),t,this,i)}createInstance(e){const t=new ol(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const e in this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new al(e.name,t);return i.color=tt.FromArray(e.color),i.alpha=e.alpha,i}}class ol extends nl{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function ll(e){const t=[],i=[],n=e.lines,r=e.colors,s=[];let a=0;for(let e=0;e0&&(t.push(a-1),t.push(a)),a++}}const o=new Li;return o.indices=t,o.positions=i,r&&(o.colors=s),o}function hl(e){const t=e.dashSize||3,i=e.gapSize||1,n=e.dashNb||200,r=e.points,s=new Array,a=new Array,o=Ye.Zero();let l=0,h=0,c=0,u=0,d=0,f=0,_=0;for(_=0;_{const s=Date.now();i=s-n;const a={startTime:n,currentTime:s,deltaTime:i,completeRate:i/e.timeout,payload:t};e.onTick&&e.onTick(a),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(r),e.onAborted&&e.onAborted(a)),i>=e.timeout&&(e.contextObservable.remove(r),e.onEnded&&e.onEnded(a))}),e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return r}Li.CreateLineSystem=ll,Li.CreateDashedLines=hl,gn.CreateLines=(e,t,i=null,n=!1,r=null)=>cl(e,{points:t,updatable:n,instance:r},i),gn.CreateDashedLines=(e,t,i,n,r,s=null,a,o)=>function(e,t,i=null){const n=t.points,r=t.instance,s=t.gapSize||1,a=t.dashSize||3;if(r){const e=e=>{const t=Ye.Zero(),i=e.length/6;let s=0,a=0,o=0,l=0,h=0,c=0,u=0,d=0;for(u=0;u{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0}};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController){const i=e.motionController.getComponentOfType(Ha.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(Ha.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){const i=e.motionController.getMainComponent();if(!i)return;t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add((()=>{this.teleportationEnabled&&i.changes.pressed&&(i.changes.pressed.current?(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,dl({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})):(t.teleportationState.forward=!1,this._currentTeleportationControllerId=""))}))}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add((i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,qe.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);const e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,(e=>-1!==this._floorMeshes.indexOf(e)));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout((()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))})):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;const e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);qe.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}else this._xrSessionManager.scene.onPointerObservable.add((i=>{i.type===Wt.POINTERDOWN?(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,dl({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})):i.type===Wt.POINTERUP&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="")}))},this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._setTargetMeshVisibility(!1)}get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,(e=>"rotationCone"===e.name));t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return!!super.attach()&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0)}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){const t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(-1===t)for(let i=0;i{if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;const t=this._floorMeshes.indexOf(e);return-1!==t&&this._floorMeshes[t].absolutePosition.y!(!this._options.pickBlockerMeshes||-1===this._options.pickBlockerMeshes.indexOf(e))||-1!==this._floorMeshes.indexOf(e)));if(a&&a.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(a.pickedMesh))return;a&&a.pickedPoint&&(t=!0,this._setTargetMeshPosition(a),this._setTargetMeshVisibility(!0),this._showParabolicPath(a))}this._setTargetMeshVisibility(t)}else this._setTargetMeshVisibility(!1)}else this._setTargetMeshVisibility(!1)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||ro.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=_a("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const i=512,n=new Os("teleportationPlaneDynamicTexture",i,e,!0);n.hasAlpha=!0;const r=n.getContext(),s=i/2,a=i/2,o=200;r.beginPath(),r.arc(s,a,o,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),n.update();const l=new er("teleportationPlaneMaterial",e);l.diffuseTexture=n,t.material=l}const i=ha("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const t=new Fn("animationInnerCircle","position.y",30,Fn.ANIMATIONTYPE_FLOAT,Fn.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),t.setKeys(n);const r=new On;r.setEasingMode(yn.EASINGMODE_EASEINOUT),t.setEasingFunction(r),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}const n=oa("rotationCone",{diameterTop:0,tessellation:4},e);if(n.isPickable=!1,n.scaling.set(.5,.12,.2),n.rotate(gi.X,Math.PI/2),n.position.z=.6,n.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,n.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const t=new er("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new tt(.3,.3,1):t.diffuseColor=new tt(.3,.3,1),t.alpha=.9,i.material=t,n.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,n.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,n=Number.MAX_VALUE;if(this._snapToPositions.length){const r=t*t;this._snapToPositions.forEach((t=>{const s=Ye.DistanceSquared(t,e);s<=r&&s{t.isVisible=e})),e?this._selectionFeature&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&this._selectionFeature.attach()))}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||ro.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],n=vi.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(n.getPoints(),e):this._quadraticBezierCurve=cl("teleportation path line",{points:n.getPoints(),instance:this._quadraticBezierCurve,updatable:!0},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){const t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint))if(this.skipNextTeleportation)this.skipNextTeleportation=!1;else if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const e=this._options.xrInput.xrCamera.realWorldHeight;this._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=e,qe.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}fl.Name=ka.TELEPORTATION,fl.Version=1,Ga.AddWebXRFeature(fl.Name,((e,t)=>()=>new fl(e,t)),fl.Version,!0);class _l{constructor(){}static CreateAsync(e,t={}){const i=new _l;if(e.onDisposeObservable.addOnce((()=>{i.dispose()})),!t.disableDefaultUI){const n={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?n.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:n.optionalFeatures=t.optionalFeatures),i.enterExitUI=new il(e,n)}return Wa.CreateAsync(e).then((e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new io(e.sessionManager,e.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const e={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(so.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(fl.Name,t.useStablePlugins?"stable":"latest",{floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId,...t.teleportationOptions}),i.teleportation.setSelectionFeature(i.pointerSelection))}return t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(el.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0,...t.nearInteractionOptions})),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)})).then((()=>i)).catch((e=>(p.Error("Error initializing XR"),p.Error(e),i)))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}mi.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;ee.isVisible&&e.isEnabled())),n=t.max.subtract(t.min),r=t.min.add(n.scale(.5));let s,a=1.5*n.length();if(isFinite(a)||(a=1,r.copyFromFloats(0,0,0)),e){const e=new Hn("default camera",-Math.PI/2,Math.PI/2,a,r,this);e.lowerRadiusLimit=.01*a,e.wheelPrecision=100/a,s=e}else{const e=new ls("default camera",new Ye(r.x,r.y,-a),this);e.setTarget(r),s=e}s.minZ=.01*a,s.maxZ=1e3*a,s.speed=.2*a,this.activeCamera=s,i&&s.attachControl()}},mi.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},mi.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,n=0,r=!0){if(!e)return p.Warn("Can not create default skybox without environment texture."),null;r&&e&&(this.environmentTexture=e);const s=$r("hdrSkyBox",{size:i},this);if(t){const t=new Wr("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Si.SKYBOX_MODE),t.microSurface=1-n,t.disableLighting=!0,t.twoSidedLighting=!0,s.material=t}else{const t=new er("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Si.SKYBOX_MODE),t.disableLighting=!0,s.material=t}return s.isPickable=!1,s.infiniteDistance=!0,s.ignoreCameraMaxZ=!0,s},mi.prototype.createDefaultEnvironment=function(e){return es?new es(e,this):null},mi.prototype.createDefaultVRExperience=function(e={}){return new va(this,e)},mi.prototype.createDefaultXRExperienceAsync=function(e={}){return _l.CreateAsync(this,e).then((e=>e))},K.prototype.createExternalTexture=function(e){return null},K.prototype.setExternalTexture=function(e,t){throw new Error("setExternalTexture: This engine does not support external textures!")};var pl,ml,gl=i(379),vl=i.n(gl),El=i(795),Tl=i.n(El),Cl=i(569),Rl=i.n(Cl),Al=i(565),bl=i.n(Al),Sl=i(216),Il=i.n(Sl),xl=i(589),yl=i.n(xl),Ml=i(518),Pl={};Pl.styleTagTransform=yl(),Pl.setAttributes=bl(),Pl.insert=Rl().bind(null,"head"),Pl.domAPI=Tl(),Pl.insertStyleElement=Il(),vl()(Ml.Z,Pl),Ml.Z&&Ml.Z.locals&&Ml.Z.locals,pl=window.amp,ml={enableVR:!0,fov:1.18,defaultCameraOrientationX:0,defaultCameraOrientationY:-Math.PI/2,disableWebGL2Support:!1,hardwareScalingLevel:1,videoType:"monoscopicPanoramic"},pl.plugin("threeSixty",(function(e){var t,i,n,r,s,a,o=this,l=function(e){var t,i,n;for(i=1;i