import{k as Iu,l as Au,W as nt,C as ka,P as Ar,n as Va,m as ql,B as $l,o as Cu,p as Mu,q as Ru,r as Pu,s as wu,t as Du,u as Fu,v as Ou,w as Lu,x as Bu,y as Nu,z as Uu,A as ku,D as Yo,E as jl,_ as Zl,R as Ql}from"./index-17a5ec1d.js";import{V as Vu,f as Nt,c as Ei,i as qo,l as Kn,m as cs,A as Gu,T as zu,C as $o,D as Wu,E as Xu,t as Ni,p as Ui,x as Hu,a2 as jo,j as $r,h as Ku,_ as Yu,a as qu,b as $u,o as ju,d as Zu}from"./vuetify-4c65b4c3.js";import{E as Qu,b as Ju,a as ef}from"./codemirror-0a1db0c7.js";import"./overlayscrollbars-44d87bcf.js";import"./echarts-ff51454d.js";function tf(a,e){return e===void 0&&(e={}),function(t,i){Iu(e,t,i),Au(function(s,n){(s.props||(s.props={}))[a]=e,(s.computed||(s.computed={}))[n]={get:function(){return this[a]},set:function(r){this.$emit("update:"+a,r)}}})(t,i)}}class sf{constructor(e,t=!1,i,s){this.initialize(e,t,i,s)}initialize(e,t=!1,i,s){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=s,this}}class nf{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class Q{static FromPromise(e,t){const i=new Q;return e.then(s=>{i.notifyObservers(s)}).catch(s=>{if(t)t.notifyObservers(s);else throw s}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new sf(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,n=!1){if(!e)return null;const r=new nf(e,t,s);return r.unregisterOnNextCall=n,i?this._observers.unshift(r):this._observers.push(r),this._onObserverAdded&&this._onObserverAdded(r),this._hasNotified&&this.notifyIfTriggered&&this._lastNotifiedValue!==void 0&&this.notifyObserver(r,this._lastNotifiedValue),r._remove=()=>{this.remove(r)},r}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return e?(e._remove=null,this._observers.indexOf(e)!==-1?(this._deferUnregister(e),!0):!1):!1}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 i!==-1?(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0):!1}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,s,n){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const r=this._eventState;r.mask=t,r.target=i,r.currentTarget=s,r.skipNextObservers=!1,r.lastReturnValue=e,r.userInfo=n;for(const o of this._observers)if(!o._willBeUnregistered&&(o.mask&t&&(o.unregisterOnNextCall&&this._deferUnregister(o),o.scope?r.lastReturnValue=o.callback.apply(o.scope,[e,r]):r.lastReturnValue=o.callback(e,r)),r.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const s=this._eventState;s.mask=i,s.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,s)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new Q;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 rf{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,s=1,n=2,r=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=s,this.samplingMode=n,this._comparisonFunction=r,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}var Zo;(function(a){a[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"})(Zo||(Zo={}));class Et extends rf{get useMipMaps(){return this.generateMipMaps}set useMipMaps(e){this.generateMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new Q,this.onErrorObservable=new Q,this.onRebuildCallback=null,this.width=0,this.height=0,this.depth=0,this.baseWidth=0,this.baseHeight=0,this.baseDepth=0,this.invertY=!1,this._invertVScale=!1,this._associatedChannel=-1,this._source=0,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._creationFlags=0,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._hardwareTexture=null,this._maxLodLevel=null,this._references=1,this._gammaSpace=null,this._premulAlpha=!1,this._dynamicTextureSource=null,this._engine=e,this._source=t,this._uniqueId=Et._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){var t,i;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){const s=this.onRebuildCallback(this),n=r=>{r._swapAndDie(this,!1),this.isReady=s.isReady};s.isAsync?s.proxy.then(n):n(s.proxy);return}let e;switch(this.source){case 2:break;case 1:e=this._engine.createTexture((t=this._originalUrl)!=null?t:this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,s=>{s._swapAndDie(this,!1),this.isReady=!0},null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer);return;case 3:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case 10:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 11:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 4:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case 7:e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer,ArrayBuffer.isView(this._buffer)?this._buffer:null);return;case 8:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,(i=this._originalFormat)!=null?i:this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case 13:return;case 9:e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,s=>{s&&s._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension),e._sphericalPolynomial=this._sphericalPolynomial;return}}_swapAndDie(e,t=!0){var n;(n=this._hardwareTexture)==null||n.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const i=this._engine.getLoadedTexturesCache();let s=i.indexOf(this);s!==-1&&i.splice(s,1),s=i.indexOf(e),s===-1&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._references===0&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}Et._Counter=0;class Ce{static get LastCreatedEngine(){return this.Instances.length===0?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}Ce.Instances=[];Ce.OnEnginesDisposedObservable=new Q;Ce._LastCreatedScene=null;Ce.UseFallbackTexture=!0;Ce.FallbackTexture="";class af{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return this.program?this.isParallelCompiled?this.engine._isRenderingStateCompiled(this):!0:!1}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,s,n,r,o,l){const h=this.engine;if(h.supportsUniformBuffers)for(const f in t)e.bindUniformBlock(f,t[f]);this.engine.getUniforms(this,i).forEach((f,d)=>{s[i[d]]=f}),this._uniforms=s;let u;for(u=0;u{r[f]=d});for(const f of h.getAttributes(this,o))l.push(f)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return i!==void 0&&i===s?!1:(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||s.length!==2)return s=[t,i],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),n}_cacheFloat3(e,t,i,s){let n=this._valueCache[e];if(!n||n.length!==3)return n=[t,i,s],this._valueCache[e]=n,!0;let r=!1;return n[0]!==t&&(n[0]=t,r=!0),n[1]!==i&&(n[1]=i,r=!0),n[2]!==s&&(n[2]=s,r=!0),r}_cacheFloat4(e,t,i,s,n){let r=this._valueCache[e];if(!r||r.length!==4)return r=[t,i,s,n],this._valueCache[e]=r,!0;let o=!1;return r[0]!==t&&(r[0]=t,o=!0),r[1]!==i&&(r[1]=i,o=!0),r[2]!==s&&(r[2]=s,o=!0),r[3]!==n&&(r[3]=n,o=!0),o}setInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,n){this._cacheFloat4(e,t,i,s,n)&&(this.engine.setInt4(this._uniforms[e],t,i,s,n)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,n){this._cacheFloat4(e,t,i,s,n)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,n)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];i!==void 0&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,n){this._cacheFloat4(e,t,i,s,n)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,n)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}const Qo={};function Te(a,e=!1){if(!(e&&Qo[a]))return Qo[a]=!0,"".concat(a," needs to be imported before as it contains a side-effect required by your code.")}function St(){return typeof window<"u"}function Xs(){return typeof navigator<"u"}function xn(){return typeof document<"u"}function Ga(a){let e="",t=a.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}const or={};function Jl(a,e,t=""){return t+(e?e+"\n":"")+a}function eh(a,e,t,i,s,n,r){const o=r||or.loadFile;if(o)return o(a,e,t,i,s,n);throw Te("FileTools")}function th(a,e,t,i){if(a){e?a.IS_NDC_HALF_ZRANGE="":delete a.IS_NDC_HALF_ZRANGE,t?a.USE_REVERSE_DEPTHBUFFER="":delete a.USE_REVERSE_DEPTHBUFFER,i?a.USE_EXACT_SRGB_CONVERSIONS="":delete a.USE_EXACT_SRGB_CONVERSIONS;return}else{let s="";return e&&(s+="#define IS_NDC_HALF_ZRANGE"),t&&(s&&(s+="\n"),s+="#define USE_REVERSE_DEPTHBUFFER"),i&&(s&&(s+="\n"),s+="#define USE_EXACT_SRGB_CONVERSIONS"),s}}const ua=new WeakMap,of={_webGLVersion:2,cachedPipelines:{}};function li(a){let e=ua.get(a);if(!e){if(!a)return of;e={_webGLVersion:a.TEXTURE_BINDING_3D?2:1,_context:a,cachedPipelines:{}},ua.set(a,e)}return e}function lf(a){ua.delete(a)}function ih(a,e,t,i,s,n){var h;const r=li(i);n||(n=(h=r._createShaderProgramInjection)!=null?h:za);const o=fa(e,"vertex",i,r._contextWasLost),l=fa(t,"fragment",i,r._contextWasLost);return n(a,o,l,i,s,r.validateShaderPrograms)}function sh(a,e,t,i,s,n=null,r){var u;const o=li(s);r||(r=(u=o._createShaderProgramInjection)!=null?u:za);const l=o._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"",h=Jo(e,"vertex",i,l,s,o._contextWasLost),c=Jo(t,"fragment",i,l,s,o._contextWasLost);return r(a,h,c,s,n,o.validateShaderPrograms)}function hf(a,e){const t=new af,i=li(a);return i.parallelShaderCompile&&(t.isParallelCompiled=!0),t.context=i._context,t}function za(a,e,t,i,s=null,n){const r=i.createProgram();if(a.program=r,!r)throw new Error("Unable to create program");return i.attachShader(r,e),i.attachShader(r,t),i.linkProgram(r),a.context=i,a.vertexShader=e,a.fragmentShader=t,a.isParallelCompiled||nh(a,i,n),r}function nh(a,e,t){const i=a.context,s=a.vertexShader,n=a.fragmentShader,r=a.program;if(!i.getProgramParameter(r,i.LINK_STATUS)){if(!e.getShaderParameter(s,e.COMPILE_STATUS)){const h=e.getShaderInfoLog(s);if(h)throw a.vertexCompilationError=h,new Error("VERTEX SHADER "+h)}if(!e.getShaderParameter(n,e.COMPILE_STATUS)){const h=e.getShaderInfoLog(n);if(h)throw a.fragmentCompilationError=h,new Error("FRAGMENT SHADER "+h)}const l=i.getProgramInfoLog(r);if(l)throw a.programLinkError=l,new Error(l)}if(t&&(i.validateProgram(r),!i.getProgramParameter(r,i.VALIDATE_STATUS))){const h=i.getProgramInfoLog(r);if(h)throw a.programValidationError=h,new Error(h)}i.deleteShader(s),i.deleteShader(n),a.vertexShader=void 0,a.fragmentShader=void 0,a.onCompiled&&(a.onCompiled(),a.onCompiled=void 0)}function cf(a,e,t,i,s,n,r,o,l,h="",c,u){var p,g;const f=li(a.context);c||(c=(p=f.createRawShaderProgramInjection)!=null?p:ih),u||(u=(g=f.createShaderProgramInjection)!=null?g:sh);const d=a;i?d.program=c(d,e,t,d.context,l):d.program=u(d,e,t,o,d.context,l),d.program.__SPECTOR_rebuildProgram=r}function Jo(a,e,t,i,s,n){return fa(Jl(a,t,i),e,s,n)}function fa(a,e,t,i){const s=t.createShader(e==="vertex"?t.VERTEX_SHADER:t.FRAGMENT_SHADER);if(!s){let n=t.NO_ERROR,r=t.NO_ERROR;for(;(r=t.getError())!==t.NO_ERROR;)n=r;throw new Error("Something went wrong while creating a gl ".concat(e," shader object. gl error=").concat(n,", gl isContextLost=").concat(t.isContextLost(),", _contextWasLost=").concat(i))}return t.shaderSource(s,a),t.compileShader(s),s}function uf(a,e){e.useProgram(a)}function ff(a,e){const t=a;if(!t.isParallelCompiled){e(a);return}const i=t.onCompiled;t.onCompiled=()=>{i==null||i(),e(a)}}function rh(a){return a.getPipelineContext===void 0}class U{static _CheckLimit(e,t){let i=U._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},U._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){var n;const i=U._LogLimitOutputs[e];if(!i||!U.MessageLimitReached)return;const s=this._Levels[t];i.current===i.limit&&U[s.name](U.MessageLimitReached.replace(/%LIMIT%/g,""+i.limit).replace(/%TYPE%/g,(n=s.name)!=null?n:""))}static _AddLogEntry(e){U._LogCache=e+U._LogCache,U.OnNewCacheEntry&&U.OnNewCacheEntry(e)}static _FormatMessage(e){const t=s=>s<10?"0"+s:""+s,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){const s=Array.isArray(t)?t[0]:t;if(i!==void 0&&!U._CheckLimit(s,i))return;const n=U._FormatMessage(s),r=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];r.logFunc&&r.logFunc("BJS - "+n,...o);const l="
").concat(n,"

");U._AddLogEntry(l),U._GenerateLimitMessage(s,e)}static get LogCache(){return U._LogCache}static ClearLogCache(){U._LogCache="",U._LogLimitOutputs={},U.errorsCount=0}static set LogLevels(e){U.Log=U._LogDisabled,U.Warn=U._LogDisabled,U.Error=U._LogDisabled,[U.MessageLogLevel,U.WarningLogLevel,U.ErrorLogLevel].forEach(t=>{if((e&t)===t){const i=this._Levels[t];U[i.name]=U._LogEnabled.bind(U,t)}})}}U.NoneLogLevel=0;U.MessageLogLevel=1;U.WarningLogLevel=2;U.ErrorLogLevel=4;U.AllLogLevel=7;U.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";U._LogCache="";U._LogLimitOutputs={};U._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];U.errorsCount=0;U.Log=U._LogEnabled.bind(U,U.MessageLogLevel);U.Warn=U._LogEnabled.bind(U,U.WarningLogLevel);U.Error=U._LogEnabled.bind(U,U.ErrorLogLevel);class df{constructor(){this.shaderLanguage=0}postProcessor(e,t,i,s,n){if(n.drawBuffersExtensionDisabled){const r=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(r,"")}return e}}const pf=/(flat\s)?\s*varying\s*.*/;class _f{constructor(){this.shaderLanguage=0}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return pf.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,n=/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;if(e=e.replace(n,""),e=e.replace(/texture2D\s*\(/g,"texture("),i){const r=e.search(/layout *\(location *= *0\) *out/g)!==-1;e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/void\s+?main\s*\(/g,(s||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(t.indexOf("#define MULTIVIEW")!==-1)return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}class on{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=on._Counter++}}on._Counter=0;class Sn extends on{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}function gf(a){let e=1;do e*=2;while(ea-t?t:e}function Xa(a){return a--,a|=a>>1,a|=a>>2,a|=a>>4,a|=a>>8,a|=a>>16,a++,a}function Cr(a){return a=a|a>>1,a=a|a>>2,a=a|a>>4,a=a|a>>8,a=a|a>>16,a-(a>>1)}function fi(a,e,t=2){let i;switch(t){case 1:i=Cr(a);break;case 2:i=Wa(a);break;case 3:default:i=Xa(a);break}return Math.min(i,e)}class K{static GetShadersRepository(e=0){return e===0?K.ShadersRepository:K.ShadersRepositoryWGSL}static GetShadersStore(e=0){return e===0?K.ShadersStore:K.ShadersStoreWGSL}static GetIncludesShadersStore(e=0){return e===0?K.IncludesShadersStore:K.IncludesShadersStoreWGSL}}K.ShadersRepository="src/Shaders/";K.ShadersStore={};K.IncludesShadersStore={};K.ShadersRepositoryWGSL="src/ShadersWGSL/";K.ShadersStoreWGSL={};K.IncludesShadersStoreWGSL={};const mf="attribute",vf="varying";class On{constructor(){this.children=[]}isValid(e){return!0}process(e,t){var s,n,r,o,l,h,c;let i="";if(this.line){let u=this.line;const f=t.processor;if(f){f.lineProcessor&&(u=f.lineProcessor(u,t.isFragment,t.processingContext));const d=(n=(s=t.processor)==null?void 0:s.attributeKeywordName)!=null?n:mf,p=t.isFragment&&((r=t.processor)!=null&&r.varyingFragmentKeywordName)?(o=t.processor)==null?void 0:o.varyingFragmentKeywordName:!t.isFragment&&((l=t.processor)!=null&&l.varyingVertexKeywordName)?(h=t.processor)==null?void 0:h.varyingVertexKeywordName:vf;!t.isFragment&&f.attributeProcessor&&this.line.startsWith(d)?u=f.attributeProcessor(this.line,e,t.processingContext):f.varyingProcessor&&((c=f.varyingCheck)!=null&&c.call(f,this.line,t.isFragment)||!f.varyingCheck&&this.line.startsWith(p))?u=f.varyingProcessor(this.line,t.isFragment,e,t.processingContext):f.uniformProcessor&&f.uniformRegexp&&f.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=f.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):f.uniformBufferProcessor&&f.uniformBufferRegexp&&f.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=f.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):f.textureProcessor&&f.textureRegexp&&f.textureRegexp.test(this.line)?u=f.textureProcessor(this.line,t.isFragment,e,t.processingContext):(f.uniformProcessor||f.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?f.uniformProcessor&&(u=f.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):f.uniformBufferProcessor&&(u=f.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&this.line.indexOf("}")!==-1&&(t.lookForClosingBracketForUniformBuffer=!1,f.endOfUniformBufferProcessor&&(u=f.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}i+=u+"\n"}return this.children.forEach(u=>{i+=u.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class xf{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(i);else{const n=t.split(";");for(let r=0;r{c=c.trim(),c!==""&&(i.push(c),c="")},r=u=>{sht._Stack[s],l=()=>s===-1?"!!INVALID EXPRESSION!!":ht._Stack[s--];let h=0,c="";for(;h1){for(n();s!==-1&&ht._OperatorPriority[o()]>=ht._OperatorPriority[f];)i.push(l());r(f),h++}else c+=u;h++}for(n();s!==-1;)o()==="("?l():i.push(l());return ht._InfixToPostfixCache.size>=ht.InfixToPostfixCacheLimitSize&&ht.ClearCache(),ht._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(ht._InfixToPostfixCache.entries()).sort((t,i)=>t[1].accessTime-i[1].accessTime);for(let t=0;t":i=s>n;break;case"<":i=s=":i=s>=n;break;case"==":i=s===n;break;case"!=":i=s!==n;break}return i}}const Ef=/defined\s*?\((.+?)\)/g,Zr=/defined\s*?\[(.+?)\]/g,If=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,Af=/__decl__/,e0=/light\{X\}.(\w*)/g,t0=/\{X\}/g,Yn=[],Cf=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function ah(a){a.processor&&a.processor.initializeShaders&&a.processor.initializeShaders(a.processingContext)}function i0(a,e,t,i){var s;(s=e.processor)!=null&&s.preProcessShaderCode&&(a=e.processor.preProcessShaderCode(a,e.isFragment)),En(a,e,n=>{e.processCodeAfterIncludes&&(n=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",n,e.defines));const r=wf(n,e,i);t(r,n)})}function Mf(a,e,t,i){var s;(s=e.processor)!=null&&s.preProcessShaderCode&&(a=e.processor.preProcessShaderCode(a,e.isFragment)),En(a,e,n=>{e.processCodeAfterIncludes&&(n=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",n,e.defines));const r=Df(n,e,i);t(r,n)})}function oh(a,e,t){return!t.processor||!t.processor.finalizeShaders?{vertexCode:a,fragmentCode:e}:t.processor.finalizeShaders(a,e,t.processingContext)}function Rf(a,e){var i;if((i=e.processor)!=null&&i.noPrecision)return a;const t=e.shouldUseHighPrecisionShader;return a.indexOf("precision highp float")===-1?t?a="precision highp float;\n"+a:a="precision mediump float;\n"+a:t||(a=a.replace("precision highp float","precision mediump float")),a}function Qr(a){const t=/defined\((.+)\)/.exec(a);if(t&&t.length)return new lr(t[1].trim(),a[0]==="!");const i=["==","!=",">=","<=","<",">"];let s="",n=0;for(s of i)if(n=a.indexOf(s),n>-1)break;if(n===-1)return new lr(a);const r=a.substring(0,n).trim(),o=a.substring(n+s.length).trim();return new Sf(r,s,o)}function Pf(a){a=a.replace(Ef,"defined[$1]");const e=ht.infixToPostfix(a),t=[];for(const s of e)if(s!=="||"&&s!=="&&")t.push(s);else if(t.length>=2){let n=t[t.length-1],r=t[t.length-2];t.length-=2;const o=s=="&&"?new Tf:new yf;typeof n=="string"&&(n=n.replace(Zr,"defined($1)")),typeof r=="string"&&(r=r.replace(Zr,"defined($1)")),o.leftOperand=typeof r=="string"?Qr(r):r,o.rightOperand=typeof n=="string"?Qr(n):n,t.push(o)}let i=t[t.length-1];return typeof i=="string"&&(i=i.replace(Zr,"defined($1)")),typeof i=="string"?Qr(i):i}function tr(a,e){const t=new bf,i=a.substring(0,e);let s=a.substring(e);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),i==="#ifdef"?t.testExpression=new lr(s):i==="#ifndef"?t.testExpression=new lr(s,!0):t.testExpression=Pf(s),t}function Jr(a,e,t){let i=a.currentLine;for(;pa(a,t);){i=a.currentLine;const s=i.substring(0,5).toLowerCase();if(s==="#else"){const n=new On;e.children.push(n),pa(a,n);return}else if(s==="#elif"){const n=tr(i,5);e.children.push(n),t=n}}}function pa(a,e){for(;a.canRead;){a.lineIndex++;const t=a.currentLine;if(t.indexOf("#")>=0){const s=Cf.exec(t);if(s&&s.length){switch(s[0]){case"#ifdef":{const r=new jr;e.children.push(r);const o=tr(t,6);r.children.push(o),Jr(a,r,o);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const r=new jr;e.children.push(r);const o=tr(t,7);r.children.push(o),Jr(a,r,o);break}case"#if":{const r=new jr,o=tr(t,3);e.children.push(r),r.children.push(o),Jr(a,r,o);break}}continue}}const i=new On;if(i.line=t,e.children.push(i),t[0]==="#"&&t[1]==="d"){const s=t.replace(";","").split(" ");i.additionalDefineKey=s[1],s.length===3&&(i.additionalDefineValue=s[2])}}return!1}function lh(a,e,t){const i=new On,s=new xf;return s.lineIndex=-1,s.lines=a.split("\n"),pa(s,i),i.process(e,t)}function hh(a,e){var s;const t=a.defines,i={};for(const n of t){const o=n.replace("#define","").replace(";","").trim().split(" ");i[o[0]]=o.length>1?o[1]:""}return((s=a.processor)==null?void 0:s.shaderLanguage)===0&&(i.GL_ES="true"),i.__VERSION__=a.version,i[a.platformName]="true",th(i,e==null?void 0:e.isNDCHalfZRange,e==null?void 0:e.useReverseDepthBuffer,e==null?void 0:e.useExactSrgbConversions),i}function wf(a,e,t){let i=Rf(a,e);if(!e.processor||e.processor.shaderLanguage===0&&i.indexOf("#version 3")!==-1&&(i=i.replace("#version 300 es",""),!e.processor.parseGLES3))return i;const s=e.defines,n=hh(e,t);return e.processor.preProcessor&&(i=e.processor.preProcessor(i,s,n,e.isFragment,e.processingContext)),i=lh(i,n,e),e.processor.postProcessor&&(i=e.processor.postProcessor(i,s,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{})),t!=null&&t._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function Df(a,e,t){var r,o;let i=a;const s=e.defines,n=hh(e,t);return(r=e.processor)!=null&&r.preProcessor&&(i=e.processor.preProcessor(i,s,n,e.isFragment,e.processingContext)),i=lh(i,n,e),(o=e.processor)!=null&&o.postProcessor&&(i=e.processor.postProcessor(i,s,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{})),t._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function En(a,e,t){Yn.length=0;let i;for(;(i=If.exec(a))!==null;)Yn.push(i);let s=String(a),n=[a],r=!1;for(const o of Yn){let l=o[1];if(l.indexOf("__decl__")!==-1&&(l=l.replace(Af,""),e.supportsUniformBuffers&&(l=l.replace("Vertex","Ubo").replace("Fragment","Ubo")),l=l+"Declaration"),e.includesShadersStore[l]){let h=e.includesShadersStore[l];if(o[2]){const u=o[3].split(",");for(let f=0;fx+"{X}")),h+=g.replace(t0,_.toString())+"\n"}else e.supportsUniformBuffers||(h=h.replace(e0,(f,d)=>d+"{X}")),h=h.replace(t0,u)}const c=[];for(const u of n){const f=u.split(o[0]);for(let d=0;d=0||h.indexOf("#include <")>=0}else{const h=e.shadersRepository+"ShadersInclude/"+l+".fx";ch.loadFile(h,c=>{e.includesShadersStore[l]=c,En(n.join(""),e,t)});return}}Yn.length=0,s=n.join(""),r?En(s.toString(),e,t):t(s)}const ch={loadFile:(a,e,t,i,s,n)=>{throw Te("FileTools")}};function Ff(a,e){return li(e).cachedPipelines[a]}function Ha(a){const e=a._name,t=a.context;if(e&&t){const i=li(t),s=i.cachedPipelines[e];s==null||s.dispose(),delete i.cachedPipelines[e]}}function Of(a,e,t,i,s,n,r){let o,l;const h=St()?n==null?void 0:n.getHostDocument():null;typeof e=="string"?o=e:e.vertexSource?o="source:"+e.vertexSource:e.vertexElement?o=(h==null?void 0:h.getElementById(e.vertexElement))||e.vertexElement:o=e.vertex||e,typeof e=="string"?l=e:e.fragmentSource?l="source:"+e.fragmentSource:e.fragmentElement?l=(h==null?void 0:h.getElementById(e.fragmentElement))||e.fragmentElement:l=e.fragment||e;const c=[void 0,void 0],u=()=>{if(c[0]&&c[1]){a.isFragment=!0;const[f,d]=c;i0(d,a,(p,g)=>{r&&(r._fragmentSourceCodeBeforeMigration=g),t&&(p=t("fragment",p));const _=oh(f,p,a);a=null;const m=Lf(_.vertexCode,_.fragmentCode,e,s);i==null||i(m.vertexSourceCode,m.fragmentSourceCode)},n)}};s0(o,"Vertex","",f=>{ah(a),i0(f,a,(d,p)=>{r&&(r._rawVertexSourceCode=f,r._vertexSourceCodeBeforeMigration=p),t&&(d=t("vertex",d)),c[0]=d,u()},n)},s),s0(l,"Fragment","Pixel",f=>{r&&(r._rawFragmentSourceCode=f),c[1]=f,u()},s)}function s0(a,e,t,i,s,n){if(typeof HTMLElement<"u"&&a instanceof HTMLElement){const l=Ga(a);i(l);return}if(a.substr(0,7)==="source:"){i(a.substr(7));return}if(a.substr(0,7)==="base64:"){const l=window.atob(a.substr(7));i(l);return}const r=K.GetShadersStore(s);if(r[a+e+"Shader"]){i(r[a+e+"Shader"]);return}if(t&&r[a+t+"Shader"]){i(r[a+t+"Shader"]);return}let o;if(a[0]==="."||a[0]==="/"||a.indexOf("http")>-1?o=a:o=K.GetShadersRepository(s)+a,n=n||eh,!n)throw new Error("loadFileInjection is not defined");n(o+"."+e.toLowerCase()+".fx",i)}function Lf(a,e,t,i){if(t){const s=t.vertexElement||t.vertex||t.spectorName||t,n=t.fragmentElement||t.fragment||t.spectorName||t;return{vertexSourceCode:(i===1?"//":"")+"#define SHADER_NAME vertex:"+s+"\n"+a,fragmentSourceCode:(i===1?"//":"")+"#define SHADER_NAME fragment:"+n+"\n"+e}}else return{vertexSourceCode:a,fragmentSourceCode:e}}const Bf=(a,e,t,i)=>{try{const s=a.existingPipelineContext||e(a.shaderProcessingContext);if(s._name=a.name,a.name&&a.context){const n=li(a.context);n.cachedPipelines[a.name]=s}return t(s,a.vertex,a.fragment,!!a.createAsRaw,"","",a.rebuildRebind,a.defines,a.transformFeedbackVaryings,""),i(s,()=>{var n;(n=a.onRenderingStateCompiled)==null||n.call(a,s)}),s}catch(s){throw U.Error("Error compiling effect"),s}};class Pt{static get ShadersRepository(){return K.ShadersRepository}static set ShadersRepository(e){K.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new Q),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,s=null,n,r=null,o=null,l=null,h=null,c,u="",f=0){var g,_,m,x;this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new Q,this.onErrorObservable=new Q,this._onBindObservable=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=u;const d=this._key.replace(/\r/g,"").replace(/\n/g,"|");let p;if(t.attributes){const I=t;if(this._engine=i,this._attributesNames=I.attributes,this._uniformsNames=I.uniformsNames.concat(I.samplers),this._samplerList=I.samplers.slice(),this.defines=I.defines,this.onError=I.onError,this.onCompiled=I.onCompiled,this._fallbacks=I.fallbacks,this._indexParameters=I.indexParameters,this._transformFeedbackVaryings=I.transformFeedbackVaryings||null,this._multiTarget=!!I.multiTarget,this._shaderLanguage=(g=I.shaderLanguage)!=null?g:0,I.uniformBuffersNames){this._uniformBuffersNamesList=I.uniformBuffersNames.slice();for(let T=0;T{this._vertexSourceCode=n,this._fragmentSourceCode=r,this._prepareEffect(t)},this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return this._isReady?!0:this._pipelineContext?this._pipelineContext.isReady:!1}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){if(this.isReady()){e(this);return}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){this._processCompilationErrors(t,e);return}this._isDisposed||setTimeout(()=>{this._checkIsReady(e)},16)}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:(t=(e=this._pipelineContext)==null?void 0:e._getVertexShaderCode())!=null?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:(t=(e=this._pipelineContext)==null?void 0:e._getFragmentShaderCode())!=null?t:this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}getPipelineGenerationOptions(){return{platformName:this._engine.shaderPlatformName,shaderLanguage:this._shaderLanguage,shaderNameOrContent:this.name,key:this._key,defines:this.defines.split("\n"),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!!(this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride)}}}_rebuildProgram(e,t,i,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(n,r)=>{s&&s(r)},this.onCompiled=()=>{var r,o;const n=this.getEngine().scenes;if(n)for(let l=0;lthis._rebuildProgram(l,h,c,u),defines:s,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,parallelShaderCompile:o._caps.parallelShaderCompile,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:l=>{t&&!e&&this._engine._deletePipelineContext(t),l&&this._onRenderingStateCompiled(l)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContext.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(i){this._processCompilationErrors(i,t)}}_getShaderCodeAndErrorLine(e,t,i){const s=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let n=null;if(t&&e){const r=t.match(s);if(r&&r.length===2){const o=parseInt(r[1]),l=e.split("\n",-1);l.length>=o&&(n="Offending line [".concat(o,"] in ").concat(i?"fragment":"vertex"," code: ").concat(l[o-1]))}}return[e,n]}_processCompilationErrors(e,t=null){var r,o,l;this._compilationError=e.message;const i=this._attributesNames,s=this._fallbacks;if(U.Error("Unable to compile effect:"),U.Error("Uniforms: "+this._uniformsNames.map(function(h){return" "+h})),U.Error("Attributes: "+i.map(function(h){return" "+h})),U.Error("Defines:\n"+this.defines),Pt.LogShaderCodeOnCompilationError){let h=null,c=null,u=null;(r=this._pipelineContext)!=null&&r._getVertexShaderCode()&&([u,h]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),u&&(U.Error("Vertex code:"),U.Error(u))),(o=this._pipelineContext)!=null&&o._getFragmentShaderCode()&&([u,c]=this._getShaderCodeAndErrorLine((l=this._pipelineContext)==null?void 0:l._getFragmentShaderCode(),this._compilationError,!0),u&&(U.Error("Fragment code:"),U.Error(u))),h&&U.Error(h),c&&U.Error(c)}U.Error("Error: "+this._compilationError);const n=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,n()),s?(this._pipelineContext=null,s.hasMoreFallbacks?(this._allFallbacksProcessed=!1,U.Error("Trying next fallback."),this.defines=s.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,n(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||n())}get isSupported(){return this._compilationError===""}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(this._samplerList.indexOf(i+"0")===-1){const s=this._samplerList.indexOf(e);for(let r=1;r{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,n=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=n,this._flagContextRestored()},0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return 0}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}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 activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e){this._activeRenderLoops.length=0,this._cancelFrame();return}const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),this._activeRenderLoops.length==0&&this._cancelFrame())}_cancelFrame(){if(this._frameHandler!==0){const e=this._frameHandler;if(this._frameHandler=0,St()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if(typeof t=="function")return t(e)}else if(typeof cancelAnimationFrame=="function")return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&this._frameHandler===0&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e-1?e.substring(b).toLowerCase():""),A=null;S.indexOf("?")>-1&&(S=S.split("?")[0]);for(const P of me._TextureLoaders)if(P.canLoad(S,p)){A=P;break}s&&s.addPendingData(T),T.url=e,T.generateMipMaps=!t,T.samplingMode=n,T.invertY=i,T._useSRGBBuffer=this._getUseSRGBBuffer(!!_,t),this._doNotHandleContextLost||(T._buffer=c);let C=null;r&&!u&&(C=T.onLoadedObservable.add(r)),u||this._internalTexturesCache.push(T);const w=(P,z)=>{s&&s.removePendingData(T),e===y?(C&&T.onLoadedObservable.remove(C),Ce.UseFallbackTexture&&e!==Ce.FallbackTexture&&this._createTextureBase(Ce.FallbackTexture,t,T.invertY,s,n,null,o,l,h,c,T),P=(P||"Unknown error")+(Ce.UseFallbackTexture?" - Fallback texture was used":""),T.onErrorObservable.notifyObservers({message:P,exception:z}),o&&o(P,z)):(U.Warn("Failed to load ".concat(e,", falling back to ").concat(y)),this._createTextureBase(y,t,T.invertY,s,n,r,o,l,h,c,T,f,d,p,g,_))};if(A){const P=z=>{A.loadData(z,T,(L,G,H,ce,J,W)=>{W?w("TextureLoader failed to load data"):l(T,S,s,{width:L,height:G},T.invertY,!H,ce,()=>(J(),!1),n)},g)};c?c instanceof ArrayBuffer?P(new Uint8Array(c)):ArrayBuffer.isView(c)?P(c):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,z=>P(new Uint8Array(z)),void 0,s?s.offlineProvider:void 0,!0,(z,L)=>{w("Unable to load "+(z&&z.responseURL,L))})}else{const P=z=>{x&&!this._doNotHandleContextLost&&(T._buffer=z),l(T,S,s,z,T.invertY,t,!1,h,n)};!m||I?c&&(typeof c.decoding=="string"||c.close)?P(c):me._FileToolsLoadImage(e||"",P,w,s?s.offlineProvider:null,p,T.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):typeof c=="string"||c instanceof ArrayBuffer||ArrayBuffer.isView(c)||c instanceof Blob?me._FileToolsLoadImage(c,P,w,s?s.offlineProvider:null,p,T.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):c&&P(c)}return T}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuildAfterContextLost()}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:xn()?document:null}getLoadedTexturesCache(){return this._internalTexturesCache}clearInternalTexturesCache(){this._internalTexturesCache.length=0}getCaps(){return this._caps}resetTextureCache(){for(const e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}get name(){return this._name}set name(e){this._name=e}static get NpmPackage(){return"babylonjs@7.13.1"}static get Version(){return"7.13.1"}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get isStencilEnable(){return this._isStencilEnable}getCreationOptions(){return this._creationOptions}constructor(e,t,i){var r,o,l,h,c,u,f,d,p,g,_;this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new uh,this._stencilStateComposer=new fh,this._stencilState=new ts,this._alphaState=new Nf,this._alphaMode=1,this._alphaEquation=0,this._activeRequests=[],this._badOS=!1,this._badDesktopOS=!1,this._compatibilityMode=!0,this._internalTexturesCache=new Array,this._currentRenderTarget=null,this._boundTexturesCache={},this._activeChannel=0,this._currentTextureChannel=-1,this._viewportCached={x:0,y:0,z:0,w:0},this._isWebGPU=!1,this.onCanvasBlurObservable=new Q,this.onCanvasFocusObservable=new Q,this.onNewSceneAddedObservable=new Q,this.onResizeObservable=new Q,this.onCanvasPointerOutObservable=new Q,this.disablePerformanceMonitorInBackground=!1,this.disableVertexArrayObjects=!1,this._frameId=0,this.hostInformation={isMobile:!1},this.isFullscreen=!1,this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.currentRenderPassId=0,this.isPointerLock=!1,this.postProcesses=[],this.canvasTabIndex=1,this._contextWasLost=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this._renderTargetWrapperCache=new Array,this._compiledEffects={},this._isDisposed=!1,this.scenes=[],this._virtualScenes=new Array,this.onBeforeTextureInitObservable=new Q,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new Q,this.onAfterShaderCompilationObservable=new Q,this.onBeginFrameObservable=new Q,this.onEndFrameObservable=new Q,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new Q,this.onContextRestoredObservable=new Q,this._name="",this.premultipliedAlpha=!0,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._doNotHandleContextLost=!1,this.cullBackFaces=null,this._renderPassNames=["main"],this._fps=60,this._deltaTime=0,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this.onDisposeObservable=new Q,Ce.Instances.push(this),this.startTime=xi.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,Rt.SetMatrixPrecision(!!t.useHighPrecisionMatrix),Xs()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),this.adaptToDeviceRatio=i!=null?i:!1,t.antialias=e!=null?e:t.antialias,t.deterministicLockstep=(r=t.deterministicLockstep)!=null?r:!1,t.lockstepMaxSteps=(o=t.lockstepMaxSteps)!=null?o:4,t.timeStep=(l=t.timeStep)!=null?l:1/60,t.audioEngine=(h=t.audioEngine)!=null?h:!0,t.stencil=(c=t.stencil)!=null?c:!0,this._audioContext=(f=(u=t.audioEngineOptions)==null?void 0:u.audioContext)!=null?f:null,this._audioDestination=(p=(d=t.audioEngineOptions)==null?void 0:d.audioDestination)!=null?p:null,this.premultipliedAlpha=(g=t.premultipliedAlpha)!=null?g:!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=(_=t.useExactSrgbConversions)!=null?_:!1;const s=St()&&window.devicePixelRatio||1,n=t.limitDeviceRatio||s;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(n,s):1,this._lastDevicePixelRatio=s,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const s=St()&&window.devicePixelRatio||1,n=this._lastDevicePixelRatio/s;this._lastDevicePixelRatio=s,this._hardwareScalingLevel*=n}if(St()&&xn())if(this._renderingCanvas){const s=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||s.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||s.height||this._renderingCanvas.height||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){if(!this._renderingCanvas||(e=e|0,t=t|0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t))return!1;if(this._renderingCanvas.width=e,this._renderingCanvas.height=t,this.scenes){for(let s=0;s{const e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&xn()&&"ontouchend"in document},this._checkForMobile(),St()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){var t;(t=this._drawCalls)==null||t.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return this._timeStep*1e3}_createImageBitmapFromSource(e,t){throw new Error("createImageBitmapFromSource is not implemented")}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){throw new Error("resizeImageBitmap is not implemented")}getFontOffset(e){throw new Error("getFontOffset is not implemented")}static _CreateCanvas(e,t){if(typeof document>"u")return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return me._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,s,n,r){throw Te("FileTools")}_loadFile(e,t,i,s,n,r){const o=eh(e,t,i,s,n,r);return this._activeRequests.push(o),o.onCompleteObservable.add(()=>{const l=this._activeRequests.indexOf(o);l!==-1&&this._activeRequests.splice(l,1)}),o}static _FileToolsLoadFile(e,t,i,s,n,r){if(or.loadFile)return or.loadFile(e,t,i,s,n,r);throw Te("FileTools")}dispose(){var t;for(this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();(t=this.releaseComputeEffects)==null||t.call(this),Pt.ResetCache();for(const i of this._activeRequests)i.abort();this._boundRenderFunction=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onNewSceneAddedObservable.clear(),St()&&window.removeEventListener("resize",this._checkForMobile);const e=Ce.Instances.indexOf(this);e>=0&&Ce.Instances.splice(e,1),Ce.Instances.length||(Ce.OnEnginesDisposedObservable.notifyObservers(this),Ce.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw Te("LoadingScreen")}}me._TextureLoaders=[];me._RenderPassIdCounter=0;me._RescalePostProcessFactory=null;class ph{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&(e=t.createTexture(),!e))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t,i;return(i=(t=this._MSAARenderBuffers)==null?void 0:t[e])!=null?i:null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}class Uf{}class Fe extends me{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return Pt.ShadersRepository}static set ShadersRepository(e){Pt.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,i,s){if(i=i||{},super(t!=null?t:i.antialias,i,s),this._name="WebGL",this.forcePOTTextures=!1,this.validateShaderPrograms=!1,this.disableUniformBuffers=!1,this._webGLVersion=1,this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},!e)return;let n=null;if(e.getContext){if(n=e,this._renderingCanvas=n,i.preserveDrawingBuffer===void 0&&(i.preserveDrawingBuffer=!1),i.xrCompatible===void 0&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const l=navigator.userAgent;for(const h of Fe.ExceptionList){const c=h.key,u=h.targets;if(new RegExp(c).test(l)){if(h.capture&&h.captureConstraint){const d=h.capture,p=h.captureConstraint,_=new RegExp(d).exec(l);if(_&&_.length>0&&parseInt(_[_.length-1])>=p)continue}for(const d of u)switch(d){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1;break}}}}if(this._doNotHandleContextLost||(this._onContextLost=l=>{l.preventDefault(),this._contextWasLost=!0,U.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},n.addEventListener("webglcontextlost",this._onContextLost,!1),n.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=n.getContext("webgl2",i)||n.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch{}if(!this._gl){if(!n)throw new Error("The provided canvas is null or undefined.");try{this._gl=n.getContext("webgl",i)||n.getContext("experimental-webgl",i)}catch{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 l=this._gl.getContextAttributes();l&&(i.stencil=l.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),i.useHighPrecisionFloats!==void 0&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let l=0;l1?new _f:new df;const r="Babylon.js v".concat(Fe.Version);U.Log(r+" - ".concat(this.description)),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",r);const o=li(this._gl);o.validateShaderPrograms=this.validateShaderPrograms,o.parallelShaderCompile=this._caps.parallelShaderCompile}_clearEmptyResources(){this._dummyFramebuffer=null,super._clearEmptyResources()}_getShaderProcessingContext(e){return null}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_initGLContext(){var t;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||this._gl.getExtension("OES_standard_derivatives")!==null,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||this._gl.getExtension("OES_element_index_uint")!==null,fragmentDepthSupported:this._webGLVersion>1||this._gl.getExtension("EXT_frag_depth")!==null,highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:this._webGLVersion!==1,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(e!=null&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),this._gl.HALF_FLOAT_OES!==36193&&(this._gl.HALF_FLOAT_OES=36193),this._gl.RGBA16F!==34842&&(this._gl.RGBA16F=34842),this._gl.RGBA32F!==34836&&(this._gl.RGBA32F=34836),this._gl.DEPTH24_STENCIL8!==35056&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(this._webGLVersion===1&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=((t=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))!=null?t: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&&this._gl.HALF_FLOAT_OES!==5131&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=this._maxMSAASamplesOverride!==null?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const i=this._gl.getExtension("WEBGL_draw_buffers");if(i!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=i.drawBuffersWEBGL.bind(i),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let s=0;s<16;s++)this._gl["COLOR_ATTACHMENT"+s+"_WEBGL"]=i["COLOR_ATTACHMENT"+s+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const i=this._gl.getExtension("WEBGL_depth_texture");i!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=i.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const i=this._gl.getExtension("OES_vertex_array_object");i!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=i.createVertexArrayOES.bind(i),this._gl.bindVertexArray=i.bindVertexArrayOES.bind(i),this._gl.deleteVertexArray=i.deleteVertexArrayOES.bind(i))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const i=this._gl.getExtension("ANGLE_instanced_arrays");i!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=i.drawArraysInstancedANGLE.bind(i),this._gl.drawElementsInstanced=i.drawElementsInstancedANGLE.bind(i),this._gl.vertexAttribDivisor=i.vertexAttribDivisorANGLE.bind(i)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const i=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),s=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);i&&s&&(this._caps.highPrecisionShaderSupported=i.precision!==0&&s.precision!==0)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const i=this._gl.getExtension("EXT_blend_minmax");i!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=i.MAX_EXT,this._gl.MIN=i.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const i=this._gl.getExtension("EXT_sRGB");i!=null&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:i.SRGB_EXT,SRGB8:i.SRGB_ALPHA_EXT,SRGB8_ALPHA8:i.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 i=0;i"u",supportRenderAndCopyToLodForFloatTextures:this._webGLVersion!==1,supportDepthStencilTexture:this._webGLVersion!==1,supportShadowSamplers:this._webGLVersion!==1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:this._webGLVersion!==1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:this._webGLVersion!==1,basisNeedsPOT:this._webGLVersion===1,support3DTextures:this._webGLVersion!==1,needTypeSuffixInShaderConstants:this._webGLVersion!==1,supportMSAA:this._webGLVersion!==1,supportSSAO2:this._webGLVersion!==1,supportExtendedTextureFormats:this._webGLVersion!==1,supportSwitchCaseInShader:this._webGLVersion!==1,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1}}get webGLVersion(){return this._webGLVersion}getClassName(){return"ThinEngine"}_prepareWorkingCanvas(){if(this._workingCanvas)return;this._workingCanvas=this.createCanvas(1,1);const e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}getInfo(){return this.getGlInfo()}getGlInfo(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}}extractDriverInfo(){const e=this.getGlInfo();return e&&e.renderer?e.renderer:""}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight}clear(e,t,i,s=!1){var o,l;const n=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=n;let r=0;if(t&&e){let h=!0;if(this._currentRenderTarget){const c=(o=this._currentRenderTarget.texture)==null?void 0:o.format;if(c===8||c===9||c===10||c===11){const u=(l=this._currentRenderTarget.texture)==null?void 0:l.type;u===7||u===5?(Fe._TempClearColorUint32[0]=e.r*255,Fe._TempClearColorUint32[1]=e.g*255,Fe._TempClearColorUint32[2]=e.b*255,Fe._TempClearColorUint32[3]=e.a*255,this._gl.clearBufferuiv(this._gl.COLOR,0,Fe._TempClearColorUint32),h=!1):(Fe._TempClearColorInt32[0]=e.r*255,Fe._TempClearColorInt32[1]=e.g*255,Fe._TempClearColorInt32[2]=e.b*255,Fe._TempClearColorInt32[3]=e.a*255,this._gl.clearBufferiv(this._gl.COLOR,0,Fe._TempClearColorInt32),h=!1)}}h&&(this._gl.clearColor(e.r,e.g,e.b,e.a!==void 0?e.a:1),r|=this._gl.COLOR_BUFFER_BIT)}i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),r|=this._gl.DEPTH_BUFFER_BIT),s&&(this._gl.clearStencil(0),r|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(r)}_viewport(e,t,i,s){(e!==this._viewportCached.x||t!==this._viewportCached.y||i!==this._viewportCached.z||s!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=s,this._gl.viewport(e,t,i,s))}endFrame(){super.endFrame(),this._badOS&&this.flushFramebuffer()}get performanceMonitor(){throw new Error("Not Supported by ThinEngine")}bindFramebuffer(e,t=0,i,s,n,r=0,o=0){var u,f,d,p,g,_;const l=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(l._MSAAFramebuffer?l._MSAAFramebuffer:l._framebuffer);const h=this._gl;e.isMulti||(e.is2DArray||e.is3D?h.framebufferTextureLayer(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,(u=e.texture._hardwareTexture)==null?void 0:u.underlyingResource,r,o):e.isCube?h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_CUBE_MAP_POSITIVE_X+t,(f=e.texture._hardwareTexture)==null?void 0:f.underlyingResource,r):l._currentLOD!==r&&(h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_2D,(d=e.texture._hardwareTexture)==null?void 0:d.underlyingResource,r),l._currentLOD=r));const c=e._depthStencilTexture;if(c){e.is3D&&(e.texture.width!==c.width||e.texture.height!==c.height||e.texture.depth!==c.depth)&&U.Warn("Depth/Stencil attachment for 3D target must have same dimensions as color attachment");const m=e._depthStencilTextureWithStencil?h.DEPTH_STENCIL_ATTACHMENT:h.DEPTH_ATTACHMENT;e.is2DArray||e.is3D?h.framebufferTextureLayer(h.FRAMEBUFFER,m,(p=c._hardwareTexture)==null?void 0:p.underlyingResource,r,o):e.isCube?h.framebufferTexture2D(h.FRAMEBUFFER,m,h.TEXTURE_CUBE_MAP_POSITIVE_X+t,(g=c._hardwareTexture)==null?void 0:g.underlyingResource,r):h.framebufferTexture2D(h.FRAMEBUFFER,m,h.TEXTURE_2D,(_=c._hardwareTexture)==null?void 0:_.underlyingResource,r)}this._cachedViewport&&!n?this.setViewport(this._cachedViewport,i,s):(i||(i=e.width,r&&(i=i/Math.pow(2,r))),s||(s=e.height,r&&(s=s/Math.pow(2,r))),this._viewport(0,0,i,s)),this.wipeCaches()}setState(e,t=0,i,s=!1,n,r,o=0){var c,u;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const l=(u=(c=this.cullBackFaces)!=null?c:n)==null||u?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==l||i)&&(this._depthCullingState.cullFace=l),this.setZOffset(t),this.setZOffsetUnits(o);const h=s?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==h||i)&&(this._depthCullingState.frontFace=h),this._stencilStateComposer.stencilMaterial=r}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return this._currentFramebuffer===null}generateMipmaps(e){const t=this._getTextureTarget(e);this._bindTextureDirectly(t,e,!0),this._gl.generateMipmap(t),this._bindTextureDirectly(t,null)}unBindFramebuffer(e,t=!1,i){var r;const s=e;this._currentRenderTarget=null;const n=this._gl;if(s._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,i);return}n.bindFramebuffer(n.READ_FRAMEBUFFER,s._MSAAFramebuffer),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,s._framebuffer),n.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,n.COLOR_BUFFER_BIT,n.NEAREST)}(r=e.texture)!=null&&r.generateMipMaps&&!t&&!e.isCube&&this.generateMipmaps(e.texture),i&&(s._MSAAFramebuffer&&this._bindUnboundFramebuffer(s._framebuffer),i()),this._bindUnboundFramebuffer(null)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e,t,i){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create vertex buffer");const s=new Sn(i);return this.bindArrayBuffer(s),typeof e!="number"?e instanceof Array?(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t),s.capacity=e.length*4):(this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),s.capacity=e.byteLength):(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Uint8Array(e),t),s.capacity=e),this._resetVertexBufferBinding(),s.references=1,s}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,i){const s=this._gl.createBuffer(),n=new Sn(s);if(!s)throw new Error("Unable to create index buffer");this.bindIndexBuffer(n);const r=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),n.references=1,n.is32Bits=r.BYTES_PER_ELEMENT===4,n}_normalizeIndexData(e){if(e.BYTES_PER_ELEMENT===2)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let i=0;i=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const s=e.program,n=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,n,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,s,n,r,o){const l=this._currentBufferPointers[t];if(!l)return;let h=!1;l.active?(l.buffer!==e&&(l.buffer=e,h=!0),l.size!==i&&(l.size=i,h=!0),l.type!==s&&(l.type=s,h=!0),l.normalized!==n&&(l.normalized=n,h=!0),l.stride!==r&&(l.stride=r,h=!0),l.offset!==o&&(l.offset=o,h=!0)):(h=!0,l.active=!0,l.index=t,l.size=i,l.type=s,l.normalized=n,l.stride=r,l.offset=o,l.buffer=e),(h||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,r,o):this._gl.vertexAttribPointer(t,i,s,n,r,o))}_bindIndexBufferWithCache(e){e!=null&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const s=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let n=0;n=0){const o=s[n];let l=null;if(i&&(l=i[o]),l||(l=e[o]),!l)continue;this._gl.enableVertexAttribArray(r),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[r]=!0);const h=l.getBuffer();h&&(this._vertexAttribPointer(h,r,l.getSize(),l.type,l.normalized,l.byteStride,l.byteOffset),l.getIsInstanced()&&(this._gl.vertexAttribDivisor(r,l.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(r),this._currentInstanceBuffers.push(h))))}}}recordVertexArrayObject(e,t,i,s){const n=this._gl.createVertexArray();if(!n)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(n),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),n}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=t!=null&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,s,n){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==n){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=n;const r=n.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let o=0;for(let l=0;l=0&&(this._gl.enableVertexAttribArray(h),this._vertexAttribArraysEnabled[h]=!0,this._vertexAttribPointer(e,h,i[l],this._gl.FLOAT,!1,s,o)),o+=i[l]*4}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,s){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,s)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1||this.isWebGPU)),(r===1&&!this._caps.textureFloatLinearFiltering||r===2&&!this._caps.textureHalfFloatLinearFiltering)&&(o=1),r===1&&!this._caps.textureFloat&&(r=0,U.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const f=this._gl,d=new Et(this,s),p=e.width||e,g=e.height||e,_=e.depth||0,m=e.layers||0,x=this._getSamplingParameters(o,n),I=m!==0?f.TEXTURE_2D_ARRAY:_!==0?f.TEXTURE_3D:f.TEXTURE_2D,T=this._getRGBABufferInternalSizedFormat(r,l,h),y=this._getInternalFormat(l),b=this._getWebGLTextureType(r);return this._bindTextureDirectly(I,d),m!==0?(d.is2DArray=!0,f.texImage3D(I,0,T,p,g,m,0,y,b,null)):_!==0?(d.is3D=!0,f.texImage3D(I,0,T,p,g,_,0,y,b,null)):f.texImage2D(I,0,T,p,g,0,y,b,null),f.texParameteri(I,f.TEXTURE_MAG_FILTER,x.mag),f.texParameteri(I,f.TEXTURE_MIN_FILTER,x.min),f.texParameteri(I,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(I,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(I),this._bindTextureDirectly(I,null),d._useSRGBBuffer=h,d.baseWidth=p,d.baseHeight=g,d.width=p,d.height=g,d.depth=m,d.isReady=!0,d.samples=c,d.generateMipMaps=n,d.samplingMode=o,d.type=r,d.format=l,d.label=u,this._internalTexturesCache.push(d),d}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,s,n=3,r=null,o=null,l=null,h=null,c=null,u=null,f,d,p,g){return this._createTextureBase(e,t,i,s,n,r,o,(..._)=>this._prepareWebGLTexture(..._,c),(_,m,x,I,T,y)=>{const b=this._gl,S=x.width===_&&x.height===m;T._creationFlags=p!=null?p:0;const A=this._getTexImageParametersForCreateTexture(T.format,T._useSRGBBuffer);if(S)return b.texImage2D(b.TEXTURE_2D,0,A.internalFormat,A.format,A.type,x),!1;const M=this._caps.maxTextureSize;if(x.width>M||x.height>M||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=_,this._workingCanvas.height=m,this._workingContext.drawImage(x,0,0,x.width,x.height,0,0,_,m),b.texImage2D(b.TEXTURE_2D,0,A.internalFormat,A.format,A.type,this._workingCanvas),T.width=_,T.height=m),!1;{const C=new Et(this,2);this._bindTextureDirectly(b.TEXTURE_2D,C,!0),b.texImage2D(b.TEXTURE_2D,0,A.internalFormat,A.format,A.type,x),this._rescaleTexture(C,T,s,A.format,()=>{this._releaseTexture(C),this._bindTextureDirectly(b.TEXTURE_2D,T,!0),y()})}return!0},l,h,c,u,f,d,g)}_getTexImageParametersForCreateTexture(e,t){let i,s;return this.webGLVersion===1?(i=this._getInternalFormat(e,t),s=i):(i=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:s,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,s,n){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const s=this._getTextureTarget(t),n=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,n.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,n.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const n=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&s!==null&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(n,null)}_uploadCompressedDataToTextureDirectly(e,t,i,s,n,r=0,o=0){const l=this._gl;let h=l.TEXTURE_2D;if(e.isCube&&(h=l.TEXTURE_CUBE_MAP_POSITIVE_X+r),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=l.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1;break}this._gl.compressedTexImage2D(h,o,t,i,s,0,n)}_uploadDataToTextureDirectly(e,t,i=0,s=0,n,r=!1){const o=this._gl,l=this._getWebGLTextureType(e.type),h=this._getInternalFormat(e.format),c=n===void 0?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(n,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let u=o.TEXTURE_2D;e.isCube&&(u=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const f=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),p=r?e.width:Math.pow(2,Math.max(f-s,0)),g=r?e.height:Math.pow(2,Math.max(d-s,0));o.texImage2D(u,s,c,p,g,0,h,l,t)}updateTextureData(e,t,i,s,n,r,o=0,l=0,h=!1){const c=this._gl,u=this._getWebGLTextureType(e.type),f=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=c.TEXTURE_2D,p=c.TEXTURE_2D;e.isCube&&(p=c.TEXTURE_CUBE_MAP_POSITIVE_X+o,d=c.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),c.texSubImage2D(p,l,i,s,n,r,f,u,t),h&&this._gl.generateMipmap(p),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const n=this._gl,r=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(r,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(r,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,n){const r=this._gl;if(!r)return;const o=this._getSamplingParameters(n,!i);r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,o.mag),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,o.min),!i&&!s&&r.generateMipmap(r.TEXTURE_2D),this._bindTextureDirectly(r.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,n,r,o,l,h,c){const u=this.getCaps().maxTextureSize,f=Math.min(u,this.needPOTTextures?fi(s.width,u):s.width),d=Math.min(u,this.needPOTTextures?fi(s.height,u):s.height),p=this._gl;if(p){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(p.TEXTURE_2D,e,!0),this._unpackFlipY(n===void 0?!0:!!n),e.baseWidth=s.width,e.baseHeight=s.height,e.width=f,e.height=d,e.isReady=!0,e.type=e.type!==-1?e.type:0,e.format=e.format!==-1?e.format:c!=null?c:t===".jpg"&&!e._useSRGBBuffer?4:5,!l(f,d,s,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,r,o,h)})&&this._prepareWebGLTextureContinuation(e,i,r,o,h)}}_setupFramebufferDepthAttachments(e,t,i,s,n=1){const r=this._gl;if(e&&t)return this._createRenderBuffer(i,s,n,r.DEPTH_STENCIL,r.DEPTH24_STENCIL8,r.DEPTH_STENCIL_ATTACHMENT);if(t){let o=r.DEPTH_COMPONENT16;return this._webGLVersion>1&&(o=r.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,n,o,o,r.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,n,r.STENCIL_INDEX8,r.STENCIL_INDEX8,r.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,n,r,o=!0){const h=this._gl.createRenderbuffer();return this._updateRenderBuffer(h,e,t,i,s,n,r,o)}_updateRenderBuffer(e,t,i,s,n,r,o,l=!0){const h=this._gl;return h.bindRenderbuffer(h.RENDERBUFFER,e),s>1&&h.renderbufferStorageMultisample?h.renderbufferStorageMultisample(h.RENDERBUFFER,s,r,t,i):h.renderbufferStorage(h.RENDERBUFFER,n,t,i),h.framebufferRenderbuffer(h.FRAMEBUFFER,o,h.RENDERBUFFER,e),l&&h.bindRenderbuffer(h.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);t!==-1&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_deleteTexture(e){e==null||e.release()}_setProgram(e){this._currentProgram!==e&&(uf(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let s=0;s-1;if(i&&r&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw U.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,(h=(l=t==null?void 0:t._hardwareTexture)==null?void 0:l.underlyingResource)!=null?h:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(n=!0,this._activateCurrentTexture());return r&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),n}_bindTexture(e,t,i){if(e===void 0)return;t&&(t._associatedChannel=e),this._activeChannel=e;const s=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(s,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,s){e!==void 0&&(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,s=!1,n=""){if(!t)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const h=t.getInternalTexture();h&&(h._associatedChannel=e),t.update()}else if(t.delayLoadState===4)return t.delayLoad(),!1;let r;s?r=t.depthStencilTexture:t.isReady()?r=t.getInternalTexture():t.isCube?r=this.emptyCubeTexture:t.is3D?r=this.emptyTexture3D:t.is2DArray?r=this.emptyTexture2DArray:r=this.emptyTexture,!i&&r&&(r._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===r&&(i||this._bindSamplerUniformToChannel(r._associatedChannel,e),o=!1),this._activeChannel=e;const l=this._getTextureTarget(r);if(o&&this._bindTextureDirectly(l,r,i),r&&!r.isMultiview){if(r.isCube&&r._cachedCoordinatesMode!==t.coordinatesMode){r._cachedCoordinatesMode=t.coordinatesMode;const h=t.coordinatesMode!==3&&t.coordinatesMode!==5?1:0;t.wrapU=h,t.wrapV=h}r._cachedWrapU!==t.wrapU&&(r._cachedWrapU=t.wrapU,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),r)),r._cachedWrapV!==t.wrapV&&(r._cachedWrapV=t.wrapV,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),r)),r.is3D&&r._cachedWrapR!==t.wrapR&&(r._cachedWrapR=t.wrapR,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),r)),this._setAnisotropicLevel(l,r,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(!(e===void 0||!t)){(!this._textureUnits||this._textureUnits.length!==i.length)&&(this._textureUnits=new Int32Array(i.length));for(let n=0;n=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;St()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&((e=this._gl.getExtension("WEBGL_lose_context"))==null||e.loseContext()),lf(this._gl)}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(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 s=t.createTexture();t.bindTexture(t.TEXTURE_2D,s),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const n=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const r=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&r===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);const o=t.RGBA,l=t.UNSIGNED_BYTE,h=new Uint8Array(4);t.readPixels(0,0,1,1,o,l,h),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(n),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(this._webGLVersion===1){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._glSRGBExtensionValues.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._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;break}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;break}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(this._webGLVersion===1){if(t!==void 0)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._glSRGBExtensionValues.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._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.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;case 11:return this._gl.RGBA16I;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;case 11:return this._gl.RGBA16UI;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;case 11:return this._gl.RGBA32I;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;case 11:return this._gl.RGBA32UI;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;case 5:return this._gl.RGBA32F;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;case 5:return this._gl.RGBA16F;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:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,s,n=!0,r=!0){const o=n?4:3,l=n?this._gl.RGBA:this._gl.RGB,h=new Uint8Array(s*i*o);return r&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,l,this._gl.UNSIGNED_BYTE,h),Promise.resolve(h)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(this._HasMajorPerformanceCaveat!==null)return!this._HasMajorPerformanceCaveat;if(this._IsSupported===null)try{const e=me._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=t!=null&&!!window.WebGLRenderingContext}catch{this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(this._HasMajorPerformanceCaveat===null)try{const e=me._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch{this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}}Fe._TempClearColorUint32=new Uint32Array(4);Fe._TempClearColorInt32=new Int32Array(4);Fe.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}];Fe.CollisionsEpsilon=.001;Fe._ConcatenateShader=Jl;Fe._IsSupported=null;Fe._HasMajorPerformanceCaveat=null;Fe.CeilingPOT=Xa;Fe.FloorPOT=Cr;Fe.NearestPOT=Wa;Fe.GetExponentOfTwo=fi;Fe.QueueNewFrame=dh;class _h{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new kf(e)}sampleFrame(e=xi.Now){if(this._enabled){if(this._lastFrameTimeMs!=null){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 e===0?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 kf{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const i=this._samples[this._pos];t=i-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(i-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}}Fe.prototype.setAlphaMode=function(a,e=!1){if(this._alphaMode===a){if(!e){const t=a===0;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(a){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: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 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 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;break}e||(this.depthCullingState.depthMask=a===0),this._alphaMode=a};function _a(a,e,t=!1,i){switch(a){case 3:{const n=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e);return i&&n.set(new Int8Array(i)),n}case 0:{const n=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&n.set(new Uint8Array(i)),n}case 4:{const n=e instanceof ArrayBuffer?new Int16Array(e):new Int16Array(t?e/2:e);return i&&n.set(new Int16Array(i)),n}case 5:case 8:case 9:case 10:case 2:{const n=e instanceof ArrayBuffer?new Uint16Array(e):new Uint16Array(t?e/2:e);return i&&n.set(new Uint16Array(i)),n}case 6:{const n=e instanceof ArrayBuffer?new Int32Array(e):new Int32Array(t?e/4:e);return i&&n.set(new Int32Array(i)),n}case 7:case 11:case 12:case 13:case 14:case 15:{const n=e instanceof ArrayBuffer?new Uint32Array(e):new Uint32Array(t?e/4:e);return i&&n.set(new Uint32Array(i)),n}case 1:{const n=e instanceof ArrayBuffer?new Float32Array(e):new Float32Array(t?e/4:e);return i&&n.set(new Float32Array(i)),n}}const s=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&s.set(new Uint8Array(i)),s}Fe.prototype._readTexturePixelsSync=function(a,e,t,i=-1,s=0,n=null,r=!0,o=!1,l=0,h=0){var f,d;const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const p=c.createFramebuffer();if(!p)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=p}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),i>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+i,(f=a._hardwareTexture)==null?void 0:f.underlyingResource,s):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,(d=a._hardwareTexture)==null?void 0:d.underlyingResource,s);let u=a.type!==void 0?this._getWebGLTextureType(a.type):c.UNSIGNED_BYTE;if(o)n||(n=_a(a.type,4*e*t));else switch(u){case c.UNSIGNED_BYTE:n||(n=new Uint8Array(4*e*t)),u=c.UNSIGNED_BYTE;break;default:n||(n=new Float32Array(4*e*t)),u=c.FLOAT;break}return r&&this.flushFramebuffer(),c.readPixels(l,h,e,t,c.RGBA,u,n),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),n};Fe.prototype._readTexturePixels=function(a,e,t,i=-1,s=0,n=null,r=!0,o=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(a,e,t,i,s,n,r,o,l,h))};Fe.prototype.updateDynamicIndexBuffer=function(a,e,t=0){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(a);let i;a.is32Bits?i=e instanceof Uint32Array?e:new Uint32Array(e):i=e instanceof Uint16Array?e:new Uint16Array(e),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,i,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()};Fe.prototype.updateDynamicVertexBuffer=function(a,e,t,i){this.bindArrayBuffer(a),t===void 0&&(t=0);const s=e.byteLength||e.length;i===void 0||i>=s&&t===0?e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,new Float32Array(e)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,e):e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(e).subarray(t,t+i)):(e instanceof ArrayBuffer?e=new Uint8Array(e,t,i):e=new Uint8Array(e.buffer,e.byteOffset+t,i),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)),this._resetVertexBufferBinding()};me.prototype.displayLoadingUI=function(){if(!St())return;const a=this.loadingScreen;a&&a.displayLoadingUI()};me.prototype.hideLoadingUI=function(){if(!St())return;const a=this._loadingScreen;a&&a.hideLoadingUI()};Object.defineProperty(me.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=me.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(a){this._loadingScreen=a},enumerable:!0,configurable:!0});Object.defineProperty(me.prototype,"loadingUIText",{set:function(a){this.loadingScreen.loadingUIText=a},enumerable:!0,configurable:!0});Object.defineProperty(me.prototype,"loadingUIBackgroundColor",{set:function(a){this.loadingScreen.loadingUIBackgroundColor=a},enumerable:!0,configurable:!0});me.prototype.getInputElement=function(){return this._renderingCanvas};me.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null};me.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null};me.prototype.getAspectRatio=function(a,e=!1){const t=a.viewport;return this.getRenderWidth(e)*t.width/(this.getRenderHeight(e)*t.height)};me.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)};me.prototype._verifyPointerLock=function(){var a;(a=this._onPointerLockChange)==null||a.call(this)};me.prototype.setAlphaEquation=function(a){if(this._alphaEquation!==a){switch(a){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);break}this._alphaEquation=a}};me.prototype.getInputElement=function(){return this._renderingCanvas};me.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc};me.prototype.setDepthFunction=function(a){this._depthCullingState.depthFunc=a};me.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)};me.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)};me.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)};me.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)};me.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask};me.prototype.setDepthWrite=function(a){this._depthCullingState.depthMask=a};me.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest};me.prototype.setStencilBuffer=function(a){this._stencilState.stencilTest=a};me.prototype.getStencilMask=function(){return this._stencilState.stencilMask};me.prototype.setStencilMask=function(a){this._stencilState.stencilMask=a};me.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc};me.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef};me.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask};me.prototype.setStencilFunction=function(a){this._stencilState.stencilFunc=a};me.prototype.setStencilFunctionReference=function(a){this._stencilState.stencilFuncRef=a};me.prototype.setStencilFunctionMask=function(a){this._stencilState.stencilFuncMask=a};me.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail};me.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail};me.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass};me.prototype.setStencilOperationFail=function(a){this._stencilState.stencilOpStencilFail=a};me.prototype.setStencilOperationDepthFail=function(a){this._stencilState.stencilOpDepthFail=a};me.prototype.setStencilOperationPass=function(a){this._stencilState.stencilOpStencilDepthPass=a};me.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()};me.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)};me.prototype.setAlphaConstants=function(a,e,t,i){this._alphaState.setAlphaBlendConstants(a,e,t,i)};me.prototype.getAlphaMode=function(){return this._alphaMode};me.prototype.getAlphaEquation=function(){return this._alphaEquation};me.prototype.getRenderPassNames=function(){return this._renderPassNames};me.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]};me.prototype.createRenderPassId=function(a){const e=++me._RenderPassIdCounter;return this._renderPassNames[e]=a!=null?a:"NONAME",e};me.prototype.releaseRenderPassId=function(a){this._renderPassNames[a]=void 0;for(let e=0;e{a.onCanvasFocusObservable.notifyObservers(a)},a._onCanvasBlur=()=>{a.onCanvasBlurObservable.notifyObservers(a)},a._onCanvasContextMenu=s=>{a.disableContextMenu&&s.preventDefault()},e.addEventListener("focus",a._onCanvasFocus),e.addEventListener("blur",a._onCanvasBlur),e.addEventListener("contextmenu",a._onCanvasContextMenu),a._onBlur=()=>{a.disablePerformanceMonitorInBackground&&a.performanceMonitor.disable(),a._windowIsBackground=!0},a._onFocus=()=>{a.disablePerformanceMonitorInBackground&&a.performanceMonitor.enable(),a._windowIsBackground=!1},a._onCanvasPointerOut=s=>{document.elementFromPoint(s.clientX,s.clientY)!==e&&a.onCanvasPointerOutObservable.notifyObservers(s)};const i=a.getHostWindow();i&&typeof i.addEventListener=="function"&&(i.addEventListener("blur",a._onBlur),i.addEventListener("focus",a._onFocus)),e.addEventListener("pointerout",a._onCanvasPointerOut),t.doNotHandleTouchAction||Vf(e),!me.audioEngine&&t.audioEngine&&me.AudioEngineFactory&&(me.audioEngine=me.AudioEngineFactory(a.getRenderingCanvas(),a.getAudioContext(),a.getAudioDestination())),xn()&&(a._onFullscreenChange=()=>{a.isFullscreen=!!document.fullscreenElement,a.isFullscreen&&a._pointerLockRequested&&e&&Ka(e)},document.addEventListener("fullscreenchange",a._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",a._onFullscreenChange,!1),a._onPointerLockChange=()=>{a.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",a._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",a._onPointerLockChange,!1)),a.enableOfflineSupport=me.OfflineProviderFactory!==void 0,a._deterministicLockstep=!!t.deterministicLockstep,a._lockstepMaxSteps=t.lockstepMaxSteps||0,a._timeStep=t.timeStep||1/60}function mh(a,e){Ce.Instances.length===1&&me.audioEngine&&(me.audioEngine.dispose(),me.audioEngine=null);const t=a.getHostWindow();t&&typeof t.removeEventListener=="function"&&(t.removeEventListener("blur",a._onBlur),t.removeEventListener("focus",a._onFocus)),e&&(e.removeEventListener("focus",a._onCanvasFocus),e.removeEventListener("blur",a._onCanvasBlur),e.removeEventListener("pointerout",a._onCanvasPointerOut),e.removeEventListener("contextmenu",a._onCanvasContextMenu)),xn()&&(document.removeEventListener("fullscreenchange",a._onFullscreenChange),document.removeEventListener("mozfullscreenchange",a._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",a._onFullscreenChange),document.removeEventListener("msfullscreenchange",a._onFullscreenChange),document.removeEventListener("pointerlockchange",a._onPointerLockChange),document.removeEventListener("mspointerlockchange",a._onPointerLockChange),document.removeEventListener("mozpointerlockchange",a._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",a._onPointerLockChange))}function vh(a){const e=document.createElement("span");e.textContent="Hg",e.style.font=a;const t=document.createElement("div");t.style.display="inline-block",t.style.width="1px",t.style.height="0px",t.style.verticalAlign="bottom";const i=document.createElement("div");i.style.whiteSpace="nowrap",i.appendChild(e),i.appendChild(t),document.body.appendChild(i);let s=0,n=0;try{n=t.getBoundingClientRect().top-e.getBoundingClientRect().top,t.style.verticalAlign="baseline",s=t.getBoundingClientRect().top-e.getBoundingClientRect().top}finally{document.body.removeChild(i)}return{ascent:s,height:n,descent:n-s}}function xh(a,e,t){return new Promise((s,n)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{a.createImageBitmap(r,t).then(o=>{s(o)})})},r.onerror=()=>{n("Error loading image ".concat(r.src))},r.src=e})}function bh(a,e,t,i){const n=a.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}function yh(a){const e=a.requestFullscreen||a.webkitRequestFullscreen;e&&e.call(a)}function Th(){const a=document;document.exitFullscreen?document.exitFullscreen():a.webkitCancelFullScreen&&a.webkitCancelFullScreen()}function Ka(a){if(a.requestPointerLock){const e=a.requestPointerLock();e instanceof Promise?e.then(()=>{a.focus()}).catch(()=>{}):a.focus()}}function Sh(){document.exitPointerLock&&document.exitPointerLock()}class ui{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){ui.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){ui.Enabled&&(this._startMonitoringTime=xi.Now)}endMonitoring(e=!0){if(!ui.Enabled)return;e&&this.fetchNewFrame();const t=xi.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;const e=xi.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}ui.Enabled=!0;me.AudioEngineFactory=(a,e,t)=>new Gf(a,e,t);class Gf{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new Q,this.onAudioLockedObservable=new Q,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!St())return;typeof window.AudioContext<"u"&&(this.canUseWebAudio=!0);const s=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{s&&s.canPlayType&&(s.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||s.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch{}try{s&&s.canPlayType&&s.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch{}}lock(){this._triggerSuspendedState()}unlock(){var e,t;if(((e=this._audioContext)==null?void 0:e.state)==="running"){this._hideMuteButton(),this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this));return}this._tryToRun?(t=this._audioContext)==null||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContextOnStateChange(){var e;(e=this._audioContext)==null||e.addEventListener("statechange",()=>{var t;this.unlocked&&((t=this._audioContext)==null?void 0:t.state)!=="running"&&this._resumeAudioContext()},{once:!0,passive:!0,signal:AbortSignal.timeout(3e3)})}_resumeAudioContext(){var e;return(e=this._audioContext)!=null&&e.resume?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,this._audioContext.state==="running"&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,U.Error("Web Audio: "+e.message)}}_triggerRunningState(){this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then(()=>{this._tryToRun=!1,this._muteButton&&this._hideMuteButton(),this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)}).catch(()=>{this._tryToRun=!1,this.unlocked=!1}))}_triggerSuspendedState(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()}_displayMuteButton(){if(this.useCustomUnlockedButton||this._muteButton)return;this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";const t=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",i=document.createElement("style");i.appendChild(document.createTextNode(t)),document.getElementsByTagName("head")[0].appendChild(i),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",()=>{this._triggerRunningState()},!0),this._muteButton.addEventListener("click",()=>{this.unlock()},!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}}class ie extends Fe{static get NpmPackage(){return me.NpmPackage}static get Version(){return me.Version}static get Instances(){return Ce.Instances}static get LastCreatedEngine(){return Ce.LastCreatedEngine}static get LastCreatedScene(){return Ce.LastCreatedScene}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this._loadFile(e,r=>{s(r)},void 0,t,i,(r,o)=>{n(o)})})}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return vh(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(this._frameHandler!==0){this._frameHandler=0;const{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&this._frameHandler===0&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}enterPointerlock(){this._renderingCanvas&&Ka(this._renderingCanvas)}exitPointerlock(){Sh()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){const t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,s,n,r=null){n=n||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const o=super.createShaderProgram(e,t,i,s,n,r);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_createShaderProgram(e,t,i,s,n=null){const r=s.createProgram();if(e.program=r,!r)throw new Error("Unable to create program");if(s.attachShader(r,t),s.attachShader(r,i),this.webGLVersion>1&&n){const o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(r,n),e.transformFeedback=o}return s.linkProgram(r),this.webGLVersion>1&&n&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),r}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach(t=>{t.postProcesses.forEach(i=>{i._outputTexture===e&&(i._outputTexture=null)}),t.cameras.forEach(i=>{i._postProcesses.forEach(s=>{s&&s._outputTexture===e&&(s._outputTexture=null)})})})}_rescaleTexture(e,t,i,s,n){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const r=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&ie._RescalePostProcessFactory&&(this._rescalePostProcess=ie._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled(()=>{this._rescalePostProcess.onApply=function(l){l._bindTexture("textureSampler",e)};let o=i;o||(o=this.scenes[this.scenes.length-1]),o.postProcessManager.directRender([this._rescalePostProcess],r,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(r),r.dispose(),n&&n()}))}wrapWebGLTexture(e,t=!1,i=3,s=0,n=0){const r=new ph(e,this._gl),o=new Et(this,0,!0);return o._hardwareTexture=r,o.baseWidth=s,o.baseHeight=n,o.width=s,o.height=n,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,s=0){const n=this._gl,r=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),l=this._getRGBABufferInternalSizedFormat(e.type,o),h=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(h,e,!0),this._unpackFlipY(e.invertY);let c=n.TEXTURE_2D;e.isCube&&(c=n.TEXTURE_CUBE_MAP_POSITIVE_X+i),n.texImage2D(c,s,l,o,r,t),this._bindTextureDirectly(h,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){U.Error("WebGL 1 does not support texture comparison.");return}const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),t===0?(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),t===0?(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 Sn(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const s=this._gl;return new Promise((n,r)=>{const o=()=>{const l=s.clientWaitSync(e,t,0);if(l==s.WAIT_FAILED){r();return}if(l==s.TIMEOUT_EXPIRED){setTimeout(o,i);return}n()};o()})}_readPixelsAsync(e,t,i,s,n,r,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const l=this._gl,h=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,h),l.bufferData(l.PIXEL_PACK_BUFFER,o.byteLength,l.STREAM_READ),l.readPixels(e,t,i,s,n,r,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null);const c=l.fenceSync(l.SYNC_GPU_COMMANDS_COMPLETE,0);return c?(l.flush(),this._clientWaitAsync(c,0,10).then(()=>(l.deleteSync(c),l.bindBuffer(l.PIXEL_PACK_BUFFER,h),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,o),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(h),o))):null}dispose(){this.hideLoadingUI(),this._rescalePostProcess&&this._rescalePostProcess.dispose(),mh(this,this._renderingCanvas),super.dispose()}}ie.ALPHA_DISABLE=0;ie.ALPHA_ADD=1;ie.ALPHA_COMBINE=2;ie.ALPHA_SUBTRACT=3;ie.ALPHA_MULTIPLY=4;ie.ALPHA_MAXIMIZED=5;ie.ALPHA_ONEONE=6;ie.ALPHA_PREMULTIPLIED=7;ie.ALPHA_PREMULTIPLIED_PORTERDUFF=8;ie.ALPHA_INTERPOLATE=9;ie.ALPHA_SCREENMODE=10;ie.DELAYLOADSTATE_NONE=0;ie.DELAYLOADSTATE_LOADED=1;ie.DELAYLOADSTATE_LOADING=2;ie.DELAYLOADSTATE_NOTLOADED=4;ie.NEVER=512;ie.ALWAYS=519;ie.LESS=513;ie.EQUAL=514;ie.LEQUAL=515;ie.GREATER=516;ie.GEQUAL=518;ie.NOTEQUAL=517;ie.KEEP=7680;ie.REPLACE=7681;ie.INCR=7682;ie.DECR=7683;ie.INVERT=5386;ie.INCR_WRAP=34055;ie.DECR_WRAP=34056;ie.TEXTURE_CLAMP_ADDRESSMODE=0;ie.TEXTURE_WRAP_ADDRESSMODE=1;ie.TEXTURE_MIRROR_ADDRESSMODE=2;ie.TEXTUREFORMAT_ALPHA=0;ie.TEXTUREFORMAT_LUMINANCE=1;ie.TEXTUREFORMAT_LUMINANCE_ALPHA=2;ie.TEXTUREFORMAT_RGB=4;ie.TEXTUREFORMAT_RGBA=5;ie.TEXTUREFORMAT_RED=6;ie.TEXTUREFORMAT_R=6;ie.TEXTUREFORMAT_RG=7;ie.TEXTUREFORMAT_RED_INTEGER=8;ie.TEXTUREFORMAT_R_INTEGER=8;ie.TEXTUREFORMAT_RG_INTEGER=9;ie.TEXTUREFORMAT_RGB_INTEGER=10;ie.TEXTUREFORMAT_RGBA_INTEGER=11;ie.TEXTURETYPE_UNSIGNED_BYTE=0;ie.TEXTURETYPE_UNSIGNED_INT=0;ie.TEXTURETYPE_FLOAT=1;ie.TEXTURETYPE_HALF_FLOAT=2;ie.TEXTURETYPE_BYTE=3;ie.TEXTURETYPE_SHORT=4;ie.TEXTURETYPE_UNSIGNED_SHORT=5;ie.TEXTURETYPE_INT=6;ie.TEXTURETYPE_UNSIGNED_INTEGER=7;ie.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;ie.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;ie.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;ie.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;ie.TEXTURETYPE_UNSIGNED_INT_24_8=12;ie.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;ie.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;ie.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;ie.TEXTURE_NEAREST_SAMPLINGMODE=1;ie.TEXTURE_BILINEAR_SAMPLINGMODE=2;ie.TEXTURE_TRILINEAR_SAMPLINGMODE=3;ie.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;ie.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;ie.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;ie.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;ie.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;ie.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;ie.TEXTURE_NEAREST_LINEAR=7;ie.TEXTURE_NEAREST_NEAREST=1;ie.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;ie.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;ie.TEXTURE_LINEAR_LINEAR=2;ie.TEXTURE_LINEAR_NEAREST=12;ie.TEXTURE_EXPLICIT_MODE=0;ie.TEXTURE_SPHERICAL_MODE=1;ie.TEXTURE_PLANAR_MODE=2;ie.TEXTURE_CUBIC_MODE=3;ie.TEXTURE_PROJECTION_MODE=4;ie.TEXTURE_SKYBOX_MODE=5;ie.TEXTURE_INVCUBIC_MODE=6;ie.TEXTURE_EQUIRECTANGULAR_MODE=7;ie.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;ie.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;ie.SCALEMODE_FLOOR=1;ie.SCALEMODE_NEAREST=2;ie.SCALEMODE_CEILING=3;const zf=1/2.2,Wf=2.2,xt=(1+Math.sqrt(5))/2,Ne=.001;class Bt{static BuildArray(e,t){const i=[];for(let s=0;s{const n=s.previous;if(!n)return;const r=s.next;r?(n.next=r,r.previous=n):(n.next=void 0,a[e]=n),s.next=void 0,s.previous=void 0}}const Hf=["push","splice","pop","shift","unshift"];function Eh(a,e){const t=Hf.map(i=>Xf(a,i,e));return()=>{t.forEach(i=>{i==null||i()})}}const Ih={};function ft(a,e){Ih[a]=e}function ms(a){return Ih[a]}function Lt(a,e,t=1401298e-51){return Math.abs(a-e)<=t}function ut(a,e){return a===e?a:Math.random()*(e-a)+a}function Ah(a,e,t){return a+(e-a)*t}function gt(a,e=0,t=1){return Math.min(t,Math.max(e,a))}function Ch(a){return a-=Math.PI*2*Math.floor((a+Math.PI)/(Math.PI*2)),a}function Ci(a){const e=a.toString(16);return a<=15?("0"+e).toUpperCase():e.toUpperCase()}const Zt=a=>parseInt(a.toString().replace(/\W/g,""));class fe{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return"{X: ".concat(this.x," Y: ").concat(this.y,"}")}getClassName(){return"Vector2"}getHashCode(){const e=Zt(this.x),t=Zt(this.y);let i=e;return i=i*397^t,i}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return fe.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new fe(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new fe(this.x+e.x,this.y+e.y)}subtract(e){return new fe(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 fe(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 fe(this.x*e,this.y*t)}divide(e){return new fe(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new fe(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.x=this.x-e,i.y=this.y-t,i}negate(){return new fe(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new fe(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=Ne){return e&&Lt(this.x,e.x,t)&&Lt(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new fe(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new fe(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const i=Math.cos(e),s=Math.sin(e),n=i*this.x-s*this.y,r=s*this.x+i*this.y;return t.x=n,t.y=r,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new fe;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new fe(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new fe(0,0)}static One(){return new fe(1,1)}static Random(e=0,t=1){return new fe(ut(e,t),ut(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ut(e,t),ut(e,t))}static get ZeroReadOnly(){return fe._ZeroReadOnly}static FromArray(e,t=0){return new fe(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,s,n){const r=n*n,o=n*r,l=.5*(2*t.x+(-e.x+i.x)*n+(2*e.x-5*t.x+4*i.x-s.x)*r+(-e.x+3*t.x-3*i.x+s.x)*o),h=.5*(2*t.y+(-e.y+i.y)*n+(2*e.y-5*t.y+4*i.y-s.y)*r+(-e.y+3*t.y-3*i.y+s.y)*o);return new fe(l,h)}static ClampToRef(e,t,i,s){return s.x=gt(e.x,t.x,i.x),s.y=gt(e.y,t.y,i.y),s}static Clamp(e,t,i){const s=gt(e.x,t.x,i.x),n=gt(e.y,t.y,i.y);return new fe(s,n)}static Hermite(e,t,i,s,n){const r=n*n,o=n*r,l=2*o-3*r+1,h=-2*o+3*r,c=o-2*r+n,u=o-r,f=e.x*l+i.x*h+t.x*c+s.x*u,d=e.y*l+i.y*h+t.y*c+s.y*u;return new fe(f,d)}static Hermite1stDerivative(e,t,i,s,n){return this.Hermite1stDerivativeToRef(e,t,i,s,n,new fe)}static Hermite1stDerivativeToRef(e,t,i,s,n,r){const o=n*n;return r.x=(o-n)*6*e.x+(3*o-4*n+1)*t.x+(-o+n)*6*i.x+(3*o-2*n)*s.x,r.y=(o-n)*6*e.y+(3*o-4*n+1)*t.y+(-o+n)*6*i.y+(3*o-2*n)*s.y,r}static Lerp(e,t,i){const s=e.x+(t.x-e.x)*i,n=e.y+(t.y-e.y)*i;return new fe(s,n)}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return fe.NormalizeToRef(e,new fe)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.xt.x?e.x:t.x,s=e.y>t.y?e.y:t.y;return new fe(i,s)}static Transform(e,t){return fe.TransformToRef(e,t,new fe)}static TransformToRef(e,t,i){const s=t.m,n=e.x*s[0]+e.y*s[4]+s[12],r=e.x*s[1]+e.y*s[5]+s[13];return i.x=n,i.y=r,i}static PointInTriangle(e,t,i,s){const n=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),r=n<0?-1:1,o=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*r,l=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*r;return o>0&&l>0&&o+l<2*n*r}static Distance(e,t){return Math.sqrt(fe.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y;return i*i+s*s}static Center(e,t){return fe.CenterToRef(e,t,new fe)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const s=fe.DistanceSquared(t,i);if(s===0)return fe.Distance(e,t);const n=i.subtract(t),r=Math.max(0,Math.min(1,fe.Dot(e.subtract(t),n)/s)),o=t.add(n.multiplyByFloats(r,r));return fe.Distance(e,o)}}fe._ZeroReadOnly=fe.Zero();Object.defineProperties(fe.prototype,{dimension:{value:[2]},rank:{value:1}});class v{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return"{X: ".concat(this._x," Y: ").concat(this._y," Z: ").concat(this._z,"}")}getClassName(){return"Vector3"}getHashCode(){const e=Zt(this._x),t=Zt(this._y),i=Zt(this._z);let s=e;return s=s*397^t,s=s*397^i,s}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return v.FromArrayToRef(e,t,this),this}toQuaternion(){return le.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new v(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new v(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 v(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new v(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e.copyFromFloats(this._x*-1,this._y*-1,this._z*-1)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new v(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const s=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const n=t*Math.sin(i)*Math.cos(s),r=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(s);return e.set(n,r,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,n=this._z,r=e._x,o=e._y,l=e._z,h=e._w,c=2*(o*n-l*s),u=2*(l*i-r*n),f=2*(r*s-o*i);return t._x=i+h*c+o*f-l*u,t._y=s+h*u+l*c-r*f,t._z=n+h*f+r*u-o*c,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new v)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new v)}projectOnPlaneToRef(e,t,i){const s=e.normal,n=e.d,r=_e.Vector3[0];this.subtractToRef(t,r),r.normalize();const o=v.Dot(r,s);if(Math.abs(o)<1e-10)i.setAll(1/0);else{const l=-(v.Dot(t,s)+n)/o,h=r.scaleInPlace(l);t.addToRef(h,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=Ne){return e&&Lt(this._x,e._x,t)&&Lt(this._y,e._y,t)&&Lt(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new v(this._x*e,this._y*t,this._z*i)}divide(e){return new v(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._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(!Lt(t,i,e))return!0;const s=Math.abs(this._z);return!Lt(t,s,e)||!Lt(i,s,e)}get isNonUniform(){const e=Math.abs(this._x),t=Math.abs(this._y);if(e!==t)return!0;const i=Math.abs(this._z);return e!==i}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new v(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))}fractToRef(e){return e._x=this.x-Math.floor(this._x),e._y=this.y-Math.floor(this._y),e._z=this.z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new v(this.x-Math.floor(this._x),this.y-Math.floor(this._y),this.z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z===0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if(e=e.toLowerCase(),e==="xyz")return this;const t=_e.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(_e.Matrix[0]),v.TransformCoordinatesToRef(this,_e.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,_e.Vector3[0]),_e.Vector3[0].rotateByQuaternionToRef(e,_e.Vector3[0]),t.addToRef(_e.Vector3[0],i),i}cross(e){return v.CrossToRef(this,e,new v)}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new v)}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new v(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,s){const n=v.Dot(e,i),r=v.Dot(t,i);return(n-s)/(n-r)}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(_e.Vector3[1]),n=t.normalizeToRef(_e.Vector3[2]);let r=v.Dot(s,n);r=gt(r,-1,1);const o=Math.acos(r),l=_e.Vector3[3];return v.CrossToRef(s,n,l),v.Dot(l,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(r)}static GetAngleBetweenVectorsOnPlane(e,t,i){_e.Vector3[0].copyFrom(e);const s=_e.Vector3[0];_e.Vector3[1].copyFrom(t);const n=_e.Vector3[1];_e.Vector3[2].copyFrom(i);const r=_e.Vector3[2],o=_e.Vector3[3],l=_e.Vector3[4];s.normalize(),n.normalize(),r.normalize(),v.CrossToRef(r,s,o),v.CrossToRef(o,r,l);const h=Math.atan2(v.Dot(n,o),v.Dot(n,l));return Ch(h)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=N.Vector3[0];return t.subtractToRef(e,s),i._y=Math.atan2(s.x,s.z)||0,i._x=Math.atan2(Math.sqrt(s.x**2+s.z**2),s.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=v.Zero();return v.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=gt(i,0,1);const n=_e.Vector3[0],r=_e.Vector3[1];n.copyFrom(e);const o=n.length();n.normalizeFromLength(o),r.copyFrom(t);const l=r.length();r.normalizeFromLength(l);const h=v.Dot(n,r);let c,u;if(h<1-Ne){const f=Math.acos(h),d=1/Math.sin(f);c=Math.sin((1-i)*f)*d,u=Math.sin(i*f)*d}else c=1-i,u=i;return n.scaleInPlace(c),r.scaleInPlace(u),s.copyFrom(n).addInPlace(r),s.scaleInPlace(Ah(o,l,i)),s}static SmoothToRef(e,t,i,s,n){return v.SlerpToRef(e,t,s===0?1:i/s,n),n}static FromArray(e,t=0){return new v(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return v.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return v.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new v(0,0,0)}static One(){return new v(1,1,1)}static Up(){return new v(0,1,0)}static get UpReadOnly(){return v._UpReadOnly}static get DownReadOnly(){return v._DownReadOnly}static get RightReadOnly(){return v._RightReadOnly}static get LeftReadOnly(){return v._LeftReadOnly}static get LeftHandedForwardReadOnly(){return v._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return v._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return v._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return v._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return v._ZeroReadOnly}static get OneReadOnly(){return v._OneReadOnly}static Down(){return new v(0,-1,0)}static Forward(e=!1){return new v(0,0,e?-1:1)}static Backward(e=!1){return new v(0,0,e?1:-1)}static Right(){return new v(1,0,0)}static Left(){return new v(-1,0,0)}static Random(e=0,t=1){return new v(ut(e,t),ut(e,t),ut(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ut(e,t),ut(e,t),ut(e,t))}static TransformCoordinates(e,t){const i=v.Zero();return v.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return v.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,n){const r=s.m,o=e*r[0]+t*r[4]+i*r[8]+r[12],l=e*r[1]+t*r[5]+i*r[9]+r[13],h=e*r[2]+t*r[6]+i*r[10]+r[14],c=1/(e*r[3]+t*r[7]+i*r[11]+r[15]);return n._x=o*c,n._y=l*c,n._z=h*c,n._isDirty=!0,n}static TransformNormal(e,t){const i=v.Zero();return v.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,s,n){const r=s.m;return n._x=e*r[0]+t*r[4]+i*r[8],n._y=e*r[1]+t*r[5]+i*r[9],n._z=e*r[2]+t*r[6]+i*r[10],n._isDirty=!0,n}static CatmullRom(e,t,i,s,n){const r=n*n,o=n*r,l=.5*(2*t._x+(-e._x+i._x)*n+(2*e._x-5*t._x+4*i._x-s._x)*r+(-e._x+3*t._x-3*i._x+s._x)*o),h=.5*(2*t._y+(-e._y+i._y)*n+(2*e._y-5*t._y+4*i._y-s._y)*r+(-e._y+3*t._y-3*i._y+s._y)*o),c=.5*(2*t._z+(-e._z+i._z)*n+(2*e._z-5*t._z+4*i._z-s._z)*r+(-e._z+3*t._z-3*i._z+s._z)*o);return new v(l,h,c)}static Clamp(e,t,i){const s=new v;return v.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let n=e._x;n=n>i._x?i._x:n,n=ni._y?i._y:r,r=ri._z?i._z:o,o=o0&&C<0?(P.copyFrom(r),z=t,L=i):C>0&&w<0?(P.copyFrom(l),z=i,L=s):(P.copyFrom(o).scaleInPlace(-1),z=s,L=t);const G=_e.Vector3[9],H=_e.Vector3[4];if(z.subtractToRef(x,b),L.subtractToRef(x,G),v.CrossToRef(b,G,H),!(v.Dot(H,h)<0))return n.copyFrom(x),Math.abs(g*_);const J=_e.Vector3[5];v.CrossToRef(P,H,J),J.normalize();const W=_e.Vector3[9];W.copyFrom(z).subtractInPlace(x);const V=W.length();if(Vthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,s){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(s,this.w),this}maximizeInPlaceFromFloats(e,t,i,s){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(s,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new Pe(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e.z=this.z-Math.floor(this.z),e.w=this.w-Math.floor(this.w),e}fract(){return new Pe(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new Pe)}normalizeToRef(e){const t=this.length();return t===0||t===1?(e.x=this.x,e.y=this.y,e.z=this.z,e.w=this.w,e):this.scaleToRef(1/t,e)}toVector3(){return new v(this.x,this.y,this.z)}clone(){return new Pe(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new Pe(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 Pe.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,n){return n.x=e,n.y=t,n.z=i,n.w=s,n}static Zero(){return new Pe(0,0,0,0)}static One(){return new Pe(1,1,1,1)}static Random(e=0,t=1){return new Pe(ut(e,t),ut(e,t),ut(e,t),ut(e,t))}static RandomToRef(e=0,t=1,i){return i.x=ut(e,t),i.y=ut(e,t),i.z=ut(e,t),i.w=ut(e,t),i}static Clamp(e,t,i){return Pe.ClampToRef(e,t,i,new Pe)}static ClampToRef(e,t,i,s){return s.x=gt(e.x,t.x,i.x),s.y=gt(e.y,t.y,i.y),s.z=gt(e.z,t.z,i.z),s.w=gt(e.w,t.w,i.w),s}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return Pe._ZeroReadOnly}static Normalize(e){return Pe.NormalizeToRef(e,new Pe)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new Pe;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new Pe;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(Pe.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,n=e.z-t.z,r=e.w-t.w;return i*i+s*s+n*n+r*r}static Center(e,t){return Pe.CenterToRef(e,t,new Pe)}static CenterToRef(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i}static TransformCoordinates(e,t){return Pe.TransformCoordinatesToRef(e,t,new Pe)}static TransformCoordinatesToRef(e,t,i){return Pe.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,n){const r=s.m,o=e*r[0]+t*r[4]+i*r[8]+r[12],l=e*r[1]+t*r[5]+i*r[9]+r[13],h=e*r[2]+t*r[6]+i*r[10]+r[14],c=e*r[3]+t*r[7]+i*r[11]+r[15];return n.x=o,n.y=l,n.z=h,n.w=c,n}static TransformNormal(e,t){return Pe.TransformNormalToRef(e,t,new Pe)}static TransformNormalToRef(e,t,i){const s=t.m,n=e.x*s[0]+e.y*s[4]+e.z*s[8],r=e.x*s[1]+e.y*s[5]+e.z*s[9],o=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=n,i.y=r,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,n,r){const o=n.m;return r.x=e*o[0]+t*o[4]+i*o[8],r.y=e*o[1]+t*o[5]+i*o[9],r.z=e*o[2]+t*o[6]+i*o[10],r.w=s,r}static FromVector3(e,t=0){return new Pe(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}}Pe._ZeroReadOnly=Pe.Zero();Object.defineProperties(Pe.prototype,{dimension:{value:[4]},rank:{value:1}});class le{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,s=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return"{X: ".concat(this._x," Y: ").concat(this._y," Z: ").concat(this._z," W: ").concat(this._w,"}")}getClassName(){return"Quaternion"}getHashCode(){const e=Zt(this._x),t=Zt(this._y),i=Zt(this._z),s=Zt(this._w);let n=e;return n=n*397^t,n=n*397^i,n=n*397^s,n}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return le.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=Ne){return e&&Lt(this._x,e._x,t)&&Lt(this._y,e._y,t)&&Lt(this._z,e._z,t)&&Lt(this._w,e._w,t)}clone(){return new le(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._isDirty=!0,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new le(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,s){return this._x+=e,this._y+=t,this._z+=i,this._w+=s,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,s){return this.subtractFromFloatsToRef(e,t,i,s,new le)}subtractFromFloatsToRef(e,t,i,s,n){return n._x=this._x-e,n._y=this._y-t,n._z=this._z-i,n._w=this._w-s,n._isDirty=!0,n}subtract(e){return new le(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new le(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new le(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,s=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,n=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,r=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,n,r),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,s){return this._x*=e,this._y*=t,this._z*=i,this._w*=s,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new le)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,s){return this._x===e&&this._y===t&&this._z===i&&this._w===s}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new le(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return t==0||t==1||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return e==0||e==1?this:(this.scaleInPlace(1/e),this)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new le(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=v.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,n=this._w,r=s*t-i*n,o=.4999999;if(r<-o)e._y=2*Math.atan2(s,n),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(r>o)e._y=2*Math.atan2(s,n),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const l=n*n,h=t*t,c=i*i,u=s*s;e._z=Math.atan2(2*(i*s+t*n),-h-c+u+l),e._x=Math.asin(-2*r),e._y=Math.atan2(2*(t*i+s*n),h-c-u+l),e._isDirty=!0}return e}toRotationMatrix(e){return O.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return le.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}static FromRotationMatrix(e){const t=new le;return le.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],n=i[4],r=i[8],o=i[1],l=i[5],h=i[9],c=i[2],u=i[6],f=i[10],d=s+l+f;let p;return d>0?(p=.5/Math.sqrt(d+1),t._w=.25/p,t._x=(u-h)*p,t._y=(r-c)*p,t._z=(o-n)*p,t._isDirty=!0):s>l&&s>f?(p=2*Math.sqrt(1+s-l-f),t._w=(u-h)/p,t._x=.25*p,t._y=(n+o)/p,t._z=(r+c)/p,t._isDirty=!0):l>f?(p=2*Math.sqrt(1+l-s-f),t._w=(r-c)/p,t._x=(n+o)/p,t._y=.25*p,t._z=(h+u)/p,t._isDirty=!0):(p=2*Math.sqrt(1+f-s-l),t._w=(o-n)/p,t._x=(r+c)/p,t._y=(h+u)/p,t._z=.25*p,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const s=le.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,n){let r=s===0?1:i/s;return r=gt(r,0,1),le.SlerpToRef(e,t,r,n),n}static Zero(){return new le(0,0,0,0)}static Inverse(e){return new le(-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 le(0,0,0,1)}static IsIdentity(e){return e&&e._x===0&&e._y===0&&e._z===0&&e._w===1}static RotationAxis(e,t){return le.RotationAxisToRef(e,t,new le)}static RotationAxisToRef(e,t,i){const s=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*s,i._y=e._y*s,i._z=e._z*s,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new le(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,s,n){return n.copyFromFloats(e,t,i,s),n}static FromEulerAngles(e,t,i){const s=new le;return le.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return le.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new le;return le.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return le.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=Ne){const n=v.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):(v.CrossToRef(e,t,N.Vector3[0]),i.set(N.Vector3[0].x,N.Vector3[0].y,N.Vector3[0].z,n)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new le;return le.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const n=i*.5,r=t*.5,o=e*.5,l=Math.sin(n),h=Math.cos(n),c=Math.sin(r),u=Math.cos(r),f=Math.sin(o),d=Math.cos(o);return s._x=d*c*h+f*u*l,s._y=f*u*h-d*c*l,s._z=d*u*l-f*c*h,s._w=d*u*h+f*c*l,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new le;return le.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const n=(i+e)*.5,r=(i-e)*.5,o=t*.5;return s._x=Math.cos(r)*Math.sin(o),s._y=Math.sin(r)*Math.sin(o),s._z=Math.sin(n)*Math.cos(o),s._w=Math.cos(n)*Math.cos(o),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new le(0,0,0,0);return le.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const n=_e.Matrix[0];return O.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),n),le.FromRotationMatrixToRef(n,s),s}static FromLookDirectionLH(e,t){const i=new le;return le.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=_e.Matrix[0];return O.LookDirectionLHToRef(e,t,s),le.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new le;return le.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=_e.Matrix[0];return O.LookDirectionRHToRef(e,t,s),le.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=le.Identity();return le.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let n,r,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,l=!1;if(o<0&&(l=!0,o=-o),o>.999999)r=1-i,n=l?-i:i;else{const h=Math.acos(o),c=1/Math.sin(h);r=Math.sin((1-i)*h)*c,n=l?-Math.sin(i*h)*c:Math.sin(i*h)*c}return s._x=r*e._x+n*t._x,s._y=r*e._y+n*t._y,s._z=r*e._z+n*t._z,s._w=r*e._w+n*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,n){const r=n*n,o=n*r,l=2*o-3*r+1,h=-2*o+3*r,c=o-2*r+n,u=o-r,f=e._x*l+i._x*h+t._x*c+s._x*u,d=e._y*l+i._y*h+t._y*c+s._y*u,p=e._z*l+i._z*h+t._z*c+s._z*u,g=e._w*l+i._w*h+t._w*c+s._w*u;return new le(f,d,p,g)}static Hermite1stDerivative(e,t,i,s,n){const r=new le;return this.Hermite1stDerivativeToRef(e,t,i,s,n,r),r}static Hermite1stDerivativeToRef(e,t,i,s,n,r){const o=n*n;return r._x=(o-n)*6*e._x+(3*o-4*n+1)*t._x+(-o+n)*6*i._x+(3*o-2*n)*s._x,r._y=(o-n)*6*e._y+(3*o-4*n+1)*t._y+(-o+n)*6*i._y+(3*o-2*n)*s._y,r._z=(o-n)*6*e._z+(3*o-4*n+1)*t._z+(-o+n)*6*i._z+(3*o-2*n)*s._z,r._w=(o-n)*6*e._w+(3*o-4*n+1)*t._w+(-o+n)*6*i._w+(3*o-2*n)*s._w,r._isDirty=!0,r}static Normalize(e){const t=le.Zero();return le.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const s=new le;return le.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(gt(e.x,t.x,i.x),gt(e.y,t.y,i.y),gt(e.z,t.z,i.z),gt(e.w,t.w,i.w))}static Random(e=0,t=1){return new le(ut(e,t),ut(e,t),ut(e,t),ut(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ut(e,t),ut(e,t),ut(e,t),ut(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(le.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,n=e.z-t.z,r=e.w-t.w;return i*i+s*s+n*n+r*r}static Center(e,t){return le.CenterToRef(e,t,le.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}Object.defineProperties(le.prototype,{dimension:{value:[4]},rank:{value:1}});class O{static get Use64Bits(){return Rt.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=O._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,s=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=this._isIdentity?!1:t,this._isIdentity3x2Dirty=this._isIdentity3x2?!1:s}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,Rt.MatrixTrackPrecisionChange&&Rt.MatrixTrackedMatrices.push(this),this._m=new Rt.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=e[0]===1&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===1&&e[6]===0&&e[7]===0&&e[8]===0&&e[9]===0&&e[10]===1&&e[11]===0&&e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,this._m[0]!==1||this._m[5]!==1||this._m[15]!==1?this._isIdentity3x2=!1: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]!==0?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(this._isIdentity===!0)return 1;const e=this._m,t=e[0],i=e[1],s=e[2],n=e[3],r=e[4],o=e[5],l=e[6],h=e[7],c=e[8],u=e[9],f=e[10],d=e[11],p=e[12],g=e[13],_=e[14],m=e[15],x=f*m-_*d,I=u*m-g*d,T=u*_-g*f,y=c*m-p*d,b=c*_-f*p,S=c*g-p*u,A=+(o*x-l*I+h*T),M=-(r*x-l*y+h*b),C=+(r*I-o*y+h*S),w=-(r*T-o*b+l*S);return t*A+i*M+s*C+n*w}toString(){return"{".concat(this.m[0],", ").concat(this.m[1],", ").concat(this.m[2],", ").concat(this.m[3],"\n").concat(this.m[4],", ").concat(this.m[5],", ").concat(this.m[6],", ").concat(this.m[7],"\n").concat(this.m[8],", ").concat(this.m[9],", ").concat(this.m[10],", ").concat(this.m[11],"\n").concat(this.m[12],", ").concat(this.m[13],", ").concat(this.m[14],", ").concat(this.m[15],"}")}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let s=0;s<16;s++)e[t+s]=i[s];return this}asArray(){return this._m}fromArray(e,t=0){return O.FromArrayToRef(e,t,this)}copyFromFloats(...e){return O.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return O.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 O;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,s=t._m,n=e.m;for(let r=0;r<16;r++)s[r]=i[r]+n[r];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;return t[0]+=i[0],t[1]+=i[1],t[2]+=i[2],t[3]+=i[3],t[4]+=i[4],t[5]+=i[5],t[6]+=i[6],t[7]+=i[7],t[8]+=i[8],t[9]+=i[9],t[10]+=i[10],t[11]+=i[11],t[12]+=i[12],t[13]+=i[13],t[14]+=i[14],t[15]+=i[15],this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]+=i[s];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]-=i[s];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,s=e.m,n=t._m;for(let r=0;r<16;r++)n[r]=i[r]-s[r];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]-=i[s];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new O)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,n=e;for(let r=0;r<16;r++)s[r]=i[r]-n[r];return t.markAsUpdated(),t}invertToRef(e){if(this._isIdentity===!0)return O.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],n=t[2],r=t[3],o=t[4],l=t[5],h=t[6],c=t[7],u=t[8],f=t[9],d=t[10],p=t[11],g=t[12],_=t[13],m=t[14],x=t[15],I=d*x-m*p,T=f*x-_*p,y=f*m-_*d,b=u*x-g*p,S=u*m-d*g,A=u*_-g*f,M=+(l*I-h*T+c*y),C=-(o*I-h*b+c*S),w=+(o*T-l*b+c*A),P=-(o*y-l*S+h*A),z=i*M+s*C+n*w+r*P;if(z===0)return e.copyFrom(this),e;const L=1/z,G=h*x-m*c,H=l*x-_*c,ce=l*m-_*h,J=o*x-g*c,W=o*m-g*h,V=o*_-g*l,R=h*p-d*c,k=l*p-f*c,Y=l*d-f*h,he=o*p-u*c,oe=o*d-u*h,re=o*f-u*l,ue=-(s*I-n*T+r*y),xe=+(i*I-n*b+r*S),ae=-(i*T-s*b+r*A),Me=+(i*y-s*S+n*A),ke=+(s*G-n*H+r*ce),Z=-(i*G-n*J+r*W),Ee=+(i*H-s*J+r*V),Oe=-(i*ce-s*W+n*V),He=-(s*R-n*k+r*Y),je=+(i*R-n*he+r*oe),Ct=-(i*k-s*he+r*re),wt=+(i*Y-s*oe+n*re);return O.FromValuesToRef(M*L,ue*L,ke*L,He*L,C*L,xe*L,Z*L,je*L,w*L,ae*L,Ee*L,Ct*L,P*L,Me*L,Oe*L,wt*L,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 v(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 O.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1),this}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiply(e){const t=new O;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]*=i[s];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,n=e;for(let r=0;r<16;r++)s[r]=i[r]*n[r];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const s=this._m,n=e.m,r=s[0],o=s[1],l=s[2],h=s[3],c=s[4],u=s[5],f=s[6],d=s[7],p=s[8],g=s[9],_=s[10],m=s[11],x=s[12],I=s[13],T=s[14],y=s[15],b=n[0],S=n[1],A=n[2],M=n[3],C=n[4],w=n[5],P=n[6],z=n[7],L=n[8],G=n[9],H=n[10],ce=n[11],J=n[12],W=n[13],V=n[14],R=n[15];return t[i]=r*b+o*C+l*L+h*J,t[i+1]=r*S+o*w+l*G+h*W,t[i+2]=r*A+o*P+l*H+h*V,t[i+3]=r*M+o*z+l*ce+h*R,t[i+4]=c*b+u*C+f*L+d*J,t[i+5]=c*S+u*w+f*G+d*W,t[i+6]=c*A+u*P+f*H+d*V,t[i+7]=c*M+u*z+f*ce+d*R,t[i+8]=p*b+g*C+_*L+m*J,t[i+9]=p*S+g*w+_*G+m*W,t[i+10]=p*A+g*P+_*H+m*V,t[i+11]=p*M+g*z+_*ce+m*R,t[i+12]=x*b+I*C+T*L+y*J,t[i+13]=x*S+I*w+T*G+y*W,t[i+14]=x*A+I*P+T*H+y*V,t[i+15]=x*M+I*z+T*ce+y*R,this}divide(e){return this.divideToRef(e,new O)}divideToRef(e,t){const i=this._m,s=e.m,n=t._m;for(let r=0;r<16;r++)n[r]=i[r]/s[r];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]/=i[s];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]=Math.min(t[s],i[s]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]=Math.min(t[s],i[s]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new O)}negateInPlace(){const e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){const t=this._m,i=e._m;for(let s=0;s<16;s++)i[s]=-t[s];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,s=t.m;return i[0]===s[0]&&i[1]===s[1]&&i[2]===s[2]&&i[3]===s[3]&&i[4]===s[4]&&i[5]===s[5]&&i[6]===s[6]&&i[7]===s[7]&&i[8]===s[8]&&i[9]===s[9]&&i[10]===s[10]&&i[11]===s[11]&&i[12]===s[12]&&i[13]===s[13]&&i[14]===s[14]&&i[15]===s[15]}equalsWithEpsilon(e,t=0){const i=this._m,s=e.m;for(let n=0;n<16;n++)if(!Lt(i[n],s[n],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new O)}floorToRef(e){const t=this._m,i=e._m;for(let s=0;s<16;s++)i[s]=Math.floor(t[s]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new O)}fractToRef(e){const t=this._m,i=e._m;for(let s=0;s<16;s++)i[s]=t[s]-Math.floor(t[s]);return e.markAsUpdated(),e}clone(){const e=new O;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=Zt(this._m[0]);for(let t=1;t<16;t++)e=e*397^Zt(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new le,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s,n=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const r=this._m;if(i&&i.copyFromFloats(r[12],r[13],r[14]),e=e||_e.Vector3[0],e.x=Math.sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]),e.y=Math.sqrt(r[4]*r[4]+r[5]*r[5]+r[6]*r[6]),e.z=Math.sqrt(r[8]*r[8]+r[9]*r[9]+r[10]*r[10]),s){const o=(n?s.absoluteScaling.x:s.scaling.x)<0?-1:1,l=(n?s.absoluteScaling.y:s.scaling.y)<0?-1:1,h=(n?s.absoluteScaling.z:s.scaling.z)<0?-1:1;e.x*=o,e.y*=l,e.z*=h}else this.determinant()<=0&&(e.y*=-1);if(e._x===0||e._y===0||e._z===0)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const o=1/e._x,l=1/e._y,h=1/e._z;O.FromValuesToRef(r[0]*o,r[1]*o,r[2]*o,0,r[4]*l,r[5]*l,r[6]*l,0,r[8]*h,r[9]*h,r[10]*h,0,0,0,0,1,_e.Matrix[0]),le.FromRotationMatrixToRef(_e.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=e*4;return new Pe(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=e*4;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 O;return O.TransposeToRef(this,e),e}transposeToRef(e){return O.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,n){if(e<0||e>3)return this;const r=e*4;return this._m[r+0]=t,this._m[r+1]=i,this._m[r+2]=s,this._m[r+3]=n,this.markAsUpdated(),this}scale(e){const t=new O;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=_e.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return O.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 O;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=_e.Vector3[0];if(!this.decompose(t))return O.IdentityToRef(e),e;const i=this._m,s=1/t._x,n=1/t._y,r=1/t._z;return O.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*n,i[5]*n,i[6]*n,0,i[8]*r,i[9]*r,i[10]*r,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const i=new O;return O.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let s=0;s<16;s++)i._m[s]=e[s+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,s){return s._m[0]=e[0+t]*i,s._m[1]=e[1+t]*i,s._m[2]=e[2+t]*i,s._m[3]=e[3+t]*i,s._m[4]=e[4+t]*i,s._m[5]=e[5+t]*i,s._m[6]=e[6+t]*i,s._m[7]=e[7+t]*i,s._m[8]=e[8+t]*i,s._m[9]=e[9+t]*i,s._m[10]=e[10+t]*i,s._m[11]=e[11+t]*i,s._m[12]=e[12+t]*i,s._m[13]=e[13+t]*i,s._m[14]=e[14+t]*i,s._m[15]=e[15+t]*i,s.markAsUpdated(),s}static get IdentityReadOnly(){return O._IdentityReadOnly}static FromValuesToRef(e,t,i,s,n,r,o,l,h,c,u,f,d,p,g,_,m){const x=m._m;x[0]=e,x[1]=t,x[2]=i,x[3]=s,x[4]=n,x[5]=r,x[6]=o,x[7]=l,x[8]=h,x[9]=c,x[10]=u,x[11]=f,x[12]=d,x[13]=p,x[14]=g,x[15]=_,m.markAsUpdated()}static FromValues(e,t,i,s,n,r,o,l,h,c,u,f,d,p,g,_){const m=new O,x=m._m;return x[0]=e,x[1]=t,x[2]=i,x[3]=s,x[4]=n,x[5]=r,x[6]=o,x[7]=l,x[8]=h,x[9]=c,x[10]=u,x[11]=f,x[12]=d,x[13]=p,x[14]=g,x[15]=_,m.markAsUpdated(),m}static Compose(e,t,i){const s=new O;return O.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const n=s._m,r=t._x,o=t._y,l=t._z,h=t._w,c=r+r,u=o+o,f=l+l,d=r*c,p=r*u,g=r*f,_=o*u,m=o*f,x=l*f,I=h*c,T=h*u,y=h*f,b=e._x,S=e._y,A=e._z;return n[0]=(1-(_+x))*b,n[1]=(p+y)*b,n[2]=(g-T)*b,n[3]=0,n[4]=(p-y)*S,n[5]=(1-(d+x))*S,n[6]=(m+I)*S,n[7]=0,n[8]=(g+T)*A,n[9]=(m-I)*A,n[10]=(1-(d+_))*A,n[11]=0,n[12]=i._x,n[13]=i._y,n[14]=i._z,n[15]=1,s.markAsUpdated(),s}static Identity(){const e=O.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 O.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=O.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 O;return O.RotationXToRef(e,t),t}static Invert(e){const t=new O;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return O.FromValuesToRef(1,0,0,0,0,s,i,0,0,-i,s,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationY(e){const t=new O;return O.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return O.FromValuesToRef(s,0,-i,0,0,1,0,0,i,0,s,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationZ(e){const t=new O;return O.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return O.FromValuesToRef(s,i,0,0,-i,s,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationAxis(e,t){const i=new O;return O.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),n=Math.cos(-t),r=1-n;e.normalize();const o=i._m;return o[0]=e._x*e._x*r+n,o[1]=e._x*e._y*r-e._z*s,o[2]=e._x*e._z*r+e._y*s,o[3]=0,o[4]=e._y*e._x*r+e._z*s,o[5]=e._y*e._y*r+n,o[6]=e._y*e._z*r-e._x*s,o[7]=0,o[8]=e._z*e._x*r-e._y*s,o[9]=e._z*e._y*r+e._x*s,o[10]=e._z*e._z*r+n,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const n=v.Dot(t,e),r=i._m;if(n<-1+Ne)r[0]=-1,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=s?1:-1,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=s?-1:1,r[11]=0;else{const o=v.Cross(t,e),l=1/(1+n);r[0]=o._x*o._x*l+n,r[1]=o._y*o._x*l-o._z,r[2]=o._z*o._x*l+o._y,r[3]=0,r[4]=o._x*o._y*l+o._z,r[5]=o._y*o._y*l+n,r[6]=o._z*o._y*l-o._x,r[7]=0,r[8]=o._x*o._z*l-o._y,r[9]=o._y*o._z*l+o._x,r[10]=o._z*o._z*l+n,r[11]=0}return r[12]=0,r[13]=0,r[14]=0,r[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new O;return O.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return le.RotationYawPitchRollToRef(e,t,i,_e.Quaternion[0]),_e.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new O;return O.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return O.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,s),s._updateIdentityStatus(e===1&&t===1&&i===1),s}static Translation(e,t,i){const s=new O;return O.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return O.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,s),s._updateIdentityStatus(e===0&&t===0&&i===0),s}static Lerp(e,t,i){const s=new O;return O.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const n=s._m,r=e.m,o=t.m;for(let l=0;l<16;l++)n[l]=r[l]*(1-i)+o[l]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new O;return O.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const n=_e.Vector3[0],r=_e.Quaternion[0],o=_e.Vector3[1];e.decompose(n,r,o);const l=_e.Vector3[2],h=_e.Quaternion[1],c=_e.Vector3[3];t.decompose(l,h,c);const u=_e.Vector3[4];v.LerpToRef(n,l,i,u);const f=_e.Quaternion[2];le.SlerpToRef(r,h,i,f);const d=_e.Vector3[5];return v.LerpToRef(o,c,i,d),O.ComposeToRef(u,f,d,s),s}static LookAtLH(e,t,i){const s=new O;return O.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const n=_e.Vector3[0],r=_e.Vector3[1],o=_e.Vector3[2];t.subtractToRef(e,o),o.normalize(),v.CrossToRef(i,o,n);const l=n.lengthSquared();l===0?n.x=1:n.normalizeFromLength(Math.sqrt(l)),v.CrossToRef(o,n,r),r.normalize();const h=-v.Dot(n,e),c=-v.Dot(r,e),u=-v.Dot(o,e);return O.FromValuesToRef(n._x,r._x,o._x,0,n._y,r._y,o._y,0,n._z,r._z,o._z,0,h,c,u,1,s),s}static LookAtRH(e,t,i){const s=new O;return O.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const n=_e.Vector3[0],r=_e.Vector3[1],o=_e.Vector3[2];e.subtractToRef(t,o),o.normalize(),v.CrossToRef(i,o,n);const l=n.lengthSquared();l===0?n.x=1:n.normalizeFromLength(Math.sqrt(l)),v.CrossToRef(o,n,r),r.normalize();const h=-v.Dot(n,e),c=-v.Dot(r,e),u=-v.Dot(o,e);return O.FromValuesToRef(n._x,r._x,o._x,0,n._y,r._y,o._y,0,n._z,r._z,o._z,0,h,c,u,1,s),s}static LookDirectionLH(e,t){const i=new O;return O.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=_e.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const n=_e.Vector3[1];return v.CrossToRef(t,s,n),O.FromValuesToRef(n._x,n._y,n._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new O;return O.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=_e.Vector3[2];return v.CrossToRef(t,e,s),O.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,s,n){const r=new O;return O.OrthoLHToRef(e,t,i,s,r,n),r}static OrthoLHToRef(e,t,i,s,n,r){const o=i,l=s,h=2/e,c=2/t,u=2/(l-o),f=-(l+o)/(l-o);return O.FromValuesToRef(h,0,0,0,0,c,0,0,0,0,u,0,0,0,f,1,n),r&&n.multiplyToRef(Ss,n),n._updateIdentityStatus(h===1&&c===1&&u===1&&f===0),n}static OrthoOffCenterLH(e,t,i,s,n,r,o){const l=new O;return O.OrthoOffCenterLHToRef(e,t,i,s,n,r,l,o),l}static OrthoOffCenterLHToRef(e,t,i,s,n,r,o,l){const h=n,c=r,u=2/(t-e),f=2/(s-i),d=2/(c-h),p=-(c+h)/(c-h),g=(e+t)/(e-t),_=(s+i)/(i-s);return O.FromValuesToRef(u,0,0,0,0,f,0,0,0,0,d,0,g,_,p,1,o),l&&o.multiplyToRef(Ss,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,s,n,r,o,l,h,c,u){const f=-o*Math.cos(l),d=-o*Math.sin(l);return O.TranslationToRef(0,0,-h,_e.Matrix[1]),O.FromValuesToRef(1,0,0,0,0,1,0,0,f,d,1,0,0,0,0,1,_e.Matrix[0]),_e.Matrix[1].multiplyToRef(_e.Matrix[0],_e.Matrix[0]),O.TranslationToRef(0,0,h,_e.Matrix[1]),_e.Matrix[0].multiplyToRef(_e.Matrix[1],_e.Matrix[0]),O.OrthoOffCenterLHToRef(e,t,i,s,n,r,c,u),_e.Matrix[0].multiplyToRef(c,c),c}static OrthoOffCenterRH(e,t,i,s,n,r,o){const l=new O;return O.OrthoOffCenterRHToRef(e,t,i,s,n,r,l,o),l}static OrthoOffCenterRHToRef(e,t,i,s,n,r,o,l){return O.OrthoOffCenterLHToRef(e,t,i,s,n,r,o,l),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,s,n,r,o,l,h,c,u){const f=o*Math.cos(l),d=o*Math.sin(l);return O.TranslationToRef(0,0,h,_e.Matrix[1]),O.FromValuesToRef(1,0,0,0,0,1,0,0,f,d,1,0,0,0,0,1,_e.Matrix[0]),_e.Matrix[1].multiplyToRef(_e.Matrix[0],_e.Matrix[0]),O.TranslationToRef(0,0,-h,_e.Matrix[1]),_e.Matrix[0].multiplyToRef(_e.Matrix[1],_e.Matrix[0]),O.OrthoOffCenterRHToRef(e,t,i,s,n,r,c,u),_e.Matrix[0].multiplyToRef(c,c),c}static PerspectiveLH(e,t,i,s,n,r=0){const o=new O,l=i,h=s,c=2*l/e,u=2*l/t,f=(h+l)/(h-l),d=-2*h*l/(h-l),p=Math.tan(r);return O.FromValuesToRef(c,0,0,0,0,u,0,p,0,0,f,1,0,0,d,0,o),n&&o.multiplyToRef(Ss,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,s,n,r=0,o=!1){const l=new O;return O.PerspectiveFovLHToRef(e,t,i,s,l,!0,n,r,o),l}static PerspectiveFovLHToRef(e,t,i,s,n,r=!0,o,l=0,h=!1){const c=i,u=s,f=1/Math.tan(e*.5),d=r?f/t:f,p=r?f:f*t,g=h&&c===0?-1:u!==0?(u+c)/(u-c):1,_=h&&c===0?2*u:u!==0?-2*u*c/(u-c):-2*c,m=Math.tan(l);return O.FromValuesToRef(d,0,0,0,0,p,0,m,0,0,g,1,0,0,_,0,n),o&&n.multiplyToRef(Ss,n),n._updateIdentityStatus(!1),n}static PerspectiveFovReverseLHToRef(e,t,i,s,n,r=!0,o,l=0){const h=1/Math.tan(e*.5),c=r?h/t:h,u=r?h:h*t,f=Math.tan(l);return O.FromValuesToRef(c,0,0,0,0,u,0,f,0,0,-i,1,0,0,1,0,n),o&&n.multiplyToRef(Ss,n),n._updateIdentityStatus(!1),n}static PerspectiveFovRH(e,t,i,s,n,r=0,o=!1){const l=new O;return O.PerspectiveFovRHToRef(e,t,i,s,l,!0,n,r,o),l}static PerspectiveFovRHToRef(e,t,i,s,n,r=!0,o,l=0,h=!1){const c=i,u=s,f=1/Math.tan(e*.5),d=r?f/t:f,p=r?f:f*t,g=h&&c===0?1:u!==0?-(u+c)/(u-c):-1,_=h&&c===0?2*u:u!==0?-2*u*c/(u-c):-2*c,m=Math.tan(l);return O.FromValuesToRef(d,0,0,0,0,p,0,m,0,0,g,-1,0,0,_,0,n),o&&n.multiplyToRef(Ss,n),n._updateIdentityStatus(!1),n}static PerspectiveFovReverseRHToRef(e,t,i,s,n,r=!0,o,l=0){const h=1/Math.tan(e*.5),c=r?h/t:h,u=r?h:h*t,f=Math.tan(l);return O.FromValuesToRef(c,0,0,0,0,u,0,f,0,0,-i,-1,0,0,-1,0,n),o&&n.multiplyToRef(Ss,n),n._updateIdentityStatus(!1),n}static GetFinalMatrix(e,t,i,s,n,r){const o=e.width,l=e.height,h=e.x,c=e.y,u=O.FromValues(o/2,0,0,0,0,-l/2,0,0,0,0,r-n,0,h+o/2,l/2+c,n,1),f=new O;return t.multiplyToRef(i,f),f.multiplyToRef(s,f),f.multiplyToRef(u,f)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return Rt.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 Rt.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new O;return O.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],n=i[4],r=i[8],o=i[12],l=i[1],h=i[5],c=i[9],u=i[13],f=i[2],d=i[6],p=i[10],g=i[14],_=i[3],m=i[7],x=i[11],I=i[15],T=t._m;return T[0]=s,T[1]=n,T[2]=r,T[3]=o,T[4]=l,T[5]=h,T[6]=c,T[7]=u,T[8]=f,T[9]=d,T[10]=p,T[11]=g,T[12]=_,T[13]=m,T[14]=x,T[15]=I,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new O;return O.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,n=e.normal.z,r=-2*i,o=-2*s,l=-2*n;return O.FromValuesToRef(r*i+1,o*i,l*i,0,r*s,o*s+1,l*s,0,r*n,o*n,l*n+1,0,r*e.d,o*e.d,l*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return O.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,s),s}static FromQuaternionToRef(e,t){const i=e._x*e._x,s=e._y*e._y,n=e._z*e._z,r=e._x*e._y,o=e._z*e._w,l=e._z*e._x,h=e._y*e._w,c=e._y*e._z,u=e._x*e._w;return t._m[0]=1-2*(s+n),t._m[1]=2*(r+o),t._m[2]=2*(l-h),t._m[3]=0,t._m[4]=2*(r-o),t._m[5]=1-2*(n+i),t._m[6]=2*(c+u),t._m[7]=0,t._m[8]=2*(l+h),t._m[9]=2*(c-u),t._m[10]=1-2*(s+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}O._UpdateFlagSeed=0;O._IdentityReadOnly=O.Identity();Object.defineProperties(O.prototype,{dimension:{value:[4,4]},rank:{value:2}});class _e{}_e.Vector3=Bt.BuildTuple(11,v.Zero);_e.Matrix=Bt.BuildTuple(2,O.Identity);_e.Quaternion=Bt.BuildTuple(3,le.Zero);class N{}N.Vector2=Bt.BuildTuple(3,fe.Zero);N.Vector3=Bt.BuildTuple(13,v.Zero);N.Vector4=Bt.BuildTuple(3,Pe.Zero);N.Quaternion=Bt.BuildTuple(2,le.Zero);N.Matrix=Bt.BuildTuple(8,O.Identity);ft("BABYLON.Vector2",fe);ft("BABYLON.Vector3",v);ft("BABYLON.Vector4",Pe);ft("BABYLON.Matrix",O);const Ss=O.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);var ci;(function(a){a[a.LOCAL=0]="LOCAL",a[a.WORLD=1]="WORLD",a[a.BONE=2]="BONE"})(ci||(ci={}));class Wt{}Wt.X=new v(1,0,0);Wt.Y=new v(0,1,0);Wt.Z=new v(0,0,1);var n0;(function(a){a[a.X=0]="X",a[a.Y=1]="Y",a[a.Z=2]="Z"})(n0||(n0={}));class Ye{static Sign(e){return e=+e,e===0||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(e===0)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e=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=Ye.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=Ye.Repeat(e,t*2);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=Ye.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return Math.abs(t-e)<=i?s=t:s=e+Ye.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=Ye.DeltaAngle(e,t);let n=0;return-i180&&(s-=360),e+s*gt(i)}static InverseLerp(e,t,i){let s=0;return e!=t?s=gt((i-e)/(t-e)):s=0,s}static Hermite(e,t,i,s,n){const r=n*n,o=n*r,l=2*o-3*r+1,h=-2*o+3*r,c=o-2*r+n,u=o-r;return e*l+i*h+t*c+s*u}static Hermite1stDerivative(e,t,i,s,n){const r=n*n;return(r-n)*6*e+(3*r-4*n+1)*t+(-r+n)*6*i+(3*r-2*n)*s}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static HCF(e,t){const i=e%t;return i===0?t:Ye.HCF(t,i)}}Ye.TwoPi=Math.PI*2;Ye.WithinEpsilon=Lt;Ye.ToHex=Ci;Ye.Clamp=gt;Ye.Lerp=Ah;Ye.RandomRange=ut;Ye.NormalizeRadians=Ch;function Ys(a){return Math.pow(a,Wf)}function qs(a){return a<=.04045?.0773993808*a:Math.pow(.947867299*(a+.055),2.4)}function $s(a){return Math.pow(a,zf)}function js(a){return a<=.0031308?12.92*a:1.055*Math.pow(a,.41666)-.055}class pe{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=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|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 pe.FromArrayToRef(e,t,this),this}toColor4(e=1){return new X(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return this.r*.3+this.g*.59+this.b*.11}multiply(e){return new pe(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new pe(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=Ne){return Ye.WithinEpsilon(this.r,e.r,t)&&Ye.WithinEpsilon(this.g,e.g,t)&&Ye.WithinEpsilon(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new pe(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=gt(this.r,e,t),i.g=gt(this.g,e,t),i.b=gt(this.b,e,t),i}add(e){return new pe(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new pe(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new pe(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s}clone(){return new pe(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){const e=Math.round(this.r*255),t=Math.round(this.g*255),i=Math.round(this.b*255);return"#"+Ci(e)+Ci(t)+Ci(i)}toHSV(){return this.toHSVToRef(new pe)}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,n=Math.max(t,i,s),r=Math.min(t,i,s);let o=0,l=0;const h=n,c=n-r;return n!==0&&(l=c/n),n!=r&&(n==t?(o=(i-s)/c,i=0&&r<=1?(l=n,h=o):r>=1&&r<=2?(l=o,h=n):r>=2&&r<=3?(h=n,c=o):r>=3&&r<=4?(h=o,c=n):r>=4&&r<=5?(l=o,c=n):r>=5&&r<=6&&(l=n,c=o);const u=i-n;return s.r=l+u,s.g=h+u,s.b=c+u,s}static FromHSV(e,t,i){const s=new pe(0,0,0);return pe.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==7)return new pe(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16);return pe.FromInts(t,i,s)}static FromArray(e,t=0){return new pe(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 pe(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new pe(0,0,0);return pe.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,s,n){const r=n*n,o=n*r,l=2*o-3*r+1,h=-2*o+3*r,c=o-2*r+n,u=o-r,f=e.r*l+i.r*h+t.r*c+s.r*u,d=e.g*l+i.g*h+t.g*c+s.g*u,p=e.b*l+i.b*h+t.b*c+s.b*u;return new pe(f,d,p)}static Hermite1stDerivative(e,t,i,s,n){const r=pe.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,n,r),r}static Hermite1stDerivativeToRef(e,t,i,s,n,r){const o=n*n;r.r=(o-n)*6*e.r+(3*o-4*n+1)*t.r+(-o+n)*6*i.r+(3*o-2*n)*s.r,r.g=(o-n)*6*e.g+(3*o-4*n+1)*t.g+(-o+n)*6*i.g+(3*o-2*n)*s.g,r.b=(o-n)*6*e.b+(3*o-4*n+1)*t.b+(-o+n)*6*i.b+(3*o-2*n)*s.b}static Red(){return new pe(1,0,0)}static Green(){return new pe(0,1,0)}static Blue(){return new pe(0,0,1)}static Black(){return new pe(0,0,0)}static get BlackReadOnly(){return pe._BlackReadOnly}static White(){return new pe(1,1,1)}static Purple(){return new pe(.5,0,.5)}static Magenta(){return new pe(1,0,1)}static Yellow(){return new pe(1,1,0)}static Gray(){return new pe(.5,.5,.5)}static Teal(){return new pe(0,1,1)}static Random(){return new pe(Math.random(),Math.random(),Math.random())}}pe._BlackReadOnly=pe.Black();Object.defineProperties(pe.prototype,{dimension:{value:[3]},rank:{value:1}});class X{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new X(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,s){return this.r+=e,this.g+=t,this.b+=i,this.a+=s,this}subtract(e){return new X(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,s){return new X(this.r-e,this.g-t,this.b-i,this.a-s)}subtractFromFloatsToRef(e,t,i,s,n){return n.r=this.r-e,n.g=this.g-t,n.b=this.b-i,n.a=this.a-s,n}scale(e){return new X(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=gt(this.r,e,t),i.g=gt(this.g,e,t),i.b=gt(this.b,e,t),i.a=gt(this.a,e,t),i}multiply(e){return new X(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,s){return new X(this.r*e,this.g*t,this.b*i,this.a*s)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,s){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(s,this.a),this}maximizeInPlaceFromFloats(e,t,i,s){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(s,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=Ne){return Ye.WithinEpsilon(this.r,e.r,t)&&Ye.WithinEpsilon(this.g,e.g,t)&&Ye.WithinEpsilon(this.b,e.b,t)&&Ye.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,i,s){return this.r===e&&this.g===t&&this.b===i&&this.a===s}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e=e*397^(this.a*255|0),e}clone(){return new X().copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,s){return this.r=e,this.g=t,this.b=i,this.a=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(this.r*255),i=Math.round(this.g*255),s=Math.round(this.b*255);if(e)return"#"+Ci(t)+Ci(i)+Ci(s);const n=Math.round(this.a*255);return"#"+Ci(t)+Ci(i)+Ci(s)+Ci(n)}toLinearSpace(e=!1){const t=new X;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=qs(this.r),e.g=qs(this.g),e.b=qs(this.b)):(e.r=Ys(this.r),e.g=Ys(this.g),e.b=Ys(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new X;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=js(this.r),e.g=js(this.g),e.b=js(this.b)):(e.r=$s(this.r),e.g=$s(this.g),e.b=$s(this.b)),e.a=this.a,this}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==9&&e.length!==7)return new X(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16),n=e.length===9?parseInt(e.substring(7,9),16):255;return X.FromInts(t,i,s,n)}static Lerp(e,t,i){return X.LerpToRef(e,t,i,new X)}static LerpToRef(e,t,i,s){return s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i,s.a=e.a+(t.a-e.a)*i,s}static Hermite(e,t,i,s,n){const r=n*n,o=n*r,l=2*o-3*r+1,h=-2*o+3*r,c=o-2*r+n,u=o-r,f=e.r*l+i.r*h+t.r*c+s.r*u,d=e.g*l+i.g*h+t.g*c+s.g*u,p=e.b*l+i.b*h+t.b*c+s.b*u,g=e.a*l+i.a*h+t.a*c+s.a*u;return new X(f,d,p,g)}static Hermite1stDerivative(e,t,i,s,n){const r=new X;return this.Hermite1stDerivativeToRef(e,t,i,s,n,r),r}static Hermite1stDerivativeToRef(e,t,i,s,n,r){const o=n*n;r.r=(o-n)*6*e.r+(3*o-4*n+1)*t.r+(-o+n)*6*i.r+(3*o-2*n)*s.r,r.g=(o-n)*6*e.g+(3*o-4*n+1)*t.g+(-o+n)*6*i.g+(3*o-2*n)*s.g,r.b=(o-n)*6*e.b+(3*o-4*n+1)*t.b+(-o+n)*6*i.b+(3*o-2*n)*s.b,r.a=(o-n)*6*e.a+(3*o-4*n+1)*t.a+(-o+n)*6*i.a+(3*o-2*n)*s.a}static FromColor3(e,t=1){return new X(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new X(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,s){return new X(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===t*3){const i=[];for(let s=0;snew X(0,0,0,0));ft("BABYLON.Color3",pe);ft("BABYLON.Color4",X);class Yt{constructor(e,t,i,s){this.normal=new v(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Yt(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=e*397^(this.d|0),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 e!==0&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=Yt._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,n=this.normal.y,r=this.normal.z,o=this.d,l=s*i[0]+n*i[1]+r*i[2]+o*i[3],h=s*i[4]+n*i[5]+r*i[6]+o*i[7],c=s*i[8]+n*i[9]+r*i[10]+o*i[11],u=s*i[12]+n*i[13]+r*i[14]+o*i[15];return new Yt(l,h,c,u)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const s=t.x-e.x,n=t.y-e.y,r=t.z-e.z,o=i.x-e.x,l=i.y-e.y,h=i.z-e.z,c=n*h-r*l,u=r*o-s*h,f=s*l-n*o,d=Math.sqrt(c*c+u*u+f*f);let p;return d!==0?p=1/d:p=0,this.normal.x=c*p,this.normal.y=u*p,this.normal.z=f*p,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return v.Dot(this.normal,e)<=t}signedDistanceTo(e){return v.Dot(e,this.normal)+this.d}static FromArray(e){return new Yt(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new Yt(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new Yt(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return v.Dot(i,t)+s}}Yt._TmpMatrix=O.Identity();class mi{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new Yt(0,0,0,0));return mi.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){mi.GetNearPlaneToRef(e,t[0]),mi.GetFarPlaneToRef(e,t[1]),mi.GetLeftPlaneToRef(e,t[2]),mi.GetRightPlaneToRef(e,t[3]),mi.GetTopPlaneToRef(e,t[4]),mi.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}var r0;(function(a){a[a.CW=0]="CW",a[a.CCW=1]="CCW"})(r0||(r0={}));class Vi{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return this._radians*180/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),s=Math.atan2(i.y,i.x);return new Vi(s)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(i===0)return new Vi(Math.PI/2);i=Math.sqrt(i);let s=e.dot(t)/i;s=Ye.Clamp(s,-1,1);const n=Math.acos(s);return new Vi(n)}static FromRadians(e){return new Vi(e)}static FromDegrees(e){return new Vi(e*Math.PI/180)}}class Kf{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const s=Math.pow(t.x,2)+Math.pow(t.y,2),n=(Math.pow(e.x,2)+Math.pow(e.y,2)-s)/2,r=(s-Math.pow(i.x,2)-Math.pow(i.y,2))/2,o=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new fe((n*(t.y-i.y)-r*(e.y-t.y))/o,((e.x-t.x)*r-(t.x-i.x)*n)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=Vi.BetweenTwoPoints(this.centerPoint,this.startPoint);const l=this.startAngle.degrees();let h=Vi.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),c=Vi.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();h-l>180&&(h-=360),h-l<-180&&(h+=360),c-h>180&&(c-=360),c-h<-180&&(c+=360),this.orientation=h-l<0?0:1,this.angle=Vi.FromDegrees(this.orientation===0?l-c:c-l)}}class Mr{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new fe(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new fe(e,t),s=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(s).length(),this}addArcTo(e,t,i,s,n=36){if(this.closed)return this;const r=this._points[this._points.length-1],o=new fe(e,t),l=new fe(i,s),h=new Kf(r,o,l);let c=h.angle.radians()/n;h.orientation===0&&(c*=-1);let u=h.startAngle.radians()+c;for(let f=0;f(1-l)*(1-l)*h+2*l*(1-l)*c+l*l*u,o=this._points[this._points.length-1];for(let l=0;l<=n;l++){const h=l/n,c=r(h,o.x,e,i),u=r(h,o.y,t,s);this.addLineTo(c,u)}return this}addBezierCurveTo(e,t,i,s,n,r,o=36){if(this.closed)return this;const l=(c,u,f,d,p)=>(1-c)*(1-c)*(1-c)*u+3*c*(1-c)*(1-c)*f+3*c*c*(1-c)*d+c*c*c*p,h=this._points[this._points.length-1];for(let c=0;c<=o;c++){const u=c/o,f=l(u,h.x,e,i,n),d=l(u,h.y,t,s,r);this.addLineTo(f,d)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let s=i-1,n=0;nNumber.EPSILON){if(h<0&&(r=this._points[n],l=-l,o=this._points[s],h=-h),e.yo.y)continue;if(e.y===r.y&&e.x===r.x)return!0;{const c=h*(e.x-r.x)-l*(e.y-r.y);if(c===0)return!0;if(c<0)continue;t=!t}}else{if(e.y!==r.y)continue;if(o.x<=e.x&&e.x<=r.x||r.x<=e.x&&e.x<=o.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,s=0;s1)return fe.Zero();const t=e*this.length();let i=0;for(let s=0;s=i&&t<=h){const c=l.normalize(),u=t-i;return new fe(r.x+c.x*u,r.y+c.y*u)}i=h}return fe.Zero()}static StartingAt(e,t){return new Mr(e,t)}}class In{constructor(e,t=null,i,s=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:v.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:O.Identity()};for(let n=0;nt){const h=e;e=t,t=h}const i=this.getCurve(),s=this.getPointAt(e);let n=this.getPreviousPointIndexAt(e);const r=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,l=[];return e!==0&&(n++,l.push(s)),l.push(...i.slice(n,o)),(t!==1||e===1)&&l.push(r),new In(l,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let s=0;st+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,s=e.length();if(s===0&&(s=1),t==null){let n;Ye.WithinEpsilon(Math.abs(e.y)/s,1,Ne)?Ye.WithinEpsilon(Math.abs(e.x)/s,1,Ne)?Ye.WithinEpsilon(Math.abs(e.z)/s,1,Ne)?n=v.Zero():n=new v(0,0,1):n=new v(1,0,0):n=new v(0,-1,0),i=v.Cross(e,n)}else i=v.Cross(e,t),v.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let s=i[0],n,r=0;const o=e*this.length();for(let l=1;lo){const u=(r-o)/h,f=s.subtract(n),d=n.add(f.scaleInPlace(u));return this._setPointAtData(e,1-u,d,l-1,t)}s=n}return this._pointAtData}_setPointAtData(e,t,i,s,n){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=s,this._pointAtData.interpolateReady=n,n&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=O.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),s=this._normals[e].clone(),n=this._binormals[e].clone(),r=this._tangents[t].clone(),o=this._normals[t].clone(),l=this._binormals[t].clone(),h=le.RotationQuaternionFromAxis(s,n,i),c=le.RotationQuaternionFromAxis(o,l,r);le.Slerp(h,c,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class oi{constructor(e,t){this.width=e,this.height=t}toString(){return"{W: ".concat(this.width,", H: ").concat(this.height,"}")}getClassName(){return"Size"}getHashCode(){let e=this.width|0;return e=e*397^(this.height|0),e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new oi(this.width*e,this.height*t)}clone(){return new oi(this.width,this.height)}equals(e){return e?this.width===e.width&&this.height===e.height:!1}get surface(){return this.width*this.height}static Zero(){return new oi(0,0)}add(e){return new oi(this.width+e.width,this.height+e.height)}subtract(e){return new oi(this.width-e.width,this.height-e.height)}scale(e){return new oi(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,n=e.height+(t.height-e.height)*i;return new oi(s,n)}}class Qs{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new Qs(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new Qs(this.x,this.y,this.width,this.height)}}var a0;(function(a){a.LowPower="low-power",a.HighPerformance="high-performance"})(a0||(a0={}));var o0;(function(a){a.DepthClipControl="depth-clip-control",a.Depth32FloatStencil8="depth32float-stencil8",a.TextureCompressionBC="texture-compression-bc",a.TextureCompressionETC2="texture-compression-etc2",a.TextureCompressionASTC="texture-compression-astc",a.TimestampQuery="timestamp-query",a.IndirectFirstInstance="indirect-first-instance",a.ShaderF16="shader-f16",a.RG11B10UFloatRenderable="rg11b10ufloat-renderable",a.BGRA8UnormStorage="bgra8unorm-storage",a.Float32Filterable="float32-filterable"})(o0||(o0={}));var l0;(function(a){a.Unmapped="unmapped",a.Pending="pending",a.Mapped="mapped"})(l0||(l0={}));var We;(function(a){a[a.MapRead=1]="MapRead",a[a.MapWrite=2]="MapWrite",a[a.CopySrc=4]="CopySrc",a[a.CopyDst=8]="CopyDst",a[a.Index=16]="Index",a[a.Vertex=32]="Vertex",a[a.Uniform=64]="Uniform",a[a.Storage=128]="Storage",a[a.Indirect=256]="Indirect",a[a.QueryResolve=512]="QueryResolve"})(We||(We={}));var h0;(function(a){a[a.Read=1]="Read",a[a.Write=2]="Write"})(h0||(h0={}));var c0;(function(a){a.E1d="1d",a.E2d="2d",a.E3d="3d"})(c0||(c0={}));var u0;(function(a){a[a.CopySrc=1]="CopySrc",a[a.CopyDst=2]="CopyDst",a[a.TextureBinding=4]="TextureBinding",a[a.StorageBinding=8]="StorageBinding",a[a.RenderAttachment=16]="RenderAttachment"})(u0||(u0={}));var f0;(function(a){a.E1d="1d",a.E2d="2d",a.E2dArray="2d-array",a.Cube="cube",a.CubeArray="cube-array",a.E3d="3d"})(f0||(f0={}));var d0;(function(a){a.All="all",a.StencilOnly="stencil-only",a.DepthOnly="depth-only"})(d0||(d0={}));var p0;(function(a){a.R8Unorm="r8unorm",a.R8Snorm="r8snorm",a.R8Uint="r8uint",a.R8Sint="r8sint",a.R16Uint="r16uint",a.R16Sint="r16sint",a.R16Float="r16float",a.RG8Unorm="rg8unorm",a.RG8Snorm="rg8snorm",a.RG8Uint="rg8uint",a.RG8Sint="rg8sint",a.R32Uint="r32uint",a.R32Sint="r32sint",a.R32Float="r32float",a.RG16Uint="rg16uint",a.RG16Sint="rg16sint",a.RG16Float="rg16float",a.RGBA8Unorm="rgba8unorm",a.RGBA8UnormSRGB="rgba8unorm-srgb",a.RGBA8Snorm="rgba8snorm",a.RGBA8Uint="rgba8uint",a.RGBA8Sint="rgba8sint",a.BGRA8Unorm="bgra8unorm",a.BGRA8UnormSRGB="bgra8unorm-srgb",a.RGB9E5UFloat="rgb9e5ufloat",a.RGB10A2UINT="rgb10a2uint",a.RGB10A2Unorm="rgb10a2unorm",a.RG11B10UFloat="rg11b10ufloat",a.RG32Uint="rg32uint",a.RG32Sint="rg32sint",a.RG32Float="rg32float",a.RGBA16Uint="rgba16uint",a.RGBA16Sint="rgba16sint",a.RGBA16Float="rgba16float",a.RGBA32Uint="rgba32uint",a.RGBA32Sint="rgba32sint",a.RGBA32Float="rgba32float",a.Stencil8="stencil8",a.Depth16Unorm="depth16unorm",a.Depth24Plus="depth24plus",a.Depth24PlusStencil8="depth24plus-stencil8",a.Depth32Float="depth32float",a.BC1RGBAUnorm="bc1-rgba-unorm",a.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",a.BC2RGBAUnorm="bc2-rgba-unorm",a.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",a.BC3RGBAUnorm="bc3-rgba-unorm",a.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",a.BC4RUnorm="bc4-r-unorm",a.BC4RSnorm="bc4-r-snorm",a.BC5RGUnorm="bc5-rg-unorm",a.BC5RGSnorm="bc5-rg-snorm",a.BC6HRGBUFloat="bc6h-rgb-ufloat",a.BC6HRGBFloat="bc6h-rgb-float",a.BC7RGBAUnorm="bc7-rgba-unorm",a.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",a.ETC2RGB8Unorm="etc2-rgb8unorm",a.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",a.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",a.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",a.ETC2RGBA8Unorm="etc2-rgba8unorm",a.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",a.EACR11Unorm="eac-r11unorm",a.EACR11Snorm="eac-r11snorm",a.EACRG11Unorm="eac-rg11unorm",a.EACRG11Snorm="eac-rg11snorm",a.ASTC4x4Unorm="astc-4x4-unorm",a.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",a.ASTC5x4Unorm="astc-5x4-unorm",a.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",a.ASTC5x5Unorm="astc-5x5-unorm",a.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",a.ASTC6x5Unorm="astc-6x5-unorm",a.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",a.ASTC6x6Unorm="astc-6x6-unorm",a.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",a.ASTC8x5Unorm="astc-8x5-unorm",a.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",a.ASTC8x6Unorm="astc-8x6-unorm",a.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",a.ASTC8x8Unorm="astc-8x8-unorm",a.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",a.ASTC10x5Unorm="astc-10x5-unorm",a.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",a.ASTC10x6Unorm="astc-10x6-unorm",a.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",a.ASTC10x8Unorm="astc-10x8-unorm",a.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",a.ASTC10x10Unorm="astc-10x10-unorm",a.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",a.ASTC12x10Unorm="astc-12x10-unorm",a.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",a.ASTC12x12Unorm="astc-12x12-unorm",a.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",a.Depth32FloatStencil8="depth32float-stencil8"})(p0||(p0={}));var _0;(function(a){a.ClampToEdge="clamp-to-edge",a.Repeat="repeat",a.MirrorRepeat="mirror-repeat"})(_0||(_0={}));var g0;(function(a){a.Nearest="nearest",a.Linear="linear"})(g0||(g0={}));var m0;(function(a){a.Nearest="nearest",a.Linear="linear"})(m0||(m0={}));var v0;(function(a){a.Never="never",a.Less="less",a.Equal="equal",a.LessEqual="less-equal",a.Greater="greater",a.NotEqual="not-equal",a.GreaterEqual="greater-equal",a.Always="always"})(v0||(v0={}));var x0;(function(a){a[a.Vertex=1]="Vertex",a[a.Fragment=2]="Fragment",a[a.Compute=4]="Compute"})(x0||(x0={}));var b0;(function(a){a.Uniform="uniform",a.Storage="storage",a.ReadOnlyStorage="read-only-storage"})(b0||(b0={}));var y0;(function(a){a.Filtering="filtering",a.NonFiltering="non-filtering",a.Comparison="comparison"})(y0||(y0={}));var T0;(function(a){a.Float="float",a.UnfilterableFloat="unfilterable-float",a.Depth="depth",a.Sint="sint",a.Uint="uint"})(T0||(T0={}));var S0;(function(a){a.WriteOnly="write-only",a.ReadOnly="read-only",a.ReadWrite="read-write"})(S0||(S0={}));var E0;(function(a){a.Error="error",a.Warning="warning",a.Info="info"})(E0||(E0={}));var I0;(function(a){a.Validation="validation",a.Internal="internal"})(I0||(I0={}));var A0;(function(a){a.Auto="auto"})(A0||(A0={}));var C0;(function(a){a.PointList="point-list",a.LineList="line-list",a.LineStrip="line-strip",a.TriangleList="triangle-list",a.TriangleStrip="triangle-strip"})(C0||(C0={}));var M0;(function(a){a.CCW="ccw",a.CW="cw"})(M0||(M0={}));var R0;(function(a){a.None="none",a.Front="front",a.Back="back"})(R0||(R0={}));var P0;(function(a){a[a.Red=1]="Red",a[a.Green=2]="Green",a[a.Blue=4]="Blue",a[a.Alpha=8]="Alpha",a[a.All=15]="All"})(P0||(P0={}));var w0;(function(a){a.Zero="zero",a.One="one",a.Src="src",a.OneMinusSrc="one-minus-src",a.SrcAlpha="src-alpha",a.OneMinusSrcAlpha="one-minus-src-alpha",a.Dst="dst",a.OneMinusDst="one-minus-dst",a.DstAlpha="dst-alpha",a.OneMinusDstAlpha="one-minus-dst-alpha",a.SrcAlphaSaturated="src-alpha-saturated",a.Constant="constant",a.OneMinusConstant="one-minus-constant"})(w0||(w0={}));var D0;(function(a){a.Add="add",a.Subtract="subtract",a.ReverseSubtract="reverse-subtract",a.Min="min",a.Max="max"})(D0||(D0={}));var F0;(function(a){a.Keep="keep",a.Zero="zero",a.Replace="replace",a.Invert="invert",a.IncrementClamp="increment-clamp",a.DecrementClamp="decrement-clamp",a.IncrementWrap="increment-wrap",a.DecrementWrap="decrement-wrap"})(F0||(F0={}));var O0;(function(a){a.Uint16="uint16",a.Uint32="uint32"})(O0||(O0={}));var L0;(function(a){a.Uint8x2="uint8x2",a.Uint8x4="uint8x4",a.Sint8x2="sint8x2",a.Sint8x4="sint8x4",a.Unorm8x2="unorm8x2",a.Unorm8x4="unorm8x4",a.Snorm8x2="snorm8x2",a.Snorm8x4="snorm8x4",a.Uint16x2="uint16x2",a.Uint16x4="uint16x4",a.Sint16x2="sint16x2",a.Sint16x4="sint16x4",a.Unorm16x2="unorm16x2",a.Unorm16x4="unorm16x4",a.Snorm16x2="snorm16x2",a.Snorm16x4="snorm16x4",a.Float16x2="float16x2",a.Float16x4="float16x4",a.Float32="float32",a.Float32x2="float32x2",a.Float32x3="float32x3",a.Float32x4="float32x4",a.Uint32="uint32",a.Uint32x2="uint32x2",a.Uint32x3="uint32x3",a.Uint32x4="uint32x4",a.Sint32="sint32",a.Sint32x2="sint32x2",a.Sint32x3="sint32x3",a.Sint32x4="sint32x4",a.UNORM10x10x10x2="unorm10-10-10-2"})(L0||(L0={}));var B0;(function(a){a.Vertex="vertex",a.Instance="instance"})(B0||(B0={}));var N0;(function(a){a.Beginning="beginning",a.End="end"})(N0||(N0={}));var U0;(function(a){a.Beginning="beginning",a.End="end"})(U0||(U0={}));var k0;(function(a){a.Load="load",a.Clear="clear"})(k0||(k0={}));var V0;(function(a){a.Store="store",a.Discard="discard"})(V0||(V0={}));var G0;(function(a){a.Occlusion="occlusion",a.Timestamp="timestamp"})(G0||(G0={}));var z0;(function(a){a.Opaque="opaque",a.Premultiplied="premultiplied"})(z0||(z0={}));var W0;(function(a){a.Unknown="unknown",a.Destroyed="destroyed"})(W0||(W0={}));var X0;(function(a){a.Validation="validation",a.OutOfMemory="out-of-memory",a.Internal="internal"})(X0||(X0={}));class Js{get isDisposed(){return this._isDisposed}constructor(e,t,i,s=0,n=!1,r=!1,o=!1,l,h){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=r,this._divisor=l||1,this._label=h,t instanceof on?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=o?s:s*Float32Array.BYTES_PER_ELEMENT,n||this.create()}createVertexBuffer(e,t,i,s,n,r=!1,o){const l=r?t:t*Float32Array.BYTES_PER_ELEMENT,h=s?r?s:s*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new E(this._engine,this,e,this._updatable,!0,h,n===void 0?this._instanced:n,l,i,void 0,void 0,!0,this._divisor||o)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data,e&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label)))}_rebuild(){if(this._data)this._buffer=null,this.create(this._data);else{if(!this._buffer)return;if(this._buffer.capacity>0){this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label);return}U.Warn('Missing data for buffer "'.concat(this._label,'" ').concat(this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":"",". Buffer reconstruction failed.")),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,s=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,s?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),t===0&&i===void 0?this._data=e:this._data=null)}_increaseReferences(){if(this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class E{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=e!=0;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,s,n,r,o,l,h,c,u=!1,f=!1,d=1,p=!1){var m,x,I,T,y;this._isDisposed=!1;let g=!1;if(this.engine=e,typeof s=="object"&&s!==null?(g=(m=s.updatable)!=null?m:!1,n=s.postponeInternalCreation,r=s.stride,o=s.instanced,l=s.offset,h=s.size,c=s.type,u=(x=s.normalized)!=null?x:!1,f=(I=s.useBytes)!=null?I:!1,d=(T=s.divisor)!=null?T:1,p=(y=s.takeBufferOwnership)!=null?y:!1,this._label=s.label):g=!!s,t instanceof Js?(this._buffer=t,this._ownsBuffer=p):(this._buffer=new Js(e,t,g,r,n,o,f,d,this._label),this._ownsBuffer=!0),this.uniqueId=E._Counter++,this._kind=i,c===void 0){const b=this.getData();this.type=b?E.GetDataType(b):E.FLOAT}else this.type=c;const _=E.GetTypeByteLength(this.type);f?(this._size=h||(r?r/_:E.DeduceStride(i)),this.byteStride=r||this._buffer.byteStride||this._size*_,this.byteOffset=l||0):(this._size=h||r||E.DeduceStride(i),this.byteStride=r?r*_:this._buffer.byteStride||this._size*_,this.byteOffset=(l||0)*_),this.normalized=u,this._instanced=o!==void 0?o:!1,this._instanceDivisor=o?d:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){var e;(e=this._buffer)==null||e._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?E.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/E.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/E.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*E.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){E.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case E.UVKind:case E.UV2Kind:case E.UV3Kind:case E.UV4Kind:case E.UV5Kind:case E.UV6Kind:return 2;case E.NormalKind:case E.PositionKind:return 3;case E.ColorKind:case E.ColorInstanceKind:case E.MatricesIndicesKind:case E.MatricesIndicesExtraKind:case E.MatricesWeightsKind:case E.MatricesWeightsExtraKind:case E.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?E.BYTE:e instanceof Uint8Array?E.UNSIGNED_BYTE:e instanceof Int16Array?E.SHORT:e instanceof Uint16Array?E.UNSIGNED_SHORT:e instanceof Int32Array?E.INT:e instanceof Uint32Array?E.UNSIGNED_INT:E.FLOAT}static GetTypeByteLength(e){switch(e){case E.BYTE:case E.UNSIGNED_BYTE:return 1;case E.SHORT:case E.UNSIGNED_SHORT:return 2;case E.INT:case E.UNSIGNED_INT:case E.FLOAT:return 4;default:throw new Error("Invalid type '".concat(e,"'"))}}static ForEach(e,t,i,s,n,r,o,l){if(e instanceof Array){let h=t/4;const c=i/4;for(let u=0;uu[d]=f),u}if(!(e instanceof Array||e instanceof Float32Array)||s!==0||e.length!==c)if(e instanceof Array){const u=s/4;return e.slice(u,u+c)}else{if(e instanceof ArrayBuffer)return new Float32Array(e,s,c);{let u=e.byteOffset+s;if(l){const d=new Float32Array(c),p=new Float32Array(e.buffer,u,c);return d.set(p),d}const f=u%4;return f&&(u=Math.max(0,u-f)),new Float32Array(e.buffer,u,c)}}return l?e.slice():e}}E._Counter=0;E.BYTE=5120;E.UNSIGNED_BYTE=5121;E.SHORT=5122;E.UNSIGNED_SHORT=5123;E.INT=5124;E.UNSIGNED_INT=5125;E.FLOAT=5126;E.PositionKind="position";E.NormalKind="normal";E.TangentKind="tangent";E.UVKind="uv";E.UV2Kind="uv2";E.UV3Kind="uv3";E.UV4Kind="uv4";E.UV5Kind="uv5";E.UV6Kind="uv6";E.ColorKind="color";E.ColorInstanceKind="instanceColor";E.MatricesIndicesKind="matricesIndices";E.MatricesWeightsKind="matricesWeights";E.MatricesIndicesExtraKind="matricesIndicesExtra";E.MatricesWeightsExtraKind="matricesWeightsExtra";const H0=(a,e,t)=>!a||a.getClassName&&a.getClassName()==="Mesh"?null:a.getClassName&&(a.getClassName()==="SubMesh"||a.getClassName()==="PhysicsBody")?a.clone(e):a.clone?a.clone():Array.isArray(a)?a.slice():t&&typeof a=="object"?{...a}:null;function Yf(a){const e=[];do Object.getOwnPropertyNames(a).forEach(function(t){e.indexOf(t)===-1&&e.push(t)});while(a=Object.getPrototypeOf(a));return e}class Ya{static DeepCopy(e,t,i,s,n=!1){const r=Yf(e);for(const o of r){if(o[0]==="_"&&(!s||s.indexOf(o)===-1)||o.endsWith("Observable")||i&&i.indexOf(o)!==-1)continue;const l=e[o],h=typeof l;if(h!=="function")try{if(h==="object")if(l instanceof Uint8Array)t[o]=Uint8Array.from(l);else if(l instanceof Array){if(t[o]=[],l.length>0)if(typeof l[0]=="object")for(let c=0;c0||Ft.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in Ft.CustomRequestHeaders){const t=Ft.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return Ft.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){Ft.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const i of Ft.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;i(this._xhr,t)}t=t.replace("file:http:","http:"),t=t.replace("file:https:","https:"),this._requestURL=t,this._xhr.open(e,t,!0)}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}Ft.CustomRequestHeaders={};Ft.CustomRequestModifiers=new Array;Ft.SkipRequestModificationForBabylonCDN=!0;class bn{}bn.FilesToLoad={};class $f{static ExponentialBackoff(e=3,t=500){return(i,s,n)=>s.status!==0||n>=e||i.indexOf("file:")!==-1?-1:Math.pow(2,n)*t}}class en extends Error{}en._setPrototypeOf=Object.setPrototypeOf||((a,e)=>(a.__proto__=e,a));const Ps={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class is extends en{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",en._setPrototypeOf(this,is.prototype)}}const Mh=a=>{const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",i,s,n,r,o,l,h,c=0;const u=ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);for(;c>2,o=(i&3)<<4|s>>4,l=(s&15)<<2|n>>6,h=n&63,isNaN(s)?l=h=64:isNaN(n)&&(h=64),t+=e.charAt(r)+e.charAt(o)+e.charAt(l)+e.charAt(h);return t},Rh=a=>atob(a),jf=a=>{const e=Rh(a),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let s=0;s(a=a.replace(/#/gm,"%23"),a),ct={DefaultRetryStrategy:$f.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:a=>a,ScriptBaseUrl:"",ScriptPreprocessUrl:a=>a,CleanUrl:Zf},$a=(a,e)=>{if(!(a&&a.indexOf("data:")===0)&&ct.CorsBehavior)if(typeof ct.CorsBehavior=="string"||ct.CorsBehavior instanceof String)e.crossOrigin=ct.CorsBehavior;else{const t=ct.CorsBehavior(a);t&&(e.crossOrigin=t)}},ja=(a,e,t,i,s="",n)=>{const r=Ce.LastCreatedEngine;if(typeof HTMLImageElement>"u"&&!(r!=null&&r._features.forceBitmapOverHTMLImageElement))return t("LoadImage is only supported in web or BabylonNative environments."),null;let o,l=!1;a instanceof ArrayBuffer||ArrayBuffer.isView(a)?typeof Blob<"u"&&typeof URL<"u"?(o=URL.createObjectURL(new Blob([a],{type:s})),l=!0):o="data:".concat(s,";base64,")+Mh(a):a instanceof Blob?(o=URL.createObjectURL(a),l=!0):(o=ct.CleanUrl(a),o=ct.PreprocessUrl(a));const h=y=>{if(t){const b=o||a.toString();t("Error while trying to load image: ".concat(b.indexOf("http")===0||b.length<=128?b:b.slice(0,128)+"..."),y)}};if(r!=null&&r._features.forceBitmapOverHTMLImageElement)return vs(o,y=>{r.createImageBitmap(new Blob([y],{type:s}),{premultiplyAlpha:"none",...n}).then(b=>{e(b),l&&URL.revokeObjectURL(o)}).catch(b=>{t&&t("Error while trying to load image: "+a,b)})},void 0,i||void 0,!0,(y,b)=>{h(b)}),null;const c=new Image;$a(o,c);const u=[],f=()=>{u.forEach(y=>{y.target.addEventListener(y.name,y.handler)})},d=()=>{u.forEach(y=>{y.target.removeEventListener(y.name,y.handler)}),u.length=0},p=()=>{d(),e(c),l&&c.src&&URL.revokeObjectURL(c.src)},g=y=>{d(),h(y),l&&c.src&&URL.revokeObjectURL(c.src)},_=y=>{if(y.blockedURI!==c.src)return;d();const b=new Error("CSP violation of policy ".concat(y.effectiveDirective," ").concat(y.blockedURI,". Current policy is ").concat(y.originalPolicy));Ce.UseFallbackTexture=!1,h(b),l&&c.src&&URL.revokeObjectURL(c.src),c.src=""};u.push({target:c,name:"load",handler:p}),u.push({target:c,name:"error",handler:g}),u.push({target:document,name:"securitypolicyviolation",handler:_}),f();const m=o.substring(0,5)==="blob:",x=o.substring(0,5)==="data:",I=()=>{m||x||!Ft.IsCustomRequestAvailable?c.src=o:vs(o,(y,b,S)=>{const A=!s&&S?S:s,M=new Blob([y],{type:A}),C=URL.createObjectURL(M);l=!0,c.src=C},void 0,i||void 0,!0,(y,b)=>{h(b)})},T=()=>{i&&i.loadImage(o,c)};if(!m&&!x&&i&&i.enableTexturesOffline)i.open(T,I);else{if(o.indexOf("file:")!==-1){const y=decodeURIComponent(o.substring(5).toLowerCase());if(bn.FilesToLoad[y]&&typeof URL<"u"){try{let b;try{b=URL.createObjectURL(bn.FilesToLoad[y])}catch{b=URL.createObjectURL(bn.FilesToLoad[y])}c.src=b,l=!0}catch{c.src=""}return c}}I()}return c},An=(a,e,t,i,s)=>{const n=new FileReader,r={onCompleteObservable:new Q,abort:()=>n.abort()};return n.onloadend=()=>r.onCompleteObservable.notifyObservers(r),s&&(n.onerror=()=>{s(new qa("Unable to read ".concat(a.name),a))}),n.onload=o=>{e(o.target.result)},t&&(n.onprogress=t),i?n.readAsArrayBuffer(a):n.readAsText(a),r},vs=(a,e,t,i,s,n,r)=>{if(a.name)return An(a,e,t,s,n?c=>{n(void 0,c)}:void 0);const o=a;if(o.indexOf("file:")!==-1){let c=decodeURIComponent(o.substring(5).toLowerCase());c.indexOf("./")===0&&(c=c.substring(2));const u=bn.FilesToLoad[c];if(u)return An(u,e,t,s,n?f=>n(void 0,new cr(f.message,f.file)):void 0)}const{match:l,type:h}=Qf(o);if(l){const c={onCompleteObservable:new Q,abort:()=>()=>{}};try{const u=s?Ja(o):Dh(o);e(u,void 0,h)}catch(u){n?n(void 0,u):U.Error(u.message||"Failed to parse the Data URL")}return hr.SetImmediate(()=>{c.onCompleteObservable.notifyObservers(c)}),c}return Za(o,(c,u)=>{e(c,u==null?void 0:u.responseURL,u==null?void 0:u.getResponseHeader("content-type"))},t,i,s,n?c=>{n(c.request,new cr(c.message,c.request))}:void 0,r)},Za=(a,e,t,i,s,n,r)=>{a=ct.CleanUrl(a),a=ct.PreprocessUrl(a);const o=ct.BaseUrl+a;let l=!1;const h={onCompleteObservable:new Q,abort:()=>l=!0},c=()=>{let u=new Ft,f=null,d;const p=()=>{u&&(t&&u.removeEventListener("progress",t),d&&u.removeEventListener("readystatechange",d),u.removeEventListener("loadend",g))};let g=()=>{p(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),t=void 0,d=null,g=null,n=void 0,r=void 0,e=void 0};h.abort=()=>{l=!0,g&&g(),u&&u.readyState!==(XMLHttpRequest.DONE||4)&&u.abort(),f!==null&&(clearTimeout(f),f=null),u=null};const _=x=>{const I=x.message||"Unknown error";n&&u?n(new ur(I,u)):U.Error(I)},m=x=>{if(u){if(u.open("GET",o),r)try{r(u)}catch(I){_(I);return}s&&(u.responseType="arraybuffer"),t&&u.addEventListener("progress",t),g&&u.addEventListener("loadend",g),d=()=>{if(!(l||!u)&&u.readyState===(XMLHttpRequest.DONE||4)){if(d&&u.removeEventListener("readystatechange",d),u.status>=200&&u.status<300||u.status===0&&(!St()||wh())){try{e&&e(s?u.response:u.responseText,u)}catch(y){_(y)}return}const I=ct.DefaultRetryStrategy;if(I){const y=I(o,u,x);if(y!==-1){p(),u=new Ft,f=setTimeout(()=>m(x+1),y);return}}const T=new ur("Error status: "+u.status+" "+u.statusText+" - Unable to load "+o,u);n&&n(T)}},u.addEventListener("readystatechange",d),u.send()}};m(0)};if(i&&i.enableSceneOffline){const u=d=>{d&&d.status>400?n&&n(d):c()},f=()=>{i&&i.loadFile(ct.BaseUrl+a,d=>{!l&&e&&e(d),h.onCompleteObservable.notifyObservers(h)},t?d=>{!l&&t&&t(d)}:void 0,u,s)};i.open(f,u)}else c();return h},wh=()=>typeof location<"u"&&location.protocol==="file:",Qa=a=>Ph.test(a),Qf=a=>{const e=Ph.exec(a);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace("base64,","")}};function Ja(a){return jf(a.split(",")[1])}const Dh=a=>Rh(a.split(",")[1]),Jf=()=>{me._FileToolsLoadImage=ja,or.loadFile=vs,ch.loadFile=vs};Jf();let fn;const ed=(a,e,t,i,s,n,r,o,l,h)=>{fn={DecodeBase64UrlToBinary:a,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:s,LoadFile:n,LoadImage:r,ReadFile:o,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(fn,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(c){t.DefaultRetryStrategy=c}}),Object.defineProperty(fn,"BaseUrl",{get:function(){return t.BaseUrl},set:function(c){t.BaseUrl=c}}),Object.defineProperty(fn,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(c){t.PreprocessUrl=c}}),Object.defineProperty(fn,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(c){t.CorsBehavior=c}})};ed(Ja,Dh,ct,Qa,wh,vs,ja,An,Za,$a);class yn{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=ms(e);if(t)return t;U.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let n=0,r=i.length;n{const e=Math.random()*16|0;return(a==="x"?e:e&3|8).toString(16)})}class ee{static get BaseUrl(){return ct.BaseUrl}static set BaseUrl(e){ct.BaseUrl=e}static get CleanUrl(){return ct.CleanUrl}static set CleanUrl(e){ct.CleanUrl=e}static IsAbsoluteUrl(e){return e.indexOf("//")===0?!0:e.indexOf("://")===-1||e.indexOf(".")===-1||e.indexOf("/")===-1||e.indexOf(":")>e.indexOf("/")?!1:e.indexOf("://"){vs(e,n=>{i(n)},void 0,void 0,t,(n,r)=>{s(r)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(ee.ScriptBaseUrl&&e.startsWith(ee._DefaultCdnUrl)){const i=ee.ScriptBaseUrl[ee.ScriptBaseUrl.length-1]==="/"?ee.ScriptBaseUrl.substring(0,ee.ScriptBaseUrl.length-1):ee.ScriptBaseUrl;e=e.replace(ee._DefaultCdnUrl,i)}return e=ee.ScriptPreprocessUrl(e),t&&(e=ee.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=ee.GetBabylonScriptURL(e),ee.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=ee.GetBabylonScriptURL(e),ee.LoadScriptAsync(e)}static LoadScript(e,t,i,s){if(typeof importScripts=="function"){try{importScripts(e),t()}catch(o){i==null||i("Unable to load script '".concat(e,"' in worker"),o)}return}else if(!St()){i==null||i("Cannot load script '".concat(e,"' outside of a window or a worker"));return}const n=document.getElementsByTagName("head")[0],r=document.createElement("script");r.setAttribute("type","text/javascript"),r.setAttribute("src",e),s&&(r.id=s),r.onload=()=>{t&&t()},r.onerror=o=>{i&&i("Unable to load script '".concat(e,"'"),o)},n.appendChild(r)}static LoadScriptAsync(e,t){return new Promise((i,s)=>{this.LoadScript(e,()=>{i()},(n,r)=>{s(r||new Error(n))},t)})}static ReadFileAsDataURL(e,t,i){const s=new FileReader,n={onCompleteObservable:new Q,abort:()=>s.abort()};return s.onloadend=()=>{n.onCompleteObservable.notifyObservers(n)},s.onload=r=>{t(r.target.result)},s.onprogress=i,s.readAsDataURL(e),n}static ReadFile(e,t,i,s,n){return An(e,t,i,s,n)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,s){Ya.DeepCopy(e,t,i,s)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{const l=atob(this.toDataURL(r,o).split(",")[1]),h=l.length,c=new Uint8Array(h);for(let u=0;ut(n)):e.toBlob(function(n){t(n)},i,s)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const i=new Date;t="screenshot_"+((i.getFullYear()+"-"+(i.getMonth()+1)).slice(2)+"-"+i.getDate()+"_"+i.getHours()+"-"+("0"+i.getMinutes()).slice(-2))+".png"}ee.Download(e,t)}else if(e&&typeof URL<"u"){const i=URL.createObjectURL(e),s=window.open("");if(!s)return;const n=s.document.createElement("img");n.onload=function(){URL.revokeObjectURL(i)},n.src=i,s.document.body.appendChild(n)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,n){if(typeof s=="string"||!t)this.ToBlob(e,function(r){r&&ee.DownloadBlob(r,s),t&&t("")},i,n);else if(t){if(ee._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:n}).then(o=>{const l=new FileReader;l.readAsDataURL(o),l.onloadend=()=>{const h=l.result;t(h)}});return}const r=e.toDataURL(i,n);t(r)}}static Download(e,t){if(typeof URL>"u")return;const i=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.style.display="none",s.href=i,s.download=t,s.addEventListener("click",()=>{s.parentElement&&s.parentElement.removeChild(s)}),s.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return typeof e[0]=="boolean"?e[0]:typeof e[1]=="boolean"?e[1]:!1}static CreateScreenshot(e,t,i,s,n="image/png",r=!1,o){throw Te("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",n){throw Te("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,n="image/png",r=1,o=!1,l,h=!1,c=!1,u=!0,f){throw Te("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",n=1,r=!1,o,l=!1,h=!1,c=!0,u){throw Te("ScreenshotTools")}static RandomId(){return eo()}static IsBase64(e){return Qa(e)}static DecodeBase64(e){return Ja(e)}static get errorsCount(){return U.errorsCount}static Log(e){U.Log(e)}static Warn(e){U.Warn(e)}static Error(e){U.Error(e)}static get LogCache(){return U.LogCache}static ClearLogCache(){U.ClearLogCache()}static set LogLevels(e){U.LogLevels=e}static set PerformanceLogLevel(e){if((e&ee.PerformanceUserMarkLogLevel)===ee.PerformanceUserMarkLogLevel){ee.StartPerformanceCounter=ee._StartUserMark,ee.EndPerformanceCounter=ee._EndUserMark;return}if((e&ee.PerformanceConsoleLogLevel)===ee.PerformanceConsoleLogLevel){ee.StartPerformanceCounter=ee._StartPerformanceConsole,ee.EndPerformanceCounter=ee._EndPerformanceConsole;return}ee.StartPerformanceCounter=ee._StartPerformanceCounterDisabled,ee.EndPerformanceCounter=ee._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!ee._Performance){if(!St())return;ee._Performance=window.performance}!t||!ee._Performance.mark||ee._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!ee._Performance.mark||(ee._Performance.mark(e+"-End"),ee._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(ee._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(ee._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return xi.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,s=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const n=t?e:Object.getPrototypeOf(e);i=n.constructor.__bjsclassName__,s=n.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(s!=null?s+".":"")+i:null}static DelayAsync(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return Xs()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}}ee.UseCustomRequestHeaders=!1;ee.CustomRequestHeaders=Ft.CustomRequestHeaders;ee.GetDOMTextContent=Ga;ee._DefaultCdnUrl="https://cdn.babylonjs.com";ee.GetAbsoluteUrl=typeof document=="object"?a=>{const e=document.createElement("a");return e.href=a,e.href}:typeof URL=="function"&&typeof location=="object"?a=>new URL(a,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")};ee.NoneLogLevel=U.NoneLogLevel;ee.MessageLogLevel=U.MessageLogLevel;ee.WarningLogLevel=U.WarningLogLevel;ee.ErrorLogLevel=U.ErrorLogLevel;ee.AllLogLevel=U.AllLogLevel;ee.IsWindowObjectExist=St;ee.PerformanceNoneLogLevel=0;ee.PerformanceUserMarkLogLevel=1;ee.PerformanceConsoleLogLevel=2;ee.StartPerformanceCounter=ee._StartPerformanceCounterDisabled;ee.EndPerformanceCounter=ee._EndPerformanceCounterDisabled;class fr{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{n&&n()?o.breakLoop():setTimeout(()=>{for(let l=0;l=e)break;if(i(h),n&&n()){o.breakLoop();break}}o.executeNext()},r)},s)}}ee.Mix=da;ee.IsExponentOfTwo=gf;Ce.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";Fe.prototype.createUniformBuffer=function(a,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");const i=new Sn(t);return this.bindUniformBuffer(i),a instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,a,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(a),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};Fe.prototype.createDynamicUniformBuffer=function(a,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");const i=new Sn(t);return this.bindUniformBuffer(i),a instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,a,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(a),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};Fe.prototype.updateUniformBuffer=function(a,e,t,i){this.bindUniformBuffer(a),t===void 0&&(t=0),i===void 0?e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,e):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,new Float32Array(e)):e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,e.subarray(t,t+i)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(e).subarray(t,t+i)),this.bindUniformBuffer(null)};Fe.prototype.bindUniformBuffer=function(a){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,a?a.underlyingResource:null)};Fe.prototype.bindUniformBufferBase=function(a,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,a?a.underlyingResource:null)};Fe.prototype.bindUniformBlock=function(a,e,t){const i=a.program,s=this._gl.getUniformBlockIndex(i,e);s!==4294967295&&this._gl.uniformBlockBinding(i,s,t)};class de{constructor(e,t,i,s,n=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||n,this._dynamic=i,this._name=s!=null?s:"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return this._dynamic!==void 0}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(e<=2?t=e:t=4,this._uniformLocationPointer%t!==0){const i=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const s=this._uniformLocationPointer-i;for(let n=0;n0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},t==16)t=t*i;else{const r=(4-t)*i;t=t*i+r}s=[];for(let n=0;n1&&this._buffers[this._bufferIndex][1])if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}else this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1]);this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(de._UpdatedUbosInFrame[this._name]||(de._UpdatedUbosInFrame[this._name]=0),de._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}}_createNewBuffer(){this._bufferIndex+10?(this._needSync=this._bufferIndex!==0,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let s=this._uniformLocations[e];if(s===void 0){if(this._buffer){U.Error("Cannot add an uniform after UBO has been created. uniformName="+e);return}this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let n=0;n=0&&(f.push(o[u]),d.push(p))}this.shaderProcessingContext.attributeNamesFromEffect=f,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new de(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=bt.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}setEngine(e){this.engine=e}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt3(e,t,i,s)}setInt4(e,t,i,s,n){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt4(e,t,i,s,n)}setIntArray(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt3(e,t,i,s)}setUInt4(e,t,i,s,n){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt4(e,t,i,s,n)}setUIntArray(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat3(e,t,i,s)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,s,n){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat4(e,t,i,s,n)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){var e;return(e=this.sources)==null?void 0:e.vertex}_getFragmentShaderCode(){var e;return(e=this.sources)==null?void 0:e.fragment}}const id=4,sd=65536,K0={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class ii{static get KnownUBOs(){return ii._SimplifiedKnownBindings?ii._SimplifiedKnownUBOs:ii._KnownUBOs}constructor(e){this.vertexBufferKindToNumberOfComponents={},this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=ii.KnownUBOs,t=[];for(const i in e){const s=e[i].binding;s.groupIndex!==-1&&(t[s.groupIndex]===void 0?t[s.groupIndex]=s.bindingIndex:t[s.groupIndex]=Math.max(t[s.groupIndex],s.bindingIndex))}this.freeGroupIndex=t.length-1,this.freeGroupIndex===0?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){var s;const i=this._attributeNextLocation;return this._attributeNextLocation+=((s=K0[e])!=null?s:1)*(t||1),i}getVaryingNextLocation(e,t=0){var s;const i=this._varyingNextLocation;return this._varyingNextLocation+=((s=K0[e])!=null?s:1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>sd-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),this.freeGroupIndex===id)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";const t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}ii._SimplifiedKnownBindings=!0;ii._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}};ii._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};function qn(a,e,t,i){let s=i,n=0,r="";for(;s=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e==95}function ga(a){let e=0,t="",i=!1;const s=[];for(;e=0&&a.charAt(e)!==t&&(!i||a.charAt(e)!==i);)e--;return e}function rd(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ma(a,e,t,i){let s=a.indexOf(e);if(s<0)return a;if(t){for(;s++0&&r>0){const o=e.substring(n+1,r);s=+o,isNaN(s)&&(s=+i[o.trim()]),e=e.substr(0,n)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const i="// Internals UBO\nuniform ".concat(bt.InternalsUBOName," {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n"),s=e.indexOf("// Internals UBO")!==-1;return t?(this._fragmentIsGLES3=e.indexOf("#version 3")!==-1,this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),s?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=e.indexOf("#version 3")!==-1,this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),s?e:i+e)}varyingCheck(e,t){const i=/(flat\s)?\s*\bout\b/,s=/(flat\s)?\s*\bin\b/,n=/(flat\s)?\s*\bvarying\b/;return(t&&this._fragmentIsGLES3?s:!t&&this._vertexIsGLES3?i:n).test(e)}varyingProcessor(e,t,i){var h;this._preProcessors=i;const s=/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,n=/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,r=/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,l=(t&&this._fragmentIsGLES3?n:!t&&this._vertexIsGLES3?s:r).exec(e);if(l!==null){const c=(h=l[1])!=null?h:"",u=l[2],f=l[3];let d;t?(d=this._webgpuProcessingContext.availableVaryings[f],this._missingVaryings[d]="",d===void 0&&U.Warn('Invalid fragment shader: The varying named "'.concat(f,'" is not declared in the vertex shader! This declaration will be ignored.'))):(d=this._webgpuProcessingContext.getVaryingNextLocation(u,this._getArraySize(f,u,i)[2]),this._webgpuProcessingContext.availableVaryings[f]=d,this._missingVaryings[d]="layout(location = ".concat(d,") ").concat(c," in ").concat(u," ").concat(f,";")),e=e.replace(l[0],d===void 0?"":"layout(location = ".concat(d,") ").concat(c," ").concat(t?"in":"out"," ").concat(u," ").concat(f,";"))}return e}attributeProcessor(e,t){this._preProcessors=t;const i=/\s*in\s+(\S+)\s+(\S+)\s*;/gm,s=/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm,r=(this._vertexIsGLES3?i:s).exec(e);if(r!==null){const o=r[1],l=r[2],h=this._webgpuProcessingContext.getAttributeNextLocation(o,this._getArraySize(l,o,t)[2]);this._webgpuProcessingContext.availableAttributes[l]=h,this._webgpuProcessingContext.orderedAttributes[h]=l;const c=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[l];if(c!==void 0){const u=c<0?c===-1?"int":"ivec"+-c:c===1?"uint":"uvec"+c,f="_int_".concat(l,"_");e=e.replace(r[0],"layout(location = ".concat(h,") in ").concat(u," ").concat(f,"; ").concat(o," ").concat(l," = ").concat(o,"(").concat(f,");"))}else e=e.replace(r[0],"layout(location = ".concat(h,") in ").concat(o," ").concat(l,";"))}return e}uniformProcessor(e,t,i){var r;this._preProcessors=i;const n=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(n!==null){let o=n[1],l=n[2];if(o.indexOf("sampler")===0||o.indexOf("sampler")===1){let h=0;[l,o,h]=this._getArraySize(l,o,i);let c=this._webgpuProcessingContext.availableTextures[l];if(!c){c={autoBindSampler:!0,isTextureArray:h>0,isStorageTexture:!1,textures:[],sampleType:"float"};for(let A=0;A<(h||1);++A)c.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const u=(r=bt._SamplerTypeByWebGLSamplerType[o])!=null?r:"sampler",f=!!bt._IsComparisonSamplerByWebGPUSamplerType[u],d=f?"comparison":"filtering",p=l+"Sampler";let g=this._webgpuProcessingContext.availableSamplers[p];g||(g={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:d});const _=o.charAt(0)==="u"?"u":o.charAt(0)==="i"?"i":"";_&&(o=o.substr(1));const m=f?"depth":_==="u"?"uint":_==="i"?"sint":"float";c.sampleType=m;const x=h>0,I=g.binding.groupIndex,T=g.binding.bindingIndex,y=bt._SamplerFunctionByWebGLSamplerType[o],b=bt._TextureTypeByWebGLSamplerType[o],S=bt._GpuTextureViewDimensionByWebGPUTextureType[b];if(!x)h=1,e="layout(set = ".concat(I,", binding = ").concat(T,") uniform ").concat(u," ").concat(p,";\n layout(set = ").concat(c.textures[0].groupIndex,", binding = ").concat(c.textures[0].bindingIndex,") uniform ").concat(_).concat(b," ").concat(l,"Texture;\n #define ").concat(l," ").concat(_).concat(y,"(").concat(l,"Texture, ").concat(p,")");else{const A=[];A.push("layout(set = ".concat(I,", binding = ").concat(T,") uniform ").concat(_).concat(u," ").concat(p,";")),e="\n";for(let M=0;M0?"\n":"","#define ").concat(l).concat(M," ").concat(_).concat(y,"(").concat(l,"Texture").concat(M,", ").concat(p,")")}e=A.join("\n")+e,this._textureArrayProcessing.push(l)}this._webgpuProcessingContext.availableTextures[l]=c,this._webgpuProcessingContext.availableSamplers[p]=g,this._addSamplerBindingDescription(p,g,!t);for(let A=0;A=0,h="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",c=l?"vec4 glFragCoord_;\n":"",u=e.search(/layout *\(location *= *0\) *out/g)!==-1;if(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/gl_FragCoord/g,"glFragCoord_"),!this._fragmentIsGLES3)e=e.replace(/void\s+?main\s*\(/g,(r||u?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");else{const f=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);f!==null&&(e=e.substring(0,f.index)+"layout(location = 0) "+e.substring(f.index))}e=e.replace(/dFdy/g,"(-yFactor_)*dFdy"),e=e.replace("##INJECTCODE##",c),l&&(e=ma(e,"void main",h))}else if(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex"),e=e.replace(/gl_VertexID/g,"gl_VertexIndex"),t.indexOf("#define MULTIVIEW")!==-1)return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;if(!i){const l=e.lastIndexOf("}");e=e.substring(0,l),e+="gl_Position.y *= yFactor_;\n",e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let s=i.exec(e);for(;s!==null;){const n=s[1];let r=+n;this._preProcessors&&isNaN(r)&&(r=+this._preProcessors[n.trim()]),e=e.replace(s[0],t+r),s=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i="layout(set = ".concat(t.binding.groupIndex,", binding = ").concat(t.binding.bindingIndex,") uniform ").concat(e," {\n ");for(const s of this._webgpuProcessingContext.leftOverUniforms)s.length>0?i+=" ".concat(s.type," ").concat(s.name,"[").concat(s.length,"];\n"):i+=" ".concat(s.type," ").concat(s.name,";\n");return i+="};\n\n",i}finalizeShaders(e,t){for(let s=0;s0&&(t=n+"\n"+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}const od="bonesDeclaration",ld="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4;attribute matricesWeights : vec4;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d;uniform boneTextureWidth : f32;\n#else\nuniform mBones : array;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\n{let offset=i32(index) *4; \nlet m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n#endif\n#endif\n";K.IncludesShadersStoreWGSL[od]=ld;const hd="bonesVertex",cd="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\n#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\n#endif \n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";K.IncludesShadersStoreWGSL[hd]=cd;const ud="bakedVertexAnimationDeclaration",fd="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\n{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n";K.IncludesShadersStoreWGSL[ud]=fd;const dd="bakedVertexAnimation",pd="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;}\n#endif\n";K.IncludesShadersStoreWGSL[dd]=pd;const _d="clipPlaneFragment",gd="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fragmentInputs.fClipDistance>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\n{discard;}\n#endif\n";K.IncludesShadersStoreWGSL[_d]=gd;const md="clipPlaneFragmentDeclaration",vd="#ifdef CLIPPLANE\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nvarying fClipDistance6: f32;\n#endif\n";K.IncludesShadersStoreWGSL[md]=vd;const xd="clipPlaneVertex",bd="#ifdef CLIPPLANE\nvertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nvertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nvertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nvertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nvertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nvertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);\n#endif\n";K.IncludesShadersStoreWGSL[xd]=bd;const yd="clipPlaneVertexDeclaration",Td="#ifdef CLIPPLANE\nuniform vClipPlane: vec4;varying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4;varying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4;varying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4;varying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4;varying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4;varying fClipDistance6: f32;\n#endif\n";K.IncludesShadersStoreWGSL[yd]=Td;const Sd="instancesDeclaration",Ed="#ifdef INSTANCES\nattribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4;\n#endif\n#endif\n";K.IncludesShadersStoreWGSL[Sd]=Ed;const Id="instancesVertex",Ad="#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\n#if !defined(WORLD_UBO)\nfinalWorld=uniforms.world*finalWorld;\n#else\nfinalWorld=mesh.world*finalWorld;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nvar finalWorld=uniforms.world;\n#else\nvar finalWorld=mesh.world;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=previousWorld;\n#endif\n#endif\n";K.IncludesShadersStoreWGSL[Id]=Ad;const Cd="helperFunctions",Md="const PI: f32=3.1415926535897932384626433832795;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const HALF_MIN: f32=5.96046448e-08; \nconst LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3=vec3 (0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\nfn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3=inMatrix[0];let i1: vec3=inMatrix[1];let i2: vec3=inMatrix[2];let outMatrix:mat3x3f=mat3x3f(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nfn inverseMat3(inMatrix: mat3x3f)->mat3x3f {let a00: f32=inMatrix[0][0];let a01: f32=inMatrix[0][1];let a02: f32=inMatrix[0][2];let a10: f32=inMatrix[1][0];let a11: f32=inMatrix[1][1];let a12: f32=inMatrix[1][2];let a20: f32=inMatrix[2][0];let a21: f32=inMatrix[2][1];let a22: f32=inMatrix[2][2];let b01: f32=a22*a11-a12*a21;let b11: f32=-a22*a10+a12*a20;let b21: f32=a21*a10-a11*a20;let det: f32=a00*b01+a01*b11+a02*b21;return mat3x3f(b01/det,(-a22*a01+a02*a21)/det,(a12*a01-a02*a11)/det,\nb11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det,\nb21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);}\n#if USE_EXACT_SRGB_CONVERSIONS\nfn toLinearSpaceExact(color: vec3)->vec3\n{let nearZeroSection: vec3=0.0773993808*color;let remainingSection: vec3=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));}\nfn toGammaSpaceExact(color: vec3)->vec3\n{let nearZeroSection: vec3=12.92*color;let remainingSection: vec3=1.055*pow(color,vec3(0.41666))-vec3(0.055);return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));}\n#endif\nfn toLinearSpace(color: vec4)->vec4\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}\nfn toLinearSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nfn toGammaSpace(color: vec4)->vec4\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}\nfn toGammaSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nfn square(value: vec3)->vec3\n{return value*value;}\nfn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;}\nfn getLuminance(color: vec3)->f32\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfn getRand(seed: vec2)->f32 {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfn dither(seed: vec2,varianceAmount: f32)->f32 {let rand: f32=getRand(seed);let normVariance: f32=varianceAmount/255.0;let dither: f32=mix(-normVariance,normVariance,rand);return dither;}\nconst rgbdMaxRange: f32=255.0;fn toRGBD(color: vec3)->vec4 {let maxRGB: f32=max(max(color.r,max(color.g,color.b)),Epsilon);var D: f32 =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);var rgb: vec3 =color.rgb*D;rgb=toGammaSpaceVec3(rgb);return vec4(clamp(rgb,vec3(0.,0.,0.),vec3(1.,1.,1.)),D); }\nfn fromRGBD(rgbd: vec4)->vec3 {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;}\nfn parallaxCorrectNormal(vertexPos: vec3,origVec: vec3,cubeSize: vec3,cubePos: vec3)->vec3 {let invOrigVec: vec3=vec3(1.0,1.0,1.0)/origVec;let halfSize: vec3=cubeSize*0.5;let intersecAtMaxPlane: vec3=(cubePos+halfSize-vertexPos)*invOrigVec;let intersecAtMinPlane: vec3=(cubePos-halfSize-vertexPos)*invOrigVec;let largestIntersec: vec3=max(intersecAtMaxPlane,intersecAtMinPlane);let distance: f32=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);let intersectPositionWS: vec3=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";K.IncludesShadersStoreWGSL[Cd]=Md;const Rd="fresnelFunction",Pd="#ifdef FRESNEL\nfn computeFresnelTerm(viewDirection: vec3f,worldNormal: vec3f,bias: f32,power: f32)->f32\n{let fresnelTerm: f32=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}\n#endif\n";K.IncludesShadersStoreWGSL[Rd]=Pd;const wd="meshUboDeclaration",Dd="struct Mesh {world : mat4x4,\nvisibility : f32,};var mesh : Mesh;\n#define WORLD_UBO\n";K.IncludesShadersStoreWGSL[wd]=Dd;const Fd="morphTargetsVertex",Od="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (var i=0; i=uniforms.morphTargetCount) {break;}\nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n}\n#endif\n#else\npositionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";K.IncludesShadersStoreWGSL[Fd]=Od;const Ld="morphTargetsVertexDeclaration",Bd="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2;\n#endif\n#elif {X}==0\nuniform morphTargetCount: i32;\n#endif\n#endif\n";K.IncludesShadersStoreWGSL[Ld]=Bd;const Nd="morphTargetsVertexGlobal",Ud="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";K.IncludesShadersStoreWGSL[Nd]=Ud;const kd="morphTargetsVertexGlobalDeclaration",Vd="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3\n{ \nlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;}\n#endif\n#endif\n";K.IncludesShadersStoreWGSL[kd]=Vd;const Gd="sceneUboDeclaration",zd="struct Scene {viewProjection : mat4x4,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\n#endif \nview : mat4x4,\nprojection : mat4x4,\nvEyePosition : vec4,};var scene : Scene;\n";K.IncludesShadersStoreWGSL[Gd]=zd;const Wd="lightsFragmentFunctions",Xd="struct lightingInfo\n{diffuse: vec3f,\n#ifdef SPECULARTERM\nspecular: vec3f,\n#endif\n#ifdef NDOTL\nndl: f32,\n#endif\n};fn computeLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var lightVectorW: vec3f;var attenuation: f32=1.0;if (lightData.w==0.)\n{var direction: vec3f=lightData.xyz-vPositionW;var attenuation: f32=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nvar ndl: f32=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nfn computeSpotLighting(viewDirectionW: vec3f,vNormal: vec3f ,lightData: vec4f,lightDirection: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var direction: vec3f=lightData.xyz-vPositionW;var lightVectorW: vec3f=normalize(direction);var attenuation: f32=max(0.,1.0-length(direction)/range);var cosAngle: f32=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;var ndl: f32=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3f(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3f(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nfn computeHemisphericLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,groundColor: vec3f,glossiness: f32)->lightingInfo {var result: lightingInfo;var ndl: f32=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\nvar angleW: vec3f=normalize(viewDirectionW+lightData.xyz);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\nfn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f)->vec3f {var strq: vec4f=textureProjectionMatrix*vec4f(vPositionW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return textureColor;}";K.IncludesShadersStoreWGSL[Wd]=Xd;const Hd="lightFragment",Kd="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(POINTLIGHT{X})\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(HEMILIGHT{X})\npreInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(DIRLIGHT{X})\npreInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#endif\npreInfo.NdotV=NdotV;\n#ifdef SPOTLIGHT{X}\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\n#elif defined(POINTLIGHT{X})\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\n#else\npreInfo.attenuation=1.0;\n#endif\n#ifdef HEMILIGHT{X}\npreInfo.roughness=roughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#ifdef IRIDESCENCE\npreInfo.iridescenceIntensity=iridescenceIntensity;\n#endif\n#ifdef HEMILIGHT{X}\ninfo.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef SPECULARTERM\n#ifdef ANISOTROPIC\ninfo.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#endif\n#ifdef SHEEN\n#ifdef SHEEN_LINKWITHALBEDO\npreInfo.roughness=sheenOut.sheenIntensity;\n#else\n#ifdef HEMILIGHT{X}\npreInfo.roughness=sheenOut.sheenRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#endif\ninfo.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef CLEARCOAT\n#ifdef HEMILIGHT{X}\npreInfo.roughness=clearcoatOut.clearCoatRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\ninfo.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb);\n#ifdef CLEARCOAT_TINT\nabsorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;\n#ifdef SPECULARTERM\ninfo.specular*=absorption;\n#endif\n#endif\ninfo.diffuse*=info.clearCoat.w;\n#ifdef SPECULARTERM\ninfo.specular*=info.clearCoat.w;\n#endif\n#ifdef SHEEN\ninfo.sheen*=info.clearCoat.w;\n#endif\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},projectionLightTexture{X}Sampler,textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSMDEBUG{X} \nvar shadowDebug{X}: vec3f;\n#endif\n#ifdef SHADOWCSM{X}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nvar index{X}: i32=-1;\n#else\nvar index{X}: i32=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nvar diff{X}: f32=0.;vPositionFromLight{X}[0]=fragmentInputs.vPositionFromLight{X}_0;vPositionFromLight{X}[1]=fragmentInputs.vPositionFromLight{X}_1;vPositionFromLight{X}[2]=fragmentInputs.vPositionFromLight{X}_2;vPositionFromLight{X}[3]=fragmentInputs.vPositionFromLight{X}_3;vDepthMetric{X}[0]=fragmentInputs.vDepthMetric{X}_0;vDepthMetric{X}[1]=fragmentInputs.vDepthMetric{X}_1;vDepthMetric{X}[2]=fragmentInputs.vDepthMetric{X}_2;vDepthMetric{X}[3]=fragmentInputs.vDepthMetric{X}_3;for (var i:i32=0; i=0.) {index{X}=i;break;}}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\n#endif\n{\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#else\nshadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#endif\n#else\nshadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3f(shadow)*vCascadeColorsMultiplier{X}[index{X}];\n#endif\n#ifndef SHADOWCSMNOBLEND{X}\nvar frustumLength:f32=uniforms.frustumLengths{X}[index{X}];var diffRatio:f32=clamp(diff{X}/frustumLength,0.,1.)*uniforms.cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\n{index{X}+=1;var nextShadow: f32=0.;\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nnextShadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#else\nnextShadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#endif\n#else\nnextShadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\nshadow=mix(nextShadow,shadow,diffRatio);\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\n#endif\n}\n#endif\n}\n#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;shadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\naggShadow+=shadow;numLights+=1.0;\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\n#else \ndiffuseBase+=info.diffuse*shadow;\n#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\n#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#endif\n#endif\n";K.IncludesShadersStoreWGSL[Hd]=Kd;const Yd="lightUboDeclaration",qd="#ifdef LIGHT{X}\nstruct Light{X}\n{vLightData: vec4f,\nvLightDiffuse: vec4f,\nvLightSpecular: vec4f,\n#ifdef SPOTLIGHT{X}\nvLightDirection: vec4f,\nvLightFalloff: vec4f,\n#elif defined(POINTLIGHT{X})\nvLightFalloff: vec4f,\n#elif defined(HEMILIGHT{X})\nvLightGround: vec3f,\n#endif\nshadowsInfo: vec4f,\ndepthValues: vec2f} ;var light{X} : Light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform textureProjectionMatrix{X}: mat4x4f;var projectionLightTexture{X}sampler: sampler;var projectionLightTexture{X}: texture_2d;\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array;uniform viewFrustumZ{X}: array;uniform frustumLengths{X}: array;uniform cascadeBlendFactor{X}: f32;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;var vPositionFromLight{X}: array;var vDepthMetric{X} : array;\n#if defined(SHADOWPCSS{X})\nvar shadowTexture{X}Sampler: sampler_comparison; \nvar shadowTexture{X}: texture_depth_2d_array;var depthTexture{X}Sampler: sampler;var depthTexture{X}: texture_2d_array;uniform lightSizeUVCorrection{X}: array;uniform depthCorrection{X}: array;uniform penumbraDarkness{X}: f32;\n#elif defined(SHADOWPCF{X})\nvar shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d_array;\n#else \nvar shadowTexture{X}Sampler: sampler; \nvar shadowTexture{X}: texture_2d_array;\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vCascadeColorsMultiplier{X}: array=array\n(\nvec3f ( 1.5,0.0,0.0 ),\nvec3f ( 0.0,1.5,0.0 ),\nvec3f ( 0.0,0.0,5.5 ),\nvec3f ( 1.5,0.0,5.5 ),\nvec3f ( 1.5,1.5,0.0 ),\nvec3f ( 1.0,1.0,1.0 ),\nvec3f ( 0.0,1.0,5.5 ),\nvec3f ( 0.5,3.5,0.75 )\n);\n#endif\n#elif defined(SHADOWCUBE{X})\nvar shadowTexture{X}Sampler: sampler;var shadowTexture{X}: texture_cube;\n#else\nvarying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;\n#if defined(SHADOWPCSS{X})\nvar shadowTexture{X}Sampler: sampler_comparison; \nvar shadowTexture{X}: texture_depth_2d;var depthTexture{X}Sampler: sampler; \nvar depthTexture{X}: texture_2d;\n#elif defined(SHADOWPCF{X})\nvar shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d;\n#else\nvar shadowTexture{X}Sampler: sampler; \nvar shadowTexture{X}: texture_2d;\n#endif\nuniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";K.IncludesShadersStoreWGSL[Yd]=qd;const $d="lightVxUboDeclaration",jd="#ifdef LIGHT{X}\nstruct Light{X}\n{vLightData: vec4f,\nvLightDiffuse: vec4f,\nvLightSpecular: vec4f,\n#ifdef SPOTLIGHT{X}\nvLightDirection: vec4f,\nvLightFalloff: vec4f,\n#elif defined(POINTLIGHT{X})\nvLightFalloff: vec4f,\n#elif defined(HEMILIGHT{X})\nvLightGround: vec3f,\n#endif\nshadowsInfo: vec4f,\ndepthValues: vec2f} ;var light{X} : Light{X};\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";K.IncludesShadersStoreWGSL[$d]=jd;const Zd="shadowsFragmentFunctions",Qd="#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfn unpack(color: vec4f)->f32\n{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfn computeFallOff(value: f32,clipSpace: vec2f,frustumEdgeFalloff: f32)->f32\n{var mask: f32=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\nfn computeShadowCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadow: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nreturn select(darkness,1.0,depth>shadow);}\nfn computeShadowWithPoissonSamplingCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,mapSize: f32,darkness: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec3f(-1.0,1.0,-1.0);poissonDisk[1]= vec3f(1.0,-1.0,-1.0);poissonDisk[2]= vec3f(-1.0,-1.0,-1.0);poissonDisk[3]= vec3f(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[0]*mapSize)),shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nvar esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;}\nfn computeShadowWithCloseESMCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nvar esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;}\nfn computeShadowCSM(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d_array,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,uv,layer));\n#else\nvar shadow: f32=textureSample(shadowTexture,shadowSampler,uv,layer).x;\n#endif\nreturn select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}\nfn computeShadow(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadow: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nreturn select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}}\nfn computeShadowWithPoissonSampling(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,mapSize: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec2f(-0.94201624,-0.39906216);poissonDisk[1]= vec2f(0.94558609,-0.76890725);poissonDisk[2]= vec2f(-0.094184101,-0.92938870);poissonDisk[3]= vec2f(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[0]*mapSize,0.)),shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nvar esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithCloseESM(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nvar esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\nfn getZInClip(clipSpace: vec3f,uvDepth: vec3f)->f32\n{\n#ifdef IS_NDC_HALF_ZRANGE\nreturn clipSpace.z;\n#else\nreturn uvDepth.z;\n#endif\n}\nconst GREATEST_LESS_THAN_ONE: f32=0.99999994;\n#define DISABLE_UNIFORMITY_ANALYSIS\nfn computeShadowWithCSMPCF1(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var shadow: f32=textureSampleCompare(shadowTexture,shadowSampler,uvDepth.xy,layer,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithCSMPCF3(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithCSMPCF5(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),layer,uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),layer,uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),layer,uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),layer,uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithPCF1(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var shadow: f32=textureSampleCompareLevel(shadowTexture,shadowSampler,uvDepth.xy,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithPCF3(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithPCF5(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst PoissonSamplers32: array=array (\nvec3f(0.06407013,0.05409927,0.),\nvec3f(0.7366577,0.5789394,0.),\nvec3f(-0.6270542,-0.5320278,0.),\nvec3f(-0.4096107,0.8411095,0.),\nvec3f(0.6849564,-0.4990818,0.),\nvec3f(-0.874181,-0.04579735,0.),\nvec3f(0.9989998,0.0009880066,0.),\nvec3f(-0.004920578,-0.9151649,0.),\nvec3f(0.1805763,0.9747483,0.),\nvec3f(-0.2138451,0.2635818,0.),\nvec3f(0.109845,0.3884785,0.),\nvec3f(0.06876755,-0.3581074,0.),\nvec3f(0.374073,-0.7661266,0.),\nvec3f(0.3079132,-0.1216763,0.),\nvec3f(-0.3794335,-0.8271583,0.),\nvec3f(-0.203878,-0.07715034,0.),\nvec3f(0.5912697,0.1469799,0.),\nvec3f(-0.88069,0.3031784,0.),\nvec3f(0.5040108,0.8283722,0.),\nvec3f(-0.5844124,0.5494877,0.),\nvec3f(0.6017799,-0.1726654,0.),\nvec3f(-0.5554981,0.1559997,0.),\nvec3f(-0.3016369,-0.3900928,0.),\nvec3f(-0.5550632,-0.1723762,0.),\nvec3f(0.925029,0.2995041,0.),\nvec3f(-0.2473137,0.5538505,0.),\nvec3f(0.9183037,-0.2862392,0.),\nvec3f(0.2469421,0.6718712,0.),\nvec3f(0.3916397,-0.4328209,0.),\nvec3f(-0.03576927,-0.6220032,0.),\nvec3f(-0.04661255,0.7995201,0.),\nvec3f(0.4402924,0.3640312,0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.)\n);const PoissonSamplers64: array=array (\nvec3f(-0.613392,0.617481,0.),\nvec3f(0.170019,-0.040254,0.),\nvec3f(-0.299417,0.791925,0.),\nvec3f(0.645680,0.493210,0.),\nvec3f(-0.651784,0.717887,0.),\nvec3f(0.421003,0.027070,0.),\nvec3f(-0.817194,-0.271096,0.),\nvec3f(-0.705374,-0.668203,0.),\nvec3f(0.977050,-0.108615,0.),\nvec3f(0.063326,0.142369,0.),\nvec3f(0.203528,0.214331,0.),\nvec3f(-0.667531,0.326090,0.),\nvec3f(-0.098422,-0.295755,0.),\nvec3f(-0.885922,0.215369,0.),\nvec3f(0.566637,0.605213,0.),\nvec3f(0.039766,-0.396100,0.),\nvec3f(0.751946,0.453352,0.),\nvec3f(0.078707,-0.715323,0.),\nvec3f(-0.075838,-0.529344,0.),\nvec3f(0.724479,-0.580798,0.),\nvec3f(0.222999,-0.215125,0.),\nvec3f(-0.467574,-0.405438,0.),\nvec3f(-0.248268,-0.814753,0.),\nvec3f(0.354411,-0.887570,0.),\nvec3f(0.175817,0.382366,0.),\nvec3f(0.487472,-0.063082,0.),\nvec3f(-0.084078,0.898312,0.),\nvec3f(0.488876,-0.783441,0.),\nvec3f(0.470016,0.217933,0.),\nvec3f(-0.696890,-0.549791,0.),\nvec3f(-0.149693,0.605762,0.),\nvec3f(0.034211,0.979980,0.),\nvec3f(0.503098,-0.308878,0.),\nvec3f(-0.016205,-0.872921,0.),\nvec3f(0.385784,-0.393902,0.),\nvec3f(-0.146886,-0.859249,0.),\nvec3f(0.643361,0.164098,0.),\nvec3f(0.634388,-0.049471,0.),\nvec3f(-0.688894,0.007843,0.),\nvec3f(0.464034,-0.188818,0.),\nvec3f(-0.440840,0.137486,0.),\nvec3f(0.364483,0.511704,0.),\nvec3f(0.034028,0.325968,0.),\nvec3f(0.099094,-0.308023,0.),\nvec3f(0.693960,-0.366253,0.),\nvec3f(0.678884,-0.204688,0.),\nvec3f(0.001801,0.780328,0.),\nvec3f(0.145177,-0.898984,0.),\nvec3f(0.062655,-0.611866,0.),\nvec3f(0.315226,-0.604297,0.),\nvec3f(-0.780145,0.486251,0.),\nvec3f(-0.371868,0.882138,0.),\nvec3f(0.200476,0.494430,0.),\nvec3f(-0.494552,-0.711051,0.),\nvec3f(0.612476,0.705252,0.),\nvec3f(-0.578845,-0.768792,0.),\nvec3f(-0.772454,-0.090976,0.),\nvec3f(0.504440,0.372295,0.),\nvec3f(0.155736,0.065157,0.),\nvec3f(0.391522,0.849605,0.),\nvec3f(-0.620106,-0.328104,0.),\nvec3f(0.789239,-0.419965,0.),\nvec3f(-0.545396,0.538133,0.),\nvec3f(-0.178564,-0.596057,0.)\n);fn computeShadowWithCSMPCSS(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uvDepthLayer: vec4f= vec4f(uvDepth.x,uvDepth.y,f32(layer),uvDepth.z);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;var exitCondition: bool=depthMetric>1.0 || depthMetric<0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);}\nfn computeShadowWithPCSS32(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);}\nfn computeShadowWithPCSS64(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);}\nfn computeShadowWithCSMPCSS16(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\nfn computeShadowWithCSMPCSS32(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\nfn computeShadowWithCSMPCSS64(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#endif\n";K.IncludesShadersStoreWGSL[Zd]=Qd;const Jd="shadowsVertex",ep="#ifdef SHADOWS\n#if defined(SHADOWCSM{X})\nvertexOutputs.vPositionFromCamera{X}=view*worldPos;\n#if SHADOWCSMNUM_CASCADES{X}>0\nvertexOutputs.vPositionFromLight{X}_0=uniforms.lightMatrix{X}[0]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_0=(-vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_0= (vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#if SHADOWCSMNUM_CASCADES{X}>1\nvertexOutputs.vPositionFromLight{X}_1=uniforms.lightMatrix{X}[1]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_1=(-vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_1= (vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#if SHADOWCSMNUM_CASCADES{X}>2\nvertexOutputs.vPositionFromLight{X}_2=uniforms.lightMatrix{X}[2]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_2=(-vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_2= (vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#if SHADOWCSMNUM_CASCADES{X}>3\nvertexOutputs.vPositionFromLight{X}_3=uniforms.lightMatrix{X}[3]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_3=(-vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_3= (vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvertexOutputs.vPositionFromLight{X}=uniforms.lightMatrix{X}*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}=(-vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}=(vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#endif\n";K.IncludesShadersStoreWGSL[Jd]=ep;const tp="fogFragmentDeclaration",ip="#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vFogInfos: vec4f;uniform vFogColor: vec3f;varying vFogDistance: vec3f;fn CalcFogFactor()->f32\n{var fogCoeff: f32=1.0;var fogStart: f32=uniforms.vFogInfos.y;var fogEnd: f32=uniforms.vFogInfos.z;var fogDensity: f32=uniforms.vFogInfos.w;var fogDistance: f32=length(fragmentInputs.vFogDistance);if (FOGMODE_LINEAR==uniforms.vFogInfos.x)\n{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}\nelse if (FOGMODE_EXP==uniforms.vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}\nelse if (FOGMODE_EXP2==uniforms.vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}\nreturn clamp(fogCoeff,0.0,1.0);}\n#endif\n";K.IncludesShadersStoreWGSL[tp]=ip;const sp="bumpFragment",np="var uvOffset: vec2f= vec2f(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)\n#ifdef NORMALXYSCALE\nvar normalScale: f32=1.0;\n#elif defined(BUMP)\nvar normalScale: f32=vBumpInfos.y;\n#else\nvar normalScale: f32=1.0;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nvar TBN: mat3x3f=vTBN;\n#elif defined(BUMP)\nvar TBNUV: vec2f=select(-vBumpUV,vBumpUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);\n#else\nvar TBNUV: vec2f=select(-vDetailUV,vDetailUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,vPositionW,TBNUV, vec2f(1.,1.));\n#endif\n#elif defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvar TBN: mat3x3f=vTBN;\n#else\nvar TBNUV: vec2f=select( -vMainUV1,vMainUV1,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW,vPositionW,TBNUV, vec2f(1.,1.));\n#endif\n#endif\n#ifdef PARALLAX\nvar invTBN: mat3x3f=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\nvar detailColor: vec4f=textureSample(detail,detailSampler,vDetailUV+uvOffset);var detailNormalRG: vec2f=detailColor.wy*2.0-1.0;var detailNormalB: f32=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));var detailNormal: vec3f= vec3f(detailNormalRG,detailNormalB);\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\n#define CUSTOM_FRAGMENT_BUMP_FRAGMENT\nnormalW=normalize(textureSample(bump,bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize( mat3x3f(normalMatrix)*normalW);\n#elif !defined(DETAIL)\nnormalW=perturbNormal(TBN,textureSample(bump,bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);\n#else\nvar bumpNormal: vec3f=textureSample(bump,bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;\n#if DETAIL_NORMALBLENDMETHOD==0 \ndetailNormal.xy*=vDetailInfos.z;var blendedNormal: vec3f=normalize( vec3f(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));\n#elif DETAIL_NORMALBLENDMETHOD==1 \ndetailNormal.xy*=vDetailInfos.z;bumpNormal+= vec3f(0.0,0.0,1.0);detailNormal*= vec3f(-1.0,-1.0,1.0);var blendedNormal: vec3f=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;\n#endif\nnormalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);\n#endif\n#elif defined(DETAIL)\ndetailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);\n#endif\n";K.IncludesShadersStoreWGSL[sp]=np;const rp="bumpFragmentMainFunctions",ap="#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)\n#if defined(TANGENT) && defined(NORMAL) \nvarying vTBN: mat3x3f;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform normalMatrix: mat4x4f;\n#if defined(WEBGL2) || defined(WEBGPU)\nfn toNormalMatrix(wMatrix: mat4x4f)->mat4x4f\n{var ret: mat4x4f=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]= vec4f(0.,0.,0.,1.);return ret;}\n#else\nfn toNormalMatrix(m: mat4x4f)->mat4x4f\n{var a00: f32=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3],\na10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3],\na20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3],\na30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3],\nb00=a00*a11-a01*a10,\nb01=a00*a12-a02*a10,\nb02=a00*a13-a03*a10,\nb03=a01*a12-a02*a11,\nb04=a01*a13-a03*a11,\nb05=a02*a13-a03*a12,\nb06=a20*a31-a21*a30,\nb07=a20*a32-a22*a30,\nb08=a20*a33-a23*a30,\nb09=a21*a32-a22*a31,\nb10=a21*a33-a23*a31,\nb11=a22*a33-a23*a32,\ndet=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;var mi: mat4x4f= mat4x4f(\na11*b11-a12*b10+a13*b09,\na02*b10-a01*b11-a03*b09,\na31*b05-a32*b04+a33*b03,\na22*b04-a21*b05-a23*b03,\na12*b08-a10*b11-a13*b07,\na00*b11-a02*b08+a03*b07,\na32*b02-a30*b05-a33*b01,\na20*b05-a22*b02+a23*b01,\na10*b10-a11*b08+a13*b06,\na01*b08-a00*b10-a03*b06,\na30*b04-a31*b02+a33*b00,\na21*b02-a20*b04-a23*b00,\na11*b07-a10*b09-a12*b06,\na00*b09-a01*b07+a02*b06,\na31*b01-a30*b03-a32*b00,\na20*b03-a21*b01+a22*b00)/det;return mat4x4f(mi[0][0],mi[1][0],mi[2][0],mi[3][0],\nmi[0][1],mi[1][1],mi[2][1],mi[3][1],\nmi[0][2],mi[1][2],mi[2][2],mi[3][2],\nmi[0][3],mi[1][3],mi[2][3],mi[3][3]);}\n#endif\n#endif\nfn perturbNormalBase(cotangentFrame: mat3x3f,normal: vec3f,scale: f32)->vec3f\n{\n#ifdef NORMALXYSCALE\nnormal=normalize(normal* vec3f(scale,scale,1.0));\n#endif\nreturn normalize(cotangentFrame*normal);}\nfn perturbNormal(cotangentFrame: mat3x3f,textureSample: vec3f,scale: f32)->vec3f\n{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}\nfn cotangent_frame(normal: vec3f,p: vec3f,uv: vec2f,tangentSpaceParams: vec2f)->mat3x3f\n{var dp1: vec3f=dpdx(p);var dp2: vec3f=dpdy(p);var duv1: vec2f=dpdx(uv);var duv2: vec2f=dpdy(uv);var dp2perp: vec3f=cross(dp2,normal);var dp1perp: vec3f=cross(normal,dp1);var tangent: vec3f=dp2perp*duv1.x+dp1perp*duv2.x;var bitangent: vec3f=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;var det: f32=max(dot(tangent,tangent),dot(bitangent,bitangent));var invmax: f32=select(inverseSqrt(det),0.0,det==0.0);return mat3x3f(tangent*invmax,bitangent*invmax,normal);}\n#endif\n";K.IncludesShadersStoreWGSL[rp]=ap;const op="samplerFragmentDeclaration",lp="#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 v_VARYINGNAME_UV: vec2f;\n#endif\nuniform _SAMPLERNAME_Sampler: sampler;uniform _SAMPLERNAME_: texture_2d;\n#endif\n";K.IncludesShadersStoreWGSL[op]=lp;const hp="bumpFragmentFunctions",cp="#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 minSamples: f32=4.;const maxSamples: f32=15.;const iMaxSamples: i32=15;fn parallaxOcclusion(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32)->vec2f {var parallaxLimit: f32=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;var vOffsetDir: vec2f=normalize(vViewDirCoT.xy);var vMaxOffset: vec2f=vOffsetDir*parallaxLimit;var numSamples: f32=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));var stepSize: f32=1.0/numSamples;var currRayHeight: f32=1.0;var vCurrOffset: vec2f= vec2f(0,0);var vLastOffset: vec2f= vec2f(0,0);var lastSampledHeight: f32=1.0;var currSampledHeight: f32=1.0;var keepWorking: bool=true;for (var i: i32=0; icurrRayHeight)\n{var delta1: f32=currSampledHeight-currRayHeight;var delta2: f32=(currRayHeight+stepSize)-lastSampledHeight;var ratio: f32=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}\nelse\n{currRayHeight-=stepSize;vLastOffset=vCurrOffset;\n#ifdef PARALLAX_RHS\nvCurrOffset-=stepSize*vMaxOffset;\n#else\nvCurrOffset+=stepSize*vMaxOffset;\n#endif\nlastSampledHeight=currSampledHeight;}}\nreturn vCurrOffset;}\nfn parallaxOffset(viewDir: vec3f,heightScale: f32)->vec2f\n{var height: f32=textureSample(bump,bumpSampler,vBumpUV).w;var texCoordOffset: vec2f=heightScale*viewDir.xy*height;\n#ifdef PARALLAX_RHS\nreturn texCoordOffset;\n#else\nreturn -texCoordOffset;\n#endif\n}\n#endif\n";K.IncludesShadersStoreWGSL[hp]=cp;const up="imageProcessingDeclaration",fp="#ifdef EXPOSURE\nuniform exposureLinear: f32;\n#endif\n#ifdef CONTRAST\nuniform contrast: f32;\n#endif\n#if defined(VIGNETTE) || defined(DITHER)\nuniform vInverseScreenSize: vec2f;\n#endif\n#ifdef VIGNETTE\nuniform vignetteSettings1: vec4f;uniform vignetteSettings2: vec4f;\n#endif\n#ifdef COLORCURVES\nuniform vCameraColorCurveNegative: vec4f;uniform vCameraColorCurveNeutral: vec4f;uniform vCameraColorCurvePositive: vec4f;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform colorTransformSettings: vec4f;\n#endif\n#ifdef DITHER\nuniform ditherIntensity: f32;\n#endif\n";K.IncludesShadersStoreWGSL[up]=fp;const dp="imageProcessingFunctions",pp="#if TONEMAPPING==3\nconst PBRNeutralStartCompression: f32=0.8-0.04;const PBRNeutralDesaturation: f32=0.15;fn PBRNeutralToneMapping( color: vec3f )->vec3f {var x: f32=min(color.r,min(color.g,color.b));var offset: f32=select(0.04,x-6.25*x*x,x<0.08);var result=color;result-=offset;var peak: f32=max(result.r,max(result.g,result.b));if (peakvec3f\n{var a: vec3f=v*(v+0.0245786)-0.000090537;var b: vec3f=v*(0.983729*v+0.4329510)+0.238081;return a/b;}\nfn ACESFitted(color: vec3f)->vec3f\n{var output=ACESInputMat*color;output=RRTAndODTFit(output);output=ACESOutputMat*output;output=saturate(output);return output;}\n#endif\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS\nfn applyImageProcessing(result: vec4f)->vec4f {\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART\nvar rgb=result.rgb;;\n#ifdef EXPOSURE\nrgb*=uniforms.exposureLinear;\n#endif\n#ifdef VIGNETTE\nvar viewportXY: vec2f=fragmentInputs.position.xy*uniforms.vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;var vignetteXY1: vec3f= vec3f(viewportXY*uniforms.vignetteSettings1.xy+uniforms.vignetteSettings1.zw,1.0);var vignetteTerm: f32=dot(vignetteXY1,vignetteXY1);var vignette: f32=pow(vignetteTerm,uniforms.vignetteSettings2.w);var vignetteColor: vec3f=uniforms.vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvar vignetteColorMultiplier: vec3f=mix(vignetteColor, vec3f(1,1,1),vignette);rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nrgb=mix(vignetteColor,rgb,vignette);\n#endif\n#endif\n#if TONEMAPPING==3\nrgb=PBRNeutralToneMapping(rgb);\n#elif TONEMAPPING==2\nrgb=ACESFitted(rgb);\n#elif TONEMAPPING==1\nconst tonemappingCalibration: f32=1.590579;rgb=1.0-exp2(-tonemappingCalibration*rgb);\n#endif\nrgb=toGammaSpaceVec3(rgb);rgb=saturate(rgb);\n#ifdef CONTRAST\nvar resultHighContrast: vec3f=rgb*rgb*(3.0-2.0*rgb);if (uniforms.contrast<1.0) {rgb=mix( vec3f(0.5,0.5,0.5),rgb,uniforms.contrast);} else {rgb=mix(rgb,resultHighContrast,uniforms.contrast-1.0);}\n#endif\n#ifdef COLORGRADING\nvar colorTransformInput: vec3f=rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvar colorTransformOutput: vec3f=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvar colorTransformOutput: vec3f=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nrgb=mix(rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\nvar luma: f32=getLuminance(rgb);var curveMix: vec2f=clamp( vec2f(luma*3.0-1.5,luma*-3.0+1.5), vec2f(0.0), vec2f(1.0));var colorCurve: vec4f=uniforms.vCameraColorCurveNeutral+curveMix.x*uniforms.vCameraColorCurvePositive-curveMix.y*uniforms.vCameraColorCurveNegative;rgb*=colorCurve.rgb;rgb=mix( vec3f(luma),rgb,colorCurve.a);\n#endif\n#ifdef DITHER\nvar rand: f32=getRand(fragmentInputs.position.xy*uniforms.vInverseScreenSize);var dither: f32=mix(-uniforms.ditherIntensity,uniforms.ditherIntensity,rand);rgb=saturate(rgb+ vec3f(dither));\n#endif\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND\nreturn vec4f(rgb,result.a);}";K.IncludesShadersStoreWGSL[dp]=pp;const _p="reflectionFunction",gp="fn computeFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f\n{var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0); }\nfn computeMirroredFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f\n{var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(1.0-s,t,0); }\nfn computeEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f\n{var cameraToVertex: vec3f=normalize(worldPos.xyz-eyePosition);var r: vec3f=normalize(reflect(cameraToVertex,worldNormal));r= (reflectionMatrix* vec4f(r,0)).xyz;var lon: f32=atan2(r.z,r.x);var lat: f32=acos(r.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0);}\nfn computeSphericalCoords(worldPos: vec4f,worldNormal: vec3f,view: mat4x4f,reflectionMatrix: mat4x4f)->vec3f\n{var viewDir: vec3f=normalize((view*worldPos).xyz);var viewNormal: vec3f=normalize((view* vec4f(worldNormal,0.0)).xyz);var r: vec3f=reflect(viewDir,viewNormal);r= (reflectionMatrix* vec4f(r,0)).xyz;r.z=r.z-1.0;var m: f32=2.0*length(r);return vec3f(r.x/m+0.5,1.0-r.y/m-0.5,0);}\nfn computePlanarCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f\n{var viewDir: vec3f=worldPos.xyz-eyePosition;var coords: vec3f=normalize(reflect(viewDir,worldNormal));return (reflectionMatrix* vec4f(coords,1)).xyz;}\nfn computeCubicCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f\n{var viewDir: vec3f=normalize(worldPos.xyz-eyePosition);var coords: vec3f=reflect(viewDir,worldNormal);coords= (reflectionMatrix* vec4f(coords,0)).xyz;\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;}\nfn computeCubicLocalCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f,reflectionSize: vec3f,reflectionPosition: vec3f)->vec3f\n{var viewDir: vec3f=normalize(worldPos.xyz-eyePosition);var coords: vec3f=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=(reflectionMatrix* vec4f(coords,0)).xyz;\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;}\nfn computeProjectionCoords(worldPos: vec4f,view: mat4x4f,reflectionMatrix: mat4x4f)->vec3f\n{return (reflectionMatrix*(view*worldPos)).xyz;}\nfn computeSkyBoxCoords(positionW: vec3f,reflectionMatrix: mat4x4f)->vec3f\n{return (reflectionMatrix* vec4f(positionW,1.)).xyz;}\n#ifdef REFLECTION\nfn computeReflectionCoords(worldPos: vec4f,worldNormal: vec3f)->vec3f\n{\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nvar direction: vec3f=normalize(vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvar direction: vec3f=normalize(vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nreturn computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nreturn computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nreturn computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_CUBIC\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nreturn computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition);\n#else\nreturn computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn computeProjectionCoords(worldPos,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn computeSkyBoxCoords(vPositionUVW,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3f(0,0,0);\n#endif\n}\n#endif\n";K.IncludesShadersStoreWGSL[_p]=gp;const mp="fogVertexDeclaration",vp="#ifdef FOG\nvarying vFogDistance: vec3f;\n#endif\n";K.IncludesShadersStoreWGSL[mp]=vp;const xp="logDepthDeclaration",bp="#ifdef LOGARITHMICDEPTH\nuniform logarithmicDepthConstant: f32;varying vFragmentDepth: f32;\n#endif\n";K.IncludesShadersStoreWGSL[xp]=bp;const yp="fogVertex",Tp="#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif\n";K.IncludesShadersStoreWGSL[yp]=Tp;const Sp="logDepthVertex",Ep="#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+vertexOutputs.position.w;vertexOutputs.position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif\n";K.IncludesShadersStoreWGSL[Sp]=Ep;const Ip="particlesVertexShader",Ap="attribute position: vec3f;attribute color: vec4f;attribute angle: f32;attribute size: vec2f;\n#ifdef ANIMATESHEET\nattribute cellIndex: f32;\n#endif\n#ifndef BILLBOARD\nattribute direction: vec3f;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute direction: vec3f;\n#endif\n#ifdef RAMPGRADIENT\nattribute remapData: vec4f;\n#endif\nattribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform translationPivot: vec2f;\n#ifdef ANIMATESHEET\nuniform particlesInfos: vec3f; \n#endif\nvarying vUV: vec2f;varying vColor: vec4f;varying vPositionW: vec3f;\n#ifdef RAMPGRADIENT\nvarying remapRanges: vec4f;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform invView: mat4x4f;\n#endif\n#include\n#include\n#include\n#ifdef BILLBOARD\nuniform eyePosition: vec3f;\n#endif\nfn rotate(yaxis: vec3f,rotatedCorner: vec3f)->vec3f {var xaxis: vec3f=normalize(cross( vec3f(0.,1.0,0.),yaxis));var zaxis: vec3f=normalize(cross(yaxis,xaxis));var row0: vec3f= vec3f(xaxis.x,xaxis.y,xaxis.z);var row1: vec3f= vec3f(yaxis.x,yaxis.y,yaxis.z);var row2: vec3f= vec3f(zaxis.x,zaxis.y,zaxis.z);var rotMatrix: mat3x3f= mat3x3f(row0,row1,row2);var alignedCorner: vec3f=rotMatrix*rotatedCorner;return vertexInputs.position+alignedCorner;}\n#ifdef BILLBOARDSTRETCHED\nfn rotateAlign(toCamera: vec3f,rotatedCorner: vec3f)->vec3f {var normalizedToCamera: vec3f=normalize(toCamera);var normalizedCrossDirToCamera: vec3f=normalize(cross(normalize(direction),normalizedToCamera));var row0: vec3f= vec3f(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);var row2: vec3f= vec3f(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvar row1: vec3f=direction;\n#else\nvar crossProduct: vec3f=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));var row1: vec3f= vec3f(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nvar rotMatrix: mat3x3f= mat3x3f(row0,row1,row2);var alignedCorner: vec3f=rotMatrix*rotatedCorner;return vertexInputs.position+alignedCorner;}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input: VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar cornerPos: vec2f;cornerPos=( vec2f(vertexInputs.offset.x-0.5,vertexInputs.offset.y -0.5)-uniforms.translationPivot)*vertexInputs.size;\n#ifdef BILLBOARD\nvar rotatedCorner: vec3f;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(vertexInputs.angle)-cornerPos.y*sin(vertexInputs.ngle);rotatedCorner.z=cornerPos.x*sin(vertexInputs.angle)+cornerPos.y*cos(vertexInputs.angle);rotatedCorner.y=0.;rotatedCorner.xz+=uniforms.translationPivot;var yaxis: vec3f=vertexInputs.position-eyePosition;yaxis.y=0.;vertexOutputs.vPositionW=rotate(normalize(yaxis),rotatedCorner);var viewPos: vec3f=(uniforms.view* vec4f(vertexOutputs.vPositionW,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(vertexInputs.angle)-cornerPos.y*sin(vertexInputs.angle);rotatedCorner.y=cornerPos.x*sin(vertexInputs.angle)+cornerPos.y*cos(vertexInputs.angle);rotatedCorner.z=0.;rotatedCorner.x+=uniforms.translationPivot.x;rotatedCorner.y+=uniforms.translationPivot.y;var toCamera: vec3f=vertexInputs.position-eyePosition;vertexOutputs.vPositionW=rotateAlign(toCamera,rotatedCorner);var viewPos: vec3f=(uniforms.view* vec4f(vertexOutputs.vPositionW,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(vertexInputs.angle)-cornerPos.y*sin(vertexInputs.angle);rotatedCorner.y=cornerPos.x*sin(vertexInputs.angle)+cornerPos.y*cos(vertexInputs.angle);rotatedCorner.z=0.;rotatedCorner.x+=uniforms.translationPivot.x;rotatedCorner.y+=uniforms.translationPivot.y;var viewPos: vec3f=(uniforms.view* vec4f(vertexInputs.position,1.0)).xyz+rotatedCorner;vertexOutputs.vPositionW=(uniforms.invView* vec4f(viewPos,1)).xyz;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\nvertexOutputs.position=uniforms.projection* vec4f(viewPos,1.0);\n#else\nvar rotatedCorner: vec3f;rotatedCorner.x=cornerPos.x*cos(vertexInputs.angle)-cornerPos.y*sin(vertexInputs.angle);rotatedCorner.z=cornerPos.x*sin(vertexInputs.angle)+cornerPos.y*cos(vertexInputs.angle);rotatedCorner.y=0.;rotatedCorner.x+=uniforms.translationPivot.x;rotatedCorner.y+=uniforms.translationPivot.y;var yaxis: vec3f=normalize(direction);vertexOutputs.vPositionW=rotate(yaxis,rotatedCorner);vertexOutputs.position=uniforms.projection*view* vec4f(vertexOutputs.vPositionW,1.0);\n#endif\nvertexOutputs.vColor=vertexInputs.color;\n#ifdef ANIMATESHEET\nvar rowOffset: f32=floor(cellIndex*particlesInfos.z);var columnOffset: f32=cellIndex-rowOffset/particlesInfos.z;var uvScale: vec2f=particlesInfos.xy;var uvOffset: vec2f= vec2f(vertexInputs.offset.x ,1.0-vertexInputs.offset.y);vertexOutputs.vUV=(uvOffset+ vec2f(columnOffset,rowOffset))*uvScale;\n#else\nvertexOutputs.vUV=vertexInputs.offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvar worldPos: vec4f= vec4f(vertexOutputs.vPositionW,1.0);\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";K.ShadersStoreWGSL[Ip]=Ap;const q0="fragmentOutputs.fragDepth",Cp="uniforms",Mp="internals",Rp={texture_1d:"1d",texture_2d:"2d",texture_2d_array:"2d-array",texture_3d:"3d",texture_cube:"cube",texture_cube_array:"cube-array",texture_multisampled_2d:"2d",texture_depth_2d:"2d",texture_depth_2d_array:"2d-array",texture_depth_cube:"cube",texture_depth_cube_array:"cube-array",texture_depth_multisampled_2d:"2d",texture_storage_1d:"1d",texture_storage_2d:"2d",texture_storage_2d_array:"2d-array",texture_storage_3d:"3d",texture_external:null};class Pp extends bt{constructor(){super(...arguments),this.shaderLanguage=1,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}preProcessor(e,t,i,s,n){for(const r in i){if(r==="__VERSION__")continue;const o=i[r];(!isNaN(parseInt(o))||!isNaN(parseFloat(o)))&&(e="const ".concat(r," = ").concat(o,";\n")+e)}return e}_getArraySize(e,t,i){let s=0;const n=t.lastIndexOf(">");if(t.indexOf("array")>=0&&n>0){let r=n;for(;r>0&&t.charAt(r)!==" "&&t.charAt(r)!==",";)r--;const o=t.substring(r+1,n);for(s=+o,isNaN(s)&&(s=+i[o.trim()]);r>0&&(t.charAt(r)===" "||t.charAt(r)===",");)r--;t=t.substring(t.indexOf("<")+1,r+1)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t="struct ".concat(bt.InternalsUBOName," {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar ").concat(Mp," : ").concat(bt.InternalsUBOName,";\n");return e.indexOf(t)!==-1?e:t+ga(e)}varyingCheck(e,t){return/(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/.test(e)}varyingProcessor(e,t,i){var r,o;const n=/\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(n!==null){const l=(r=n[1])!=null?r:"perspective",h=(o=n[2])!=null?o:"center",c=n[4],u=n[3],f=l==="flat"?"@interpolate(".concat(l,")"):"@interpolate(".concat(l,", ").concat(h,")");let d;t?(d=this._webgpuProcessingContext.availableVaryings[u],d===void 0&&U.Warn('Invalid fragment shader: The varying named "'.concat(u,'" is not declared in the vertex shader! This declaration will be ignored.'))):(d=this._webgpuProcessingContext.getVaryingNextLocation(c,this._getArraySize(u,c,i)[2]),this._webgpuProcessingContext.availableVaryings[u]=d,this._varyingsWGSL.push(" @location(".concat(d,") ").concat(f," ").concat(u," : ").concat(c,",")),this._varyingNamesWGSL.push(u)),e=""}return e}attributeProcessor(e,t){const s=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(s!==null){const n=s[2],r=s[1],o=this._webgpuProcessingContext.getAttributeNextLocation(n,this._getArraySize(r,n,t)[2]);this._webgpuProcessingContext.availableAttributes[r]=o,this._webgpuProcessingContext.orderedAttributes[o]=r;const l=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[r];if(l!==void 0){const h=l<0?l===-1?"i32":"vec"+-l+"":l===1?"u32":"vec"+l+"",c="_int_".concat(r,"_");this._attributesInputWGSL.push("@location(".concat(o,") ").concat(c," : ").concat(h,",")),this._attributesWGSL.push("".concat(r," : ").concat(n,",")),this._attributesConversionCodeWGSL.push("vertexInputs.".concat(r," = ").concat(n,"(vertexInputs_.").concat(c,");")),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push("@location(".concat(o,") ").concat(r," : ").concat(n,",")),this._attributesWGSL.push("".concat(r," : ").concat(n,",")),this._attributesConversionCodeWGSL.push("vertexInputs.".concat(r," = vertexInputs_.").concat(r,";"));e=""}return e}uniformProcessor(e,t,i){const s=this.uniformRegexp.exec(e);if(s!==null){const n=s[2],r=s[1];this._addUniformToLeftOverUBO(r,n,i),e=""}return e}textureProcessor(e,t,i){const s=this.textureRegexp.exec(e);if(s!==null){const n=s[1],r=s[2],o=!!s[3],l=s[4],h=l.indexOf("storage")>0,c=s[6],u=h?c.substring(0,c.indexOf(",")).trim():null;let f=o?this._getArraySize(n,r,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[n];if(d)f=d.textures.length;else{d={isTextureArray:f>0,isStorageTexture:h,textures:[],sampleType:"float"},f=f||1;for(let m=0;m0,g=Rp[l],_=p?"depth":c==="u32"?"uint":c==="i32"?"sint":"float";if(d.sampleType=_,g===void 0)throw"Can't get the texture dimension corresponding to the texture function \"".concat(l,'"!');for(let m=0;m=0?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const s=this._buildLeftOverUBO();e=s+e,t=s+t,e=e.replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;"),e=e.replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let n="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(n+=this._attributesInputWGSL.join("\n")),n+="\n};\nvar vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(n+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n",n+=this._attributesWGSL.join("\n"),n+="\n};\nvar vertexInputs : VertexInputs_;\n");let r="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(r+=this._varyingsWGSL.join("\n")),r+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=n+r+e;let o="\n vertexInputs".concat(this._hasNonFloatAttribute?"_":""," = input;\n");this._hasNonFloatAttribute&&(o+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n",o+=this._attributesConversionCodeWGSL.join("\n"),o+="\n");const l=" vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;";let h=e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")!==-1;e=(h?"diagnostic(off, derivative_uniformity);\n":"")+ma(e,"fn main",o,l),t=t.replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;"),t=t.replace(/#define /g,"//#define "),t=this._processStridedUniformArrays(t),t=t.replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let c="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(c+=this._varyingsWGSL.join("\n")),c+="\n};\nvar fragmentInputs : FragmentInputs;\n";let u="struct FragmentOutputs {\n @location(0) color : vec4,\n",f=!1,d=0;for(;!f&&(d=t.indexOf(q0,d),!(d<0));){const _=d;for(f=!0;d>1&&t.charAt(d)!=="\n";){if(t.charAt(d)==="/"&&t.charAt(d-1)==="/"){f=!1;break}d--}d=_+q0.length}f&&(u+=" @builtin(frag_depth) fragDepth: f32,\n"),u+="};\nvar fragmentOutputs : FragmentOutputs;\n",t=c+u+t;const p=" fragmentInputs = input;\n "+i,g=" return fragmentOutputs;";return h=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")!==-1,t=(h?"diagnostic(off, derivative_uniformity);\n":"")+ma(t,"fn main",p,g),this._collectBindingNames(),this._preCreateBindGroupEntries(),this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",s="struct ".concat(e," {\n");for(const n of this._webgpuProcessingContext.leftOverUniforms){const r=n.type.replace(/^(.*?)(<.*>)?$/,"$1"),o=bt.UniformSizes[r];if(n.length>0)if(o<=2){const l="".concat(e,"_").concat(this._stridedUniformArrays.length,"_strided_arr");i+="struct ".concat(l," {\n @size(16)\n el: ").concat(r,",\n }"),this._stridedUniformArrays.push(n.name),s+=" @align(16) ".concat(n.name," : array<").concat(l,", ").concat(n.length,">,\n")}else s+=" ".concat(n.name," : array<").concat(n.type,", ").concat(n.length,">,\n");else s+=" ".concat(n.name," : ").concat(n.type,",\n")}return s+="};\n",s="".concat(i,"\n").concat(s),s+="@group(".concat(t.binding.groupIndex,") @binding(").concat(t.binding.bindingIndex,") var ").concat(Cp," : ").concat(e,";\n"),s}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const s=i.exec(e);if(s===null)break;const n=s[1],r=s[2],o=n.length-7,l=n.lastIndexOf("Sampler")===o?n.substring(0,o):null,h=r==="sampler_comparison"?"comparison":"filtering";if(l){const p=this._webgpuProcessingContext.availableTextures[l];p&&(p.autoBindSampler=!0)}let c=this._webgpuProcessingContext.availableSamplers[n];c||(c={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:h},this._webgpuProcessingContext.availableSamplers[n]=c),this._addSamplerBindingDescription(n,c,t);const u=e.substring(0,s.index),f="@group(".concat(c.binding.groupIndex,") @binding(").concat(c.binding.bindingIndex,") "),d=e.substring(s.index);e=u+f+d,i.lastIndex+=f.length}return e}_processCustomBuffers(e,t){var s;const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const n=i.exec(e);if(n===null)break;const r=n[1],o=n[3];let l=n[4];const h=n[5];let c=this._webgpuProcessingContext.availableBuffers[l];if(!c){const _=r==="uniform"?ii.KnownUBOs[h]:null;let m;_?(l=h,m=_.binding,m.groupIndex===-1&&(m=(s=this._webgpuProcessingContext.availableBuffers[l])==null?void 0:s.binding,m||(m=this._webgpuProcessingContext.getNextFreeUBOBinding()))):m=this._webgpuProcessingContext.getNextFreeUBOBinding(),c={binding:m},this._webgpuProcessingContext.availableBuffers[l]=c}this._addBufferBindingDescription(l,this._webgpuProcessingContext.availableBuffers[l],o==="read_write"?"storage":r==="storage"?"read-only-storage":"uniform",t);const u=c.binding.groupIndex,f=c.binding.bindingIndex,d=e.substring(0,n.index),p="@group(".concat(u,") @binding(").concat(f,") "),g=e.substring(n.index);e=d+p+g,i.lastIndex+=p.length}return e}_processStridedUniformArrays(e){for(const t of this._stridedUniformArrays)e=e.replace(new RegExp("".concat(t,"\\s*\\[(.*?)\\]"),"g"),"".concat(t,"[$1].el"));return e}}class Ve{static ComputeNumMipmapLevels(e,t){return Ye.ILog2(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb10a2uint":case"rgb10a2unorm":case"rgb9e5ufloat":case"rg11b10ufloat":case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc6h-rgb-ufloat":case"bc6h-rgb-float":case"bc5-rg-unorm":case"bc5-rg-snorm":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc4-r-unorm":case"bc4-r-snorm":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-r11unorm":case"eac-r11snorm":case"eac-rg11unorm":case"eac-rg11snorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":case"stencil8":return 0;case"r16uint":case"r16sint":case"rg16uint":case"rg16sint":case"rgba16uint":case"rgba16sint":case"depth16unorm":return 5;case"r16float":case"rg16float":case"rgba16float":return 2;case"r32uint":case"r32sint":case"rg32uint":case"rg32sint":case"rgba32uint":case"rgba32sint":return 7;case"r32float":case"rg32float":case"rgba32float":case"depth32float":case"depth32float-stencil8":case"depth24plus":case"depth24plus-stencil8":return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":return{width:1,height:1,length:1};case"r16uint":case"r16sint":case"r16float":case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":return{width:1,height:1,length:2};case"r32uint":case"r32sint":case"r32float":case"rg16uint":case"rg16sint":case"rg16float":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb9e5ufloat":case"rgb10a2uint":case"rgb10a2unorm":case"rg11b10ufloat":return{width:1,height:1,length:4};case"rg32uint":case"rg32sint":case"rg32float":case"rgba16uint":case"rgba16sint":case"rgba16float":return{width:1,height:1,length:8};case"rgba32uint":case"rgba32sint":case"rgba32float":return{width:1,height:1,length:16};case"stencil8":throw"No fixed size for Stencil8 format!";case"depth16unorm":return{width:1,height:1,length:2};case"depth24plus":throw"No fixed size for Depth24Plus format!";case"depth24plus-stencil8":throw"No fixed size for Depth24PlusStencil8 format!";case"depth32float":return{width:1,height:1,length:4};case"depth32float-stencil8":return{width:1,height:1,length:5};case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc6h-rgb-ufloat":case"bc6h-rgb-float":case"bc5-rg-unorm":case"bc5-rg-snorm":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":return{width:4,height:4,length:16};case"bc4-r-unorm":case"bc4-r-snorm":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":return{width:4,height:4,length:8};case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"eac-r11unorm":case"eac-r11snorm":return{width:4,height:4,length:8};case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-rg11unorm":case"eac-rg11snorm":return{width:4,height:4,length:16};case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":return{width:4,height:4,length:16};case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":return{width:5,height:4,length:16};case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":return{width:5,height:5,length:16};case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":return{width:6,height:5,length:16};case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":return{width:6,height:6,length:16};case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":return{width:8,height:5,length:16};case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":return{width:8,height:6,length:16};case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":return{width:8,height:8,length:16};case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":return{width:10,height:5,length:16};case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":return{width:10,height:6,length:16};case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":return{width:10,height:8,length:16};case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":return{width:10,height:10,length:16};case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":return{width:12,height:10,length:16};case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return e.close!==void 0}static IsImageBitmapArray(e){return Array.isArray(e)&&e[0].close!==void 0}static IsCompressedFormat(e){switch(e){case"bc7-rgba-unorm-srgb":case"bc7-rgba-unorm":case"bc6h-rgb-float":case"bc6h-rgb-ufloat":case"bc5-rg-snorm":case"bc5-rg-unorm":case"bc4-r-snorm":case"bc4-r-unorm":case"bc3-rgba-unorm-srgb":case"bc3-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc1-rgba-unorm-srgb":case"bc1-rgba-unorm":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-r11unorm":case"eac-r11snorm":case"eac-rg11unorm":case"eac-rg11snorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return"depth16unorm";case 16:return"depth24plus";case 13:return"depth24plus-stencil8";case 14:return"depth32float";case 18:return"depth32float-stencil8";case 19:return"stencil8";case 36492:return i?"bc7-rgba-unorm-srgb":"bc7-rgba-unorm";case 36495:return"bc6h-rgb-ufloat";case 36494:return"bc6h-rgb-float";case 33779:return i?"bc3-rgba-unorm-srgb":"bc3-rgba-unorm";case 33778:return i?"bc2-rgba-unorm-srgb":"bc2-rgba-unorm";case 33777:case 33776:return i?"bc1-rgba-unorm-srgb":"bc1-rgba-unorm";case 37808:return i?"astc-4x4-unorm-srgb":"astc-4x4-unorm";case 36196:case 37492:return i?"etc2-rgb8unorm-srgb":"etc2-rgb8unorm";case 37496:return i?"etc2-rgba8unorm-srgb":"etc2-rgba8unorm"}switch(e){case 3:switch(t){case 6:return"r8snorm";case 7:return"rg8snorm";case 4:throw"RGB format not supported in WebGPU";case 8:return"r8sint";case 9:return"rg8sint";case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return"rgba8sint";default:return"rgba8snorm"}case 0:switch(t){case 6:return"r8unorm";case 7:return"rg8unorm";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?"rgba8unorm-srgb":"rgba8unorm";case 12:return i?"bgra8unorm-srgb":"bgra8unorm";case 8:return"r8uint";case 9:return"rg8uint";case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return"rgba8uint";case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return"rgba8unorm"}case 4:switch(t){case 8:return"r16sint";case 9:return"rg16sint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return"rgba16sint";default:return"rgba16sint"}case 5:switch(t){case 8:return"r16uint";case 9:return"rg16uint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return"rgba16uint";default:return"rgba16uint"}case 6:switch(t){case 8:return"r32sint";case 9:return"rg32sint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return"rgba32sint";default:return"rgba32sint"}case 7:switch(t){case 8:return"r32uint";case 9:return"rg32uint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return"rgba32uint";default:return"rgba32uint"}case 1:switch(t){case 6:return"r32float";case 7:return"rg32float";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return"rgba32float";default:return"rgba32float"}case 2:switch(t){case 6:return"r16float";case 7:return"rg16float";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return"rgba16float";default:return"rgba16float"}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:return"rg11b10ufloat";case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV";default:return"rg11b10ufloat"}case 14:switch(t){case 5:return"rgb9e5ufloat";case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV";default:return"rgb9e5ufloat"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:return"rgb10a2unorm";case 11:return"rgb10a2uint";default:return"rgb10a2unorm"}}return i?"rgba8unorm-srgb":"rgba8unorm"}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":case"bc4-r-unorm":case"bc4-r-snorm":case"r16uint":case"r16sint":case"depth16unorm":case"r16float":case"r32uint":case"r32sint":case"r32float":case"depth32float":case"stencil8":case"depth24plus":case"eac-r11unorm":case"eac-r11snorm":return 1;case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"depth32float-stencil8":case"bc5-rg-unorm":case"bc5-rg-snorm":case"rg16uint":case"rg16sint":case"rg16float":case"rg32uint":case"rg32sint":case"rg32float":case"depth24plus-stencil8":case"eac-rg11unorm":case"eac-rg11snorm":return 2;case"rgb9e5ufloat":case"rg11b10ufloat":case"bc6h-rgb-ufloat":case"bc6h-rgb-float":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":return 3;case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb10a2uint":case"rgb10a2unorm":case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"rgba16uint":case"rgba16sint":case"rgba16float":case"rgba32uint":case"rgba32sint":case"rgba32float":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return 4}throw"Unknown format ".concat(e,"!")}static HasStencilAspect(e){switch(e){case"stencil8":case"depth32float-stencil8":case"depth24plus-stencil8":return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case"depth32float-stencil8":case"depth24plus-stencil8":return!0}return!1}static GetDepthFormatOnly(e){switch(e){case"depth16unorm":return"depth16unorm";case"depth24plus":return"depth24plus";case"depth24plus-stencil8":return"depth24plus";case"depth32float":return"depth32float";case"depth32float-stencil8":return"depth32float"}return e}static GetSample(e){return e>1?4:1}}class ir{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){var t,i;return(i=(t=this._webgpuMSAATexture)==null?void 0:t[e])!=null?i:null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),t===-1&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)e==null||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this._originalFormatIsRGB=!1,this.format="rgba8unorm",this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,s,n,r,o,l){let h="2d",c=1;s?(h=i?"cube-array":"cube",c=6*(l||1)):n?(h="3d",c=1):i&&(h="2d-array",c=l);const u=Ve.GetDepthFormatOnly(this.format),f=Ve.HasDepthAndStencilAspects(this.format)?"depth-only":"all";this.createView({label:"TextureView".concat(n?"3D":s?"Cube":"2D").concat(i?"_Array"+c:"","_").concat(r,"x").concat(o,"_").concat(t?"wmips":"womips","_").concat(this.format,"_").concat(h),format:u,dimension:h,mipLevelCount:t?Ye.ILog2(Math.max(r,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:c,aspect:f})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const i=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=i}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){var e,t;(e=this._webgpuTexture)==null||e.destroy(),this.releaseMSAATexture(),(t=this._copyInvertYTempTexture)==null||t.destroy(),this.reset()}}const wp="\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(location = 0) out vec2 vTex;\n\n void main() {\n vTex = tex[gl_VertexIndex];\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",Dp="\n layout(set = 0, binding = 0) uniform sampler imgSampler;\n layout(set = 0, binding = 1) uniform texture2D img;\n\n layout(location = 0) in vec2 vTex;\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = texture(sampler2D(img, imgSampler), vTex);\n }\n ",Fh="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) out flat ivec2 vTextureSize;\n #endif\n\n void main() {\n #ifdef INVERTY\n vTextureSize = textureSize(img, 0);\n #endif\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",Fp="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n ",Op=Fh,Lp="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n layout(set = 0, binding = 1) uniform Params {\n float ofstX;\n float ofstY;\n float width;\n float height;\n };\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {\n discard;\n }\n if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {\n discard;\n }\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n ",Bp="\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n\n void main() {\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",Np="\n layout(set = 0, binding = 0) uniform Uniforms {\n uniform vec4 color;\n };\n\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = color;\n }\n ",Up="\n struct VertexOutput {\n @builtin(position) Position : vec4,\n @location(0) fragUV : vec2\n }\n\n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n ",kp="\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ",Vp="\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y));\n }\n ";var gi;(function(a){a[a.MipMap=0]="MipMap",a[a.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",a[a.Clear=2]="Clear",a[a.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"})(gi||(gi={}));var Ks;(function(a){a[a.DontInvertY=0]="DontInvertY",a[a.InvertY=1]="InvertY"})(Ks||(Ks={}));const $0=[{vertex:wp,fragment:Dp},{vertex:Fh,fragment:Fp},{vertex:Bp,fragment:Np},{vertex:Op,fragment:Lp}],Gi={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};class Gp{constructor(e,t,i,s,n,r){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._glslang=i,this._tintWASM=s,this._bufferManager=n,r.indexOf("rg11b10ufloat-renderable")!==-1){const o=Object.keys(Gi);Gi.rg11b10ufloat=Gi[o[o.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:"linear"}),this._videoSampler=t.createSampler({minFilter:"linear"}),this._ubCopyWithOfst=this._bufferManager.createBuffer(4*4,We.Uniform|We.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline("rgba8unorm"),this._getVideoPipeline("rgba8unorm")}_getPipeline(e,t=gi.MipMap,i){const s=t===gi.MipMap?1:t===gi.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===gi.Clear?8:t===gi.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let n=this._pipelines[e][s];if(!n){let r="#version 450\n";(t===gi.InvertYPremultiplyAlpha||t===gi.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(r+="#define INVERTY\n"),i.premultiplyAlpha&&(r+="#define PREMULTIPLYALPHA\n"));let o=this._compiledShaders[s];if(!o){let h=this._glslang.compileGLSL(r+$0[t].vertex,"vertex"),c=this._glslang.compileGLSL(r+$0[t].fragment,"fragment");this._tintWASM&&(h=this._tintWASM.convertSpirV2WGSL(h),c=this._tintWASM.convertSpirV2WGSL(c));const u=this._device.createShaderModule({code:h}),f=this._device.createShaderModule({code:c});o=this._compiledShaders[s]=[u,f]}const l=this._device.createRenderPipeline({layout:"auto",vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint16"}});n=this._pipelines[e][s]=[l,l.getBindGroupLayout(0)]}return n}_getVideoPipeline(e,t=Ks.DontInvertY){const i=t===Ks.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let s=this._videoPipelines[e][i];if(!s){let n=this._videoCompiledShaders[i];if(!n){const o=this._device.createShaderModule({code:Up}),l=this._device.createShaderModule({code:i===0?kp:Vp});n=this._videoCompiledShaders[i]=[o,l]}const r=this._device.createRenderPipeline({label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_CopyVideoToTexture_").concat(e,"_").concat(i===0?"DontInvertY":"InvertY"),layout:"auto",vertex:{module:n[0],entryPoint:"main"},fragment:{module:n[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint16"}});s=this._videoPipelines[e][i]=[r,r.getBindGroupLayout(0)]}return s}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,s=!1,n){var p,g;const r=n===void 0,[o,l]=this._getVideoPipeline(i,s?Ks.InvertY:Ks.DontInvertY);r&&(n=this._device.createCommandEncoder({})),(p=n.pushDebugGroup)==null||p.call(n,"copy video to texture - invertY=".concat(s));const h=t._hardwareTexture,c={label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_copyVideoToTexture_").concat(i,"_").concat(s?"InvertY":"DontInvertY").concat(t.label?"_"+t.label:""),colorAttachments:[{view:h.underlyingResource.createView({format:i,dimension:"2d",mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:"all"}),loadOp:"load",storeOp:"store"}]},u=n.beginRenderPass(c),f={layout:l,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},d=this._device.createBindGroup(f);u.setPipeline(o),u.setBindGroup(0,d),u.draw(4,1,0,0),u.end(),(g=n.popDebugGroup)==null||g.call(n),r&&(this._device.queue.submit([n.finish()]),n=null)}invertYPreMultiplyAlpha(e,t,i,s,n=!1,r=!1,o=0,l=0,h=1,c=0,u=0,f=0,d=0,p,g){var C,w,P,z;const _=f!==0,m=p===void 0,[x,I]=this._getPipeline(s,_?gi.InvertYPremultiplyAlphaWithOfst:gi.InvertYPremultiplyAlpha,{invertY:n,premultiplyAlpha:r});o=Math.max(o,0),m&&(p=this._device.createCommandEncoder({})),(C=p.pushDebugGroup)==null||C.call(p,"internal process texture - invertY=".concat(n," premultiplyAlpha=").concat(r));let T;if(Ve.IsHardwareTexture(e)?(T=e.underlyingResource,n&&!r&&h===1&&o===0||(e=void 0)):(T=e,e=void 0),!T)return;_&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([c,u,f,d]),0,4*4);const y=e,b=(w=y==null?void 0:y._copyInvertYTempTexture)!=null?w:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,s,1,p,21,void 0,"TempTextureForCopyWithInvertY"),S=(P=y==null?void 0:y._copyInvertYRenderPassDescr)!=null?P:{label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_invertYPreMultiplyAlpha_").concat(s,"_").concat(n?"InvertY":"DontInvertY","_").concat(r?"PremultiplyAlpha":"DontPremultiplyAlpha"),colorAttachments:[{view:b.createView({format:s,dimension:"2d",baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:"load",storeOp:"store"}]},A=p.beginRenderPass(S);let M=_?y==null?void 0:y._copyInvertYBindGroupWithOfst:y==null?void 0:y._copyInvertYBindGroup;if(!M){const L={layout:I,entries:[{binding:0,resource:T.createView({format:s,dimension:"2d",baseMipLevel:l,mipLevelCount:1,arrayLayerCount:h,baseArrayLayer:o})}]};_&&L.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),M=this._device.createBindGroup(L)}A.setPipeline(x),A.setBindGroup(0,M),A.draw(4,1,0,0),A.end(),p.copyTextureToTexture({texture:b},{texture:T,mipLevel:l,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),y?(y._copyInvertYTempTexture=b,y._copyInvertYRenderPassDescr=S,_?y._copyInvertYBindGroupWithOfst=M:y._copyInvertYBindGroup=M):this._deferredReleaseTextures.push([b,null]),(z=p.popDebugGroup)==null||z.call(p),m&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,s){var c,u;const n=s===void 0,[r,o]=this._getPipeline(t,gi.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});n&&(s=this._device.createCommandEncoder({})),(c=s.pushDebugGroup)==null||c.call(s,"internal copy texture with invertY");const l=s.beginRenderPass(i),h=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:e}]});l.setPipeline(r),l.setBindGroup(0,h),l.draw(4,1,0,0),l.end(),(u=s.popDebugGroup)==null||u.call(s),n&&(this._device.queue.submit([s.finish()]),s=null)}createTexture(e,t=!1,i=!1,s=!1,n=!1,r=!1,o="rgba8unorm",l=1,h,c=-1,u=0,f){l=Ve.GetSample(l);const d=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:d},g=Gi[o]?16:0,_=Ve.IsCompressedFormat(o),m=t?Ve.ComputeNumMipmapLevels(e.width,e.height):1,x=c>=0?c:7;u|=t&&!_?1|g:0,!_&&!r&&(u|=g|2);const I=this._device.createTexture({label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_Texture").concat(r?"3D":"2D","_").concat(f?f+"_":"").concat(p.width,"x").concat(p.height,"x").concat(p.depthOrArrayLayers,"_").concat(t?"wmips":"womips","_").concat(o,"_samples").concat(l),size:p,dimension:r?"3d":"2d",format:o,usage:x|u,sampleCount:l,mipLevelCount:m});return Ve.IsImageBitmap(e)&&(this.updateTexture(e,I,e.width,e.height,d,o,0,0,s,n,0,0),t&&i&&this.generateMipmaps(I,o,m,0,r,h)),I}createCubeTexture(e,t=!1,i=!1,s=!1,n=!1,r="rgba8unorm",o=1,l,h=-1,c=0,u){o=Ve.GetSample(o);const f=Ve.IsImageBitmapArray(e)?e[0].width:e.width,d=Ve.IsImageBitmapArray(e)?e[0].height:e.height,p=Gi[r]?16:0,g=Ve.IsCompressedFormat(r),_=t?Ve.ComputeNumMipmapLevels(f,d):1,m=h>=0?h:7;c|=t&&!g?1|p:0,g||(c|=p|2);const x=this._device.createTexture({label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_TextureCube_").concat(u?u+"_":"").concat(f,"x").concat(d,"x6_").concat(t?"wmips":"womips","_").concat(r,"_samples").concat(o),size:{width:f,height:d,depthOrArrayLayers:6},dimension:"2d",format:r,usage:m|c,sampleCount:o,mipLevelCount:_});return Ve.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,x,f,d,r,s,n,0,0),t&&i&&this.generateCubeMipmaps(x,r,_,l)),x}generateCubeMipmaps(e,t,i,s){var r,o;const n=s===void 0;n&&(s=this._device.createCommandEncoder({})),(r=s.pushDebugGroup)==null||r.call(s,"create cube mipmaps - ".concat(i," levels"));for(let l=0;l<6;++l)this.generateMipmaps(e,t,i,l,!1,s);(o=s.popDebugGroup)==null||o.call(s),n&&(this._device.queue.submit([s.finish()]),s=null)}generateMipmaps(e,t,i,s=0,n=!1,r){var f,d,p,g,_,m;const o=r===void 0,[l,h]=this._getPipeline(t);s=Math.max(s,0),o&&(r=this._device.createCommandEncoder({})),(f=r.pushDebugGroup)==null||f.call(r,"create mipmaps for face #".concat(s," - ").concat(i," levels"));let c;if(Ve.IsHardwareTexture(e)?(c=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(c=e,e=void 0),!c)return;const u=e;for(let x=1;x=0;o--)(r=a[o])&&(n=(s<3?r(n):s>3?r(e,t,n):r(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}const $n={},sr={};function Wp(a){const e=a.getClassName();return sr[e]||(sr[e]={}),sr[e]}function va(a){const e=a.getClassName();if($n[e])return $n[e];$n[e]={};const t=$n[e];let i=a,s=e;for(;s;){const n=sr[s];for(const l in n)t[l]=n[l];let r,o=!1;do{if(r=Object.getPrototypeOf(i),!r.getClassName){o=!0;break}if(r.getClassName()!==s)break;i=r}while(r);if(o)break;s=r.getClassName(),i=r}return t}function Fi(a,e){return(t,i)=>{const s=Wp(t);s[i]||(s[i]={type:a,sourceName:e})}}function Xp(a,e=null){return(t,i)=>{const s=e||"_"+i;Object.defineProperty(t,i,{get:function(){return this[s]},set:function(n){typeof this.equals=="function"&&this.equals(n)||this[s]!==n&&(this[s]=n,t[a].apply(this))},enumerable:!0,configurable:!0})}}function qe(a,e=null){return Xp(a,e)}function B(a){return Fi(0,a)}function pi(a){return Fi(1,a)}function ls(a){return Fi(2,a)}function Ln(a){return Fi(3,a)}function Oh(a){return Fi(4,a)}function bi(a){return Fi(5,a)}function Lh(a){return Fi(6,a)}function Hp(a){return Fi(7,a)}function to(a){return Fi(8,a)}function Kp(a){return Fi(10,a)}function Yp(a){return Fi(11,a)}function ss(a,e,t,i){const s=t.value;t.value=(...n)=>{let r=s;if(typeof _native<"u"&&_native[e]){const o=_native[e];i?r=(...l)=>i(...l)?o(...l):s(...l):r=o}return a[e]=r,r(...n)}}ss.filter=function(a){return(e,t,i)=>ss(e,t,i,a)};class io{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return this._texture?this._texture.isCube:!1}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return(e==null?void 0:e.shareDepth)!==void 0}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=oi.Zero(),this._cachedBaseSize=oi.Zero(),this._initialSamplingMode=2,this._texture=io._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return this.delayLoadState===4?(this.delayLoad(),!1):this._texture?this._texture.isReady:!1}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return!this.isReady()||!this._texture?(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize):this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}class Cs{static Eval(e,t){return e.match(/\([^()]*\)/g)?e=e.replace(/\([^()]*\)/g,i=>(i=i.slice(1,i.length-1),Cs._HandleParenthesisContent(i,t))):e=Cs._HandleParenthesisContent(e,t),e==="true"?!0:e==="false"?!1:Cs.Eval(e,t)}static _HandleParenthesisContent(e,t){t=t||(n=>n==="true");let i;const s=e.split("||");for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)){let r=Cs._SimplifyNegation(s[n].trim());const o=r.split("&&");if(o.length>1)for(let l=0;l(t=t.replace(/[\s]/g,()=>""),t.length%2?"!":"")),e=e.trim(),e==="!true"?e="false":e==="!false"&&(e="true"),e}}class ze{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>ze.HasTags(e),e.addTags=t=>ze.AddTagsTo(e,t),e.removeTags=t=>ze.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>ze.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 i in t)if(Object.prototype.hasOwnProperty.call(t,i))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const i=[];for(const s in e._tags)Object.prototype.hasOwnProperty.call(e._tags,s)&&e._tags[s]===!0&&i.push(s);return i.join(" ")}else return e._tags}static AddTagsTo(e,t){if(!t||typeof t!="string")return;t.split(" ").forEach(function(s){ze._AddTagTo(e,s)})}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(ze.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!ze.HasTags(e))return;const i=t.split(" ");for(const s in i)ze._RemoveTagFrom(e,i[s])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?ze.HasTags(e):Cs.Eval(t,i=>ze.HasTags(e)&&e._tags[i])}}const j0=function(a,e,t,i={}){const s=a();ze&&ze.HasTags(e)&&ze.AddTagsTo(s,ze.GetTags(e,!0));const n=va(s),r={};for(const o in n){const l=n[o],h=e[o],c=l.type;if(h!=null&&(o!=="uniqueId"||Ae.AllowLoadingUniqueId))switch(c){case 0:case 6:case 11:s[o]=h;break;case 1:i.cloneTexturesOnlyOnce&&r[h.uniqueId]?s[o]=r[h.uniqueId]:(s[o]=t||h.isRenderTarget?h:h.clone(),r[h.uniqueId]=s[o]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:s[o]=t?h:h.clone();break}}return s};class Ae{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw Te("ImageProcessingConfiguration")};Ae._FresnelParametersParser=a=>{throw Te("FresnelParameters")};Ae._ColorCurvesParser=a=>{throw Te("ColorCurves")};Ae._TextureParser=(a,e,t)=>{throw Te("Texture")};class lt extends io{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.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:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){if(this._texture)this._texture._gammaSpace===null&&(this._texture._gammaSpace=this._gammaSpace);else return this._gammaSpace;return this._texture._gammaSpace&&!this._texture._useSRGBBuffer}set gammaSpace(e){var t;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this))}get isRGBD(){return this._texture!=null&&this._texture._isRGBD}set isRGBD(e){var t;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return this._texture?this._texture._linearSpecularLOD:!1}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=eo()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=lt.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new Q,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?lt._IsScene(e)?this._scene=e:this._engine=e:this._scene=Ce.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return O.IdentityReadOnly}getReflectionTextureMatrix(){return O.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,n,r){const o=this._getEngine();if(!o)return null;const l=o._getUseSRGBBuffer(!!n,t),h=o.getLoadedTexturesCache();for(let c=0;c=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const t=this._parentContainer.textures.indexOf(this);t>-1&&this._parentContainer.textures.splice(t,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=Ae.Serialize(this);return Ae.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(i===0){t();return}for(let s=0;s{--i===0&&t()}):--i===0&&t()}}}static _IsScene(e){return e.getClassName()==="Scene"}}lt.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;D([B()],lt.prototype,"uniqueId",void 0);D([B()],lt.prototype,"name",void 0);D([B()],lt.prototype,"metadata",void 0);D([B("hasAlpha")],lt.prototype,"_hasAlpha",void 0);D([B("getAlphaFromRGB")],lt.prototype,"_getAlphaFromRGB",void 0);D([B()],lt.prototype,"level",void 0);D([B("coordinatesIndex")],lt.prototype,"_coordinatesIndex",void 0);D([B()],lt.prototype,"optimizeUVAllocation",void 0);D([B("coordinatesMode")],lt.prototype,"_coordinatesMode",void 0);D([B()],lt.prototype,"wrapU",null);D([B()],lt.prototype,"wrapV",null);D([B()],lt.prototype,"wrapR",void 0);D([B()],lt.prototype,"anisotropicFilteringLevel",void 0);D([B()],lt.prototype,"isCube",null);D([B()],lt.prototype,"is3D",null);D([B()],lt.prototype,"is2DArray",null);D([B()],lt.prototype,"gammaSpace",null);D([B()],lt.prototype,"invertZ",void 0);D([B()],lt.prototype,"lodLevelInAlpha",void 0);D([B()],lt.prototype,"lodGenerationOffset",null);D([B()],lt.prototype,"lodGenerationScale",null);D([B()],lt.prototype,"linearSpecularLOD",null);D([pi()],lt.prototype,"irradianceTexture",null);D([B()],lt.prototype,"isRenderTarget",void 0);function Bh(a,e,t=!1){const i=e.width,s=e.height;if(a instanceof Float32Array){let h=a.byteLength/a.BYTES_PER_ELEMENT;const c=new Uint8Array(h);for(;--h>=0;){let u=a[h];u<0?u=0:u>1&&(u=1),c[h]=u*255}a=c}const n=document.createElement("canvas");n.width=i,n.height=s;const r=n.getContext("2d");if(!r)return null;const o=r.createImageData(i,s);if(o.data.set(a),r.putImageData(o,0,0),t){const h=document.createElement("canvas");h.width=i,h.height=s;const c=h.getContext("2d");return c?(c.translate(0,s),c.scale(1,-1),c.drawImage(n,0,0),h.toDataURL("image/png")):null}return n.toDataURL("image/png")}function qp(a,e=0,t=0){const i=a.getInternalTexture();if(!i)return null;const s=a._readPixelsSync(e,t);return s?Bh(s,a.getSize(),i.invertY):null}async function $p(a,e=0,t=0){const i=a.getInternalTexture();if(!i)return null;const s=await a.readPixels(e,t);return s?Bh(s,a.getSize(),i.invertY):null}class Le{}Le.UseOpenGLOrientationForUV=!1;class ne extends lt{static _CreateVideoTexture(e,t,i,s=!1,n=!1,r=ne.TRILINEAR_SAMPLINGMODE,o={},l,h=5){throw Te("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,s,n=ne.TRILINEAR_SAMPLINGMODE,r=null,o=null,l=null,h=!1,c,u,f,d,p){var S,A,M,C,w,P,z,L,G,H;super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedIdentity3x2=!0,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new Q,this._isBlocking=!0,this.name=e||"",this.url=e;let g,_=!1,m=null,x=!0;typeof i=="object"&&i!==null?(g=(S=i.noMipmap)!=null?S:!1,s=(A=i.invertY)!=null?A:!Le.UseOpenGLOrientationForUV,n=(M=i.samplingMode)!=null?M:ne.TRILINEAR_SAMPLINGMODE,r=(C=i.onLoad)!=null?C:null,o=(w=i.onError)!=null?w:null,l=(P=i.buffer)!=null?P:null,h=(z=i.deleteBuffer)!=null?z:!1,c=i.format,u=i.mimeType,f=i.loaderOptions,d=i.creationFlags,_=(L=i.useSRGBBuffer)!=null?L:!1,m=(G=i.internalTexture)!=null?G:null,x=(H=i.gammaSpace)!=null?H:x):g=!!i,this._gammaSpace=x,this._noMipmap=g,this._invertY=s===void 0?!Le.UseOpenGLOrientationForUV:s,this._initialSamplingMode=n,this._buffer=l,this._deleteBuffer=h,this._mimeType=u,this._loaderOptions=f,this._creationFlags=d,this._useSRGBBuffer=_,this._forcedExtension=p,c&&(this._format=c);const I=this.getScene(),T=this._getEngine();if(!T)return;T.onBeforeTextureInitObservable.notifyObservers(this);const y=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),this._texture._cachedWrapU!==null&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),this._texture._cachedWrapV!==null&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),this._texture._cachedWrapR!==null&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),r&&r(),!this.isBlocking&&I&&I.resetCachedMaterial()},b=(ce,J)=>{this._loadingError=!0,this._errorObject={message:ce,exception:J},o&&o(ce,J),ne.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!m){this._delayedOnLoad=y,this._delayedOnError=b;return}if(this._texture=m!=null?m:this._getFromCache(this.url,g,n,this._invertY,_,this.isCube),this._texture)if(this._texture.isReady)hr.SetImmediate(()=>y());else{const ce=this._texture.onLoadedObservable.add(y);this._texture.onErrorObservable.add(J=>{var W;b(J.message,J.exception),(W=this._texture)==null||W.onLoadedObservable.remove(ce)})}else if(!I||!I.useDelayedTextureLoading){try{this._texture=T.createTexture(this.url,g,this._invertY,I,n,y,b,this._buffer,void 0,this._format,this._forcedExtension,u,f,d,_)}catch(ce){throw b("error loading",ce),ce}h&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=y,this._delayedOnError=b}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,n=>n.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=s,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(this.delayLoadState!==4)return;const e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?hr.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,s){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,v.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,s),s.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,s.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,s.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,(!this._cachedTextureMatrix||!this._rowGenerationMatrix)&&(this._cachedTextureMatrix=O.Zero(),this._rowGenerationMatrix=new O,this._t0=v.Zero(),this._t1=v.Zero(),this._t2=v.Zero()),O.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(O.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,N.Matrix[0]),O.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,N.Matrix[1]),O.ScalingToRef(this._cachedUScale,this._cachedVScale,0,N.Matrix[2]),O.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,N.Matrix[3]),N.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(N.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(N.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(N.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),O.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));const t=this.getScene();if(!t)return this._cachedTextureMatrix;const i=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&i!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(1,s=>s.hasTexture(this)),this._cachedTextureMatrix}getReflectionTextureMatrix(){const e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode)if(this.coordinatesMode===ne.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=O.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=O.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 ne.PLANAR_MODE:{O.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 ne.PROJECTION_MODE:{O.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const i=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=i.updateFlag,i.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:O.IdentityToRef(this._cachedReflectionTextureMatrix);break}return t&&e.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){const e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return Ae.Clone(()=>new ne(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var i,s;const e=this.name;ne.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(ne._SerializeInternalTextureUniqueId);return t?((ne.SerializeBuffers||ne.ForceSerializeBuffers)&&(typeof this._buffer=="string"&&this._buffer.substr(0,5)==="data:"?(t.base64String=this._buffer,t.name=t.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?t.base64String="data:image/png;base64,"+Mh(this._buffer):(ne.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?qp(this):$p(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,ne._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=(s=(i=this._texture)==null?void 0:i.uniqueId)!=null?s:void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const h=yn.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&h.updateSamplingMode&&h._samplingMode&&h._samplingMode!==e.samplingMode&&h.updateSamplingMode(e.samplingMode),h}if(e.isCube&&!e.isRenderTarget)return ne._CubeTextureParser(e,t,i);const s=e.internalTextureUniqueId!==void 0;if(!e.name&&!e.isRenderTarget&&!s)return null;let n;if(s){const l=t.getEngine().getLoadedTexturesCache();for(const h of l)if(h.uniqueId===e.internalTextureUniqueId){n=h;break}}const r=l=>{var h;if(l&&l._texture&&(l._texture._cachedWrapU=null,l._texture._cachedWrapV=null,l._texture._cachedWrapR=null),e.samplingMode){const c=e.samplingMode;l&&l.samplingMode!==c&&l.updateSamplingMode(c)}if(l&&e.animations)for(let c=0;c{var h,c,u;let l=!0;if(e.noMipmap&&(l=!1),e.mirrorPlane){const f=ne._CreateMirror(e.name,e.renderTargetSize,t,l);return f._waitingRenderList=e.renderList,f.mirrorPlane=Yt.FromArray(e.mirrorPlane),r(f),f}else if(e.isRenderTarget){let f=null;if(e.isCube){if(t.reflectionProbes)for(let d=0;d{r(f)},(c=e._creationFlags)!=null?c:0,(u=e._useSRGBBuffer)!=null?u:!1),f.name=e.name;else{let d;e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?d=e.name:d=i+e.name,e.url&&(e.url.startsWith("data:")||ne.UseSerializedUrlIfAny)&&(d=e.url);const p={noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{r(f)},internalTexture:n};f=new ne(d,t,p)}return f}},e,t)}static CreateFromBase64String(e,t,i,s,n,r=ne.TRILINEAR_SAMPLINGMODE,o=null,l=null,h=5,c,u){return new ne("data:"+t,i,s,n,r,o,l,e,!1,h,void 0,void 0,c,u)}static LoadFromDataString(e,t,i,s=!1,n,r=!0,o=ne.TRILINEAR_SAMPLINGMODE,l=null,h=null,c=5,u,f){return e.substr(0,5)!=="data:"&&(e="data:"+e),new ne(e,i,n,r,o,l,h,t,s,c,void 0,void 0,u,f)}}ne.SerializeBuffers=!0;ne.ForceSerializeBuffers=!1;ne.OnTextureLoadErrorObservable=new Q;ne._SerializeInternalTextureUniqueId=!1;ne._CubeTextureParser=(a,e,t)=>{throw Te("CubeTexture")};ne._CreateMirror=(a,e,t,i)=>{throw Te("MirrorTexture")};ne._CreateRenderTargetTexture=(a,e,t,i,s)=>{throw Te("RenderTargetTexture")};ne.NEAREST_SAMPLINGMODE=1;ne.NEAREST_NEAREST_MIPLINEAR=8;ne.BILINEAR_SAMPLINGMODE=2;ne.LINEAR_LINEAR_MIPNEAREST=11;ne.TRILINEAR_SAMPLINGMODE=3;ne.LINEAR_LINEAR_MIPLINEAR=3;ne.NEAREST_NEAREST_MIPNEAREST=4;ne.NEAREST_LINEAR_MIPNEAREST=5;ne.NEAREST_LINEAR_MIPLINEAR=6;ne.NEAREST_LINEAR=7;ne.NEAREST_NEAREST=1;ne.LINEAR_NEAREST_MIPNEAREST=9;ne.LINEAR_NEAREST_MIPLINEAR=10;ne.LINEAR_LINEAR=2;ne.LINEAR_NEAREST=12;ne.EXPLICIT_MODE=0;ne.SPHERICAL_MODE=1;ne.PLANAR_MODE=2;ne.CUBIC_MODE=3;ne.PROJECTION_MODE=4;ne.SKYBOX_MODE=5;ne.INVCUBIC_MODE=6;ne.EQUIRECTANGULAR_MODE=7;ne.FIXED_EQUIRECTANGULAR_MODE=8;ne.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;ne.CLAMP_ADDRESSMODE=0;ne.WRAP_ADDRESSMODE=1;ne.MIRROR_ADDRESSMODE=2;ne.UseSerializedUrlIfAny=!1;D([B()],ne.prototype,"url",void 0);D([B()],ne.prototype,"uOffset",void 0);D([B()],ne.prototype,"vOffset",void 0);D([B()],ne.prototype,"uScale",void 0);D([B()],ne.prototype,"vScale",void 0);D([B()],ne.prototype,"uAng",void 0);D([B()],ne.prototype,"vAng",void 0);D([B()],ne.prototype,"wAng",void 0);D([B()],ne.prototype,"uRotationCenter",void 0);D([B()],ne.prototype,"vRotationCenter",void 0);D([B()],ne.prototype,"wRotationCenter",void 0);D([B()],ne.prototype,"homogeneousRotationInUVTransform",void 0);D([B()],ne.prototype,"isBlocking",null);ft("BABYLON.Texture",ne);Ae._TextureParser=ne.Parse;class xa{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[E.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[E.PositionKind]=new E(this._scene.getEngine(),e,E.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[E.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!i||(t=t||i._postProcesses.filter(s=>s!=null),!t||t.length===0||!this._scene.postProcessesEnabled)?!1:(t[0].activate(i,e,t!=null),!0)}directRender(e,t=null,i=!1,s=0,n=0,r=!1){var l;const o=this._scene.getEngine();for(let h=0;hh!=null),s.length===0||!this._scene.postProcessesEnabled))return;const o=this._scene.getEngine();for(let h=0,c=s.length;hthis.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t=this.length?-1:t}contains(e){return this.indexOf(e)!==-1}}Vt._GlobalId=0;class Is extends Vt{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?!1:(this.push(e),!0)}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(e.length!==0){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;tt._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(),s=t.getMesh();return i.material&&s.material?i.material.uniqueId-s.material.uniqueId:i.uniqueId-s.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){t===void 0&&(t=e.getMesh()),i===void 0&&(i=e.getMaterial()),i!=null&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t.isEnabled()&&t.isVisible&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(this._particleSystems.length===0)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i0}get is3D(){return this.depth>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){var e,t;return(t=(e=this._textures)==null?void 0:e[0])!=null?t:null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,n){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=s,this._depthStencilTexture=null,this.label=n}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),t!==void 0&&t>=0&&(this._layerIndices[e]=t),i!==void 0&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,n=14,r){var o;return(o=this._depthStencilTexture)==null||o.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=r,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:s,depthTextureFormat:n,label:r},this),this._depthStencilTexture}_shareDepth(e){this.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var t,i,s,n,r,o,l,h;let e=null;if(this._isMulti){const c=this.textures;if(c&&c.length>0){let u=!1,f=c.length,d=-1;const p=c[c.length-1]._source;(p===14||p===12)&&(u=!0,d=c[c.length-1].format,f--);const g=[],_=[],m=[],x=[],I=[],T=[],y=[],b={};for(let M=0;M1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e;if(this._textures)for(let t=0;t<((e=this._textures)==null?void 0:e.length);++t)this._textures[t].dispose();this._textures=null}dispose(e=!1){var t;e||((t=this._depthStencilTexture)==null||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class Zp extends Nh{constructor(e,t,i,s,n){super(e,t,i,s),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=n}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=super._cloneRenderTargetWrapper(),e}_swapRenderTargetWrapper(e){super._swapRenderTargetWrapper(e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,n=14,r){if(this._depthStencilBuffer){const o=this._engine,l=o._currentFramebuffer,h=this._context;o._bindUnboundFramebuffer(this._framebuffer),h.framebufferRenderbuffer(h.FRAMEBUFFER,h.DEPTH_STENCIL_ATTACHMENT,h.RENDERBUFFER,null),h.framebufferRenderbuffer(h.FRAMEBUFFER,h.DEPTH_ATTACHMENT,h.RENDERBUFFER,null),h.framebufferRenderbuffer(h.FRAMEBUFFER,h.STENCIL_ATTACHMENT,h.RENDERBUFFER,null),o._bindUnboundFramebuffer(l),h.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null}return super.createDepthStencilTexture(e,t,i,s,n,r)}shareDepth(e){super.shareDepth(e);const t=this._context,i=this._depthStencilBuffer,s=e._MSAAFramebuffer||e._framebuffer,n=this._engine;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;const r=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;n._bindUnboundFramebuffer(s),t.framebufferRenderbuffer(t.FRAMEBUFFER,r,t.RENDERBUFFER,i),n._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,s=0){var l,h,c,u;if(!e._hardwareTexture)return;const n=this._framebuffer,r=this._engine,o=r._currentFramebuffer;if(r._bindUnboundFramebuffer(n),r.webGLVersion>1){const f=this._context,d=f["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=(h=i!=null?i:(l=this.layerIndices)==null?void 0:l[t])!=null?h:0,f.framebufferTextureLayer(f.FRAMEBUFFER,d,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=(u=i!=null?i:(c=this.faceIndices)==null?void 0:c[t])!=null?u:0,f.framebufferTexture2D(f.FRAMEBUFFER,d,f.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):f.framebufferTexture2D(f.FRAMEBUFFER,d,f.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const f=this._context,d=f["COLOR_ATTACHMENT"+t+"_WEBGL"],p=i!==void 0?f.TEXTURE_CUBE_MAP_POSITIVE_X+i:f.TEXTURE_2D;f.framebufferTexture2D(f.FRAMEBUFFER,d,p,e._hardwareTexture.underlyingResource,s)}r._bindUnboundFramebuffer(o)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var s,n;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=(n=(s=this._attachments)==null?void 0:s.length)!=null?n:this.textures.length;for(let r=0;r1&&(r.format===15?u=t.DEPTH_COMPONENT16:r.format===16?u=t.DEPTH_COMPONENT24:r.format===17||r.format===13?u=t.DEPTH24_STENCIL8:r.format===14?u=t.DEPTH_COMPONENT32F:r.format===18&&(u=t.DEPTH32F_STENCIL8)),r.is2DArray?t.texImage3D(n,0,u,r.width,r.height,i,0,c,h,null):r.is3D?t.texImage3D(n,0,u,r.width,r.height,s,0,c,h,null):t.texImage2D(n,0,u,r.width,r.height,0,c,h,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(r),r};Fe.prototype.updateRenderTargetTextureSampleCount=function(a,e){if(this.webGLVersion<2||!a||!a.texture)return 1;if(a.samples===e)return e;const t=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),a._depthStencilBuffer&&(t.deleteRenderbuffer(a._depthStencilBuffer),a._depthStencilBuffer=null),a._MSAAFramebuffer&&(t.deleteFramebuffer(a._MSAAFramebuffer),a._MSAAFramebuffer=null);const i=a.texture._hardwareTexture;if(i.releaseMSAARenderBuffers(),e>1&&typeof t.renderbufferStorageMultisample=="function"){const s=t.createFramebuffer();if(!s)throw new Error("Unable to create multi sampled framebuffer");a._MSAAFramebuffer=s,this._bindUnboundFramebuffer(a._MSAAFramebuffer);const n=this._createRenderBuffer(a.texture.width,a.texture.height,e,-1,this._getRGBABufferInternalSizedFormat(a.texture.type,a.texture.format,a.texture._useSRGBBuffer),t.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");i.addMSAARenderBuffer(n)}else this._bindUnboundFramebuffer(a._framebuffer);return a.texture.samples=e,a._samples=e,a._depthStencilBuffer=this._setupFramebufferDepthAttachments(a._generateStencilBuffer,a._generateDepthBuffer,a.texture.width,a.texture.height,e),this._bindUnboundFramebuffer(null),e};Fe.prototype._setupDepthStencilTexture=function(a,e,t,i,s,n=1){const r=e.width||e,o=e.height||e,l=e.layers||0,h=e.depth||0;a.baseWidth=r,a.baseHeight=o,a.width=r,a.height=o,a.is2DArray=l>0,a.depth=l||h,a.isReady=!0,a.samples=n,a.generateMipMaps=!1,a.samplingMode=i?2:1,a.type=0,a._comparisonFunction=s;const c=this._gl,u=this._getTextureTarget(a),f=this._getSamplingParameters(a.samplingMode,!1);c.texParameteri(u,c.TEXTURE_MAG_FILTER,f.mag),c.texParameteri(u,c.TEXTURE_MIN_FILTER,f.min),c.texParameteri(u,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(u,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(s===0?(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,515),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,s),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))};Fe.prototype.createRenderTargetCubeTexture=function(a,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,a),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...e};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,(i.type===1&&!this._caps.textureFloatLinearFiltering||i.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(i.samplingMode=1);const s=this._gl,n=new Et(this,5);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,n,!0);const r=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type===1&&!this._caps.textureFloat&&(i.type=0,U.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,r.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,r.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(let l=0;l<6;l++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,0,this._getRGBABufferInternalSizedFormat(i.type,i.format),a,a,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);const o=s.createFramebuffer();return this._bindUnboundFramebuffer(o),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,a,a),i.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),t._framebuffer=o,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer,n.width=a,n.height=a,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=i.generateMipMaps,n.samplingMode=i.samplingMode,n.type=i.type,n.format=i.format,this._internalTexturesCache.push(n),t.setTextures(n),t};Fe.prototype.setDepthStencilTexture=function(a,e,t,i){a!==void 0&&(e&&(this._boundUniforms[a]=e),!t||!t.depthStencilTexture?this._setTexture(a,null,void 0,void 0,i):this._setTexture(a,t,!1,!0,i))};class ln{static GetEffect(e){return e.getPipelineContext===void 0?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){var s;this.effect=e,t!==void 0&&(this.defines=t),i&&((s=this.drawContext)==null||s.reset())}dispose(){var e;(e=this.drawContext)==null||e.dispose()}}const Qp="postprocessVertexShader",Jp="attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";K.ShadersStore[Qp]=Jp;const ta={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class e_{constructor(e,t=ta){var n,r;this._fullscreenViewport=new Qs(0,0,1,1);const i=(n=t.positions)!=null?n:ta.positions,s=(r=t.indices)!=null?r:ta.indices;this.engine=e,this._vertexBuffers={[E.PositionKind]:new E(e,i,E.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(s);for(const o in this._vertexBuffers)this._vertexBuffers[o]._rebuild()})}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return e.renderTarget!==void 0}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=t===null?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[E.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[E.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class t_{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){this.onApplyObservable=new Q;let t;const i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add(()=>{this.effect.setFloat2("scale",1,1)}));const s=e.defines?e.defines.join("\n"):"";this._drawWrapper=new ln(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],i,e.samplerNames,s,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new Pt(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,s,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()}))}dispose(e=!0){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),e&&this.effect.dispose()}}const Uh="passPixelShader",kh="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";K.ShadersStore[Uh]=kh;const Z0={name:Uh,shader:kh};class Ot{static _CreateDumpRenderer(){if(!Ot._DumpToolsEngine){let e,t=null;const i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new Fe(e,!1,i)}catch{e=document.createElement("canvas"),t=new Fe(e,!1,i)}Ce.Instances.pop(),Ce.OnEnginesDisposedObservable.add(r=>{t&&r!==t&&!t.isDisposed&&Ce.Instances.length===0&&Ot.Dispose()}),t.getCaps().parallelShaderCompile=void 0;const s=new e_(t),n=new t_({engine:t,name:Z0.name,fragmentShader:Z0.shader,samplerNames:["textureSampler"]});Ot._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:n}}return Ot._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,n="image/png",r,o){const l=await i.readPixels(0,0,e,t),h=new Uint8Array(l.buffer);Ot.DumpData(e,t,h,s,n,r,!0,void 0,o)}static DumpDataAsync(e,t,i,s="image/png",n,r=!1,o=!1,l){return new Promise(h=>{Ot.DumpData(e,t,i,c=>h(c),s,n,r,o,l)})}static DumpData(e,t,i,s,n="image/png",r,o=!1,l=!1,h){const c=Ot._CreateDumpRenderer();if(c.engine.setSize(e,t,!0),i instanceof Float32Array){const f=new Uint8Array(i.length);let d=i.length;for(;d--;){const p=i[d];f[d]=Math.round(Ye.Clamp(p)*255)}i=f}const u=c.engine.createRawTexture(i,e,t,5,!1,!o,1);c.renderer.setViewport(),c.renderer.applyEffectWrapper(c.wrapper),c.wrapper.effect._bindTexture("textureSampler",u),c.renderer.draw(),l?ee.ToBlob(c.canvas,f=>{const d=new FileReader;d.onload=p=>{const g=p.target.result;s&&s(g)},d.readAsArrayBuffer(f)},n,h):ee.EncodeScreenshotCanvasData(c.canvas,s,n,r,h),u.dispose()}static Dispose(){Ot._DumpToolsEngine&&(Ot._DumpToolsEngine.wrapper.dispose(),Ot._DumpToolsEngine.renderer.dispose(),Ot._DumpToolsEngine.engine.dispose()),Ot._DumpToolsEngine=null}}const i_=()=>{ee.DumpData=Ot.DumpData,ee.DumpDataAsync=Ot.DumpDataAsync,ee.DumpFramebuffer=Ot.DumpFramebuffer};i_();Pt.prototype.setDepthStencilTexture=function(a,e){this._engine.setDepthStencilTexture(this._samplers[a],this._uniforms[a],e,a)};class wi extends ne{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=Eh(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;Array.isArray(e)?i=e:i=[e];for(let s=0;s{var G;const L=this._renderList?this._renderList.length:0;(z===0&&L>0||L===0)&&((G=this.getScene())==null||G.meshes.forEach(H=>{H._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new Q,this.onAfterUnbindObservable=new Q,this.onBeforeRenderObservable=new Q,this.onAfterRenderObservable=new Q,this.onClearObservable=new Q,this.onResizeObservable=new Q,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=v.Zero(),i=this.getScene(),!i)return;const T=this.getScene().getEngine();this._gammaSpace=I,this._coordinatesMode=ne.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=o,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=T.onResizeObservable.add(()=>{}),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=n,this._renderingManager=new Ut(i),this._renderingManager._useSceneAutoClearSetup=!0,!u&&(this._renderTargetOptions={generateMipMaps:s,type:r,format:(w=this._format)!=null?w:void 0,samplingMode:this.samplingMode,generateDepthBuffer:h,generateStencilBuffer:c,samples:p,creationFlags:g,noColorAttachment:_,useSRGBBuffer:m,colorAttachment:x,label:this.name},this.samplingMode===ne.NEAREST_SAMPLINGMODE&&(this.wrapU=ne.CLAMP_ADDRESSMODE,this.wrapV=ne.CLAMP_ADDRESSMODE),d||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=ne.INVCUBIC_MODE,this._textureMatrix=O.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,p!==void 0&&(this.samples=p)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,n=14,r){var o;(o=this._renderTarget)==null||o.createDepthStencilTexture(e,t,i,s,n,r)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;if(e)return e;const t=this._size.depth;return t||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var s;const t=this.isCube;(s=this._renderTarget)==null||s.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e,!1),t?this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,this._renderTargetOptions.samples!==void 0&&(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 c;const s=this.getScene();if(!s)return i;const n=s.getEngine();if(this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let u=0;u{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):(!s||!e.postProcessManager._prepareFrame(this._texture))&&this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,n=null){var h,c,u,f,d,p;const r=this.getScene();if(!r)return;const o=r.getEngine();if((h=o._debugPushGroup)==null||h.call(o,"render to face #".concat(e," layer #").concat(s),1),this._prepareFrame(r,e,s,t),this.is2DArray||this.is3D?(o.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(o.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),o.snapshotRendering&&o.snapshotRenderingMode===1)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||r.clearColor,!0,!0,!0);else{let g=null;const _=this.renderList?this.renderList:r.getActiveMeshes().data,m=this.renderList?this.renderList.length:r.getActiveMeshes().length;this.getCustomRenderList&&(g=this.getCustomRenderList(this.is2DArray||this.is3D?s:e,_,m)),g?this._prepareRenderingManager(g,g.length,n,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(_,m,n,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),g=_);for(const I of r._beforeRenderTargetClearStage)I.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||r.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||r.updateTransformMatrix(!0);for(const I of r._beforeRenderTargetDrawStage)I.action(this,e,s);this._renderingManager.render(this.customRenderFunction,g,this.renderParticles,this.renderSprites);for(const I of r._afterRenderTargetDrawStage)I.action(this,e,s);const x=(u=(c=this._texture)==null?void 0:c.generateMipMaps)!=null?u:!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,(f=this._renderTarget)!=null?f:void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&r.postProcessManager._finalizeFrame(!1,(d=this._renderTarget)!=null?d:void 0,e);for(const I of r._afterRenderTargetPostProcessStage)I.action(this,e,s);this._texture&&(this._texture.generateMipMaps=x),this._doNotChangeAspectRatio||r.updateTransformMatrix(!0),i&&Ot.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),o)}this._unbindFrameBuffer(o,e),this._texture&&this.isCube&&e===5&&o.generateMipMapsForCubemap(this._texture,!0),(p=o._debugPopGroup)==null||p.call(o,1)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new wi(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&&e.customRenderTargets.splice(t,1);for(const s of e.cameras)t=s.customRenderTargets.indexOf(this),t>=0&&s.customRenderTargets.splice(t,1);(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===wi.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=wi.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}wi.REFRESHRATE_RENDER_ONCE=0;wi.REFRESHRATE_RENDER_ONEVERYFRAME=1;wi.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2;ne._CreateRenderTargetTexture=(a,e,t,i,s)=>new wi(a,e,t,i);me.prototype.setTextureFromPostProcess=function(a,e,t){var s;let i=null;e&&(e._forcedOutputTexture?i=e._forcedOutputTexture:e._textures.data[e._currentRenderTextureInd]&&(i=e._textures.data[e._currentRenderTextureInd])),this._bindTexture(a,(s=i==null?void 0:i.texture)!=null?s:null,t)};me.prototype.setTextureFromPostProcessOutput=function(a,e,t){var i,s;this._bindTexture(a,(s=(i=e==null?void 0:e._outputTexture)==null?void 0:i.texture)!=null?s:null,t)};Pt.prototype.setTextureFromPostProcess=function(a,e){this._engine.setTextureFromPostProcess(this._samplers[a],e,a)};Pt.prototype.setTextureFromPostProcessOutput=function(a,e){this._engine.setTextureFromPostProcessOutput(this._samplers[a],e,a)};class it{static RegisterShaderCodeProcessing(e,t){if(!t){delete it._CustomShaderCodeProcessing[e!=null?e:""];return}it._CustomShaderCodeProcessing[e!=null?e:""]=t}static _GetShaderCodeProcessing(e){var t;return(t=it._CustomShaderCodeProcessing[e])!=null?t:it._CustomShaderCodeProcessing[""]}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach(t=>{t.setSamples(this._samples)})}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,s,n,r,o=1,l,h,c=null,u=0,f="postprocess",d,p=!1,g=5,_=0){var I,T,y,b,S,A,M,C,w,P,z,L;this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],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 Vt(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new fe(1,1),this._texelSize=fe.Zero(),this.onActivateObservable=new Q,this.onSizeChangedObservable=new Q,this.onApplyObservable=new Q,this.onBeforeRenderObservable=new Q,this.onAfterRenderObservable=new Q,this.name=e;let m=1,x=null;if(i&&!Array.isArray(i)){const G=i;i=(I=G.uniforms)!=null?I:null,s=(T=G.samplers)!=null?T:null,m=(y=G.size)!=null?y:1,r=(b=G.camera)!=null?b:null,o=(S=G.samplingMode)!=null?S:1,l=G.engine,h=G.reusable,c=(A=G.defines)!=null?A:null,u=(M=G.textureType)!=null?M:0,f=(C=G.vertexUrl)!=null?C:"postprocess",d=G.indexParameters,p=(w=G.blockCompilation)!=null?w:!1,g=(P=G.textureFormat)!=null?P:5,_=(z=G.shaderLanguage)!=null?z:0,x=(L=G.uniformBuffers)!=null?L:null}else n&&(typeof n=="number"?m=n:m={width:n.width,height:n.height});r!=null?(this._camera=r,this._scene=r.getScene(),r.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):l&&(this._engine=l,this._engine.postProcesses.push(this)),this._options=m,this.renderTargetSamplingMode=o||1,this._reusable=h||!1,this._textureType=u,this._textureFormat=g,this._shaderLanguage=_,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=f,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=x||[],this._indexParameters=d,this._drawWrapper=new ln(this._engine),p||this.updateEffect(c)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){this._textures.length==0&&(this._textures=new Vt(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,n,r,o,l){var c,u;const h=it._GetShaderCodeProcessing(this.name);if(h!=null&&h.defineCustomBindings){const f=(c=t==null?void 0:t.slice())!=null?c:[];f.push(...this._parameters);const d=(u=i==null?void 0:i.slice())!=null?u:[];d.push(...this._samplers),e=h.defineCustomBindings(this.name,e,f,d),t=f,i=d}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:o!=null?o:this._vertexUrl,fragment:l!=null?l:this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:e!==null?e:"",fallbacks:null,onCompiled:n!=null?n:null,onError:r!=null?r:null,indexParameters:s||this._indexParameters,processCodeAfterIncludes:h!=null&&h.processCodeAfterIncludes?(f,d)=>h.processCodeAfterIncludes(this.name,f,d):null,processFinalCode:h!=null&&h.processFinalCode?(f,d)=>h.processFinalCode(this.name,f,d):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 i=!1;for(let s=0;s0&&this._textures.reset(),this.width=e,this.height=t;let r=null;if(i){for(let h=0;h{g.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(g,this.samples)}),this._flushTextureCache(),this._renderId++}return f||(f=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/h,l/c),this._engine.bindFramebuffer(f,0,o,l,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(f,0,void 0,void 0,this.forceFullscreenViewport)),(p=(d=this._engine)._debugInsertMarker)==null||p.call(d,"post process ".concat(this.name," input")),this.onActivateObservable.notifyObservers(e),this.autoClear&&(this.alphaMode===0||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),f}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){var e,t;return(t=(e=this._drawWrapper.effect)==null?void 0:e.isReady())!=null?t:!1}apply(){var t,i,s;if(!((t=this._drawWrapper.effect)!=null&&t.isReady()))return null;this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a);let e;return this._shareOutputWithPostProcess?e=this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?e=this._forcedOutputTexture:e=this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e==null?void 0:e.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),(s=(i=it._GetShaderCodeProcessing(this.name))==null?void 0:i.bindCustomBindings)==null||s.call(i,this.name,this._drawWrapper.effect),this._drawWrapper.effect}_disposeTextures(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}this._disposeTextureCache(),this._textures.dispose()}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return this._prePassEffectConfiguration?(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0):!1}dispose(e){e=e||this._camera,this._disposeTextures();let t;if(this._scene&&(t=this._scene.postProcesses.indexOf(this),t!==-1&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const i=this._parentContainer.postProcesses.indexOf(this);i>-1&&this._parentContainer.postProcesses.splice(i,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),t!==-1&&this._engine.postProcesses.splice(t,1),!!e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),t===0&&e._postProcesses.length>0){const i=this._camera._getFirstPostProcess();i&&i.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){const e=Ae.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=it.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const s=ms(e.customType);if(!s||!s._Parse)return null;const n=t?t.getCameraById(e.cameraId):null;return s._Parse(e,n,t,i)}static _Parse(e,t,i,s){return Ae.Parse(()=>new it(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat),e,i,s)}}it._CustomShaderCodeProcessing={};D([B()],it.prototype,"uniqueId",void 0);D([B()],it.prototype,"name",void 0);D([B()],it.prototype,"width",void 0);D([B()],it.prototype,"height",void 0);D([B()],it.prototype,"renderTargetSamplingMode",void 0);D([to()],it.prototype,"clearColor",void 0);D([B()],it.prototype,"autoClear",void 0);D([B()],it.prototype,"forceAutoClearInAlphaMode",void 0);D([B()],it.prototype,"alphaMode",void 0);D([B()],it.prototype,"alphaConstants",void 0);D([B()],it.prototype,"enablePixelPerfectMode",void 0);D([B()],it.prototype,"forceFullscreenViewport",void 0);D([B()],it.prototype,"scaleMode",void 0);D([B()],it.prototype,"alwaysForcePOT",void 0);D([B("samples")],it.prototype,"_samples",void 0);D([B()],it.prototype,"adaptScaleToCurrentViewport",void 0);ft("BABYLON.PostProcess",it);const s_="passCubePixelShader",n_="varying vec2 vUV;uniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";K.ShadersStore[s_]=n_;class Bn extends it{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,n,r,o=0,l=!1){super(e,"pass",null,null,t,i,s,n,r,void 0,o,void 0,null,l)}static _Parse(e,t,i,s){return Ae.Parse(()=>new Bn(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,s)}}ft("BABYLON.PassPostProcess",Bn);me._RescalePostProcessFactory=a=>new Bn("rescale",1,null,2,a,!1,0);const r_="lodPixelShader",a_="#extension GL_EXT_shader_texture_lod : enable\nprecision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform sampler2D textureSampler;uniform float lod;uniform vec2 texSize;uniform bool gamma;void main(void)\n{gl_FragColor=textureLod(textureSampler,vUV,lod);if (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";K.ShadersStore[r_]=a_;const o_="lodCubePixelShader",l_="precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform bool gamma;void main(void)\n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod);\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod);\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod);\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod);\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod);\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod);\n#endif\nif (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";K.ShadersStore[o_]=l_;function h_(a,e,t,i,s,n,r,o){const l=e.getEngine();return e.isReady=!1,s=s!=null?s:e.samplingMode,i=i!=null?i:e.type,n=n!=null?n:e.format,r=r!=null?r:e.width,o=o!=null?o:e.height,i===-1&&(i=0),new Promise(h=>{const c=new it("postprocess",a,null,null,1,null,s,l,!1,void 0,i,void 0,null,!1,n);c.externalTextureSamplerBinding=!0;const u=l.createRenderTargetTexture({width:r,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:i,format:n});c.getEffect().executeWhenCompiled(()=>{c.onApply=f=>{f._bindTexture("textureSampler",e),f.setFloat2("scale",1,1)},t.postProcessManager.directRender([c],u,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(e),c&&c.dispose(),u._swapAndDie(e),e.type=i,e.format=5,e.isReady=!0,h(e)})})}function c_(a){const e=(a&32768)>>15,t=(a&31744)>>10,i=a&1023;return t===0?(e?-1:1)*Math.pow(2,-14)*(i/Math.pow(2,10)):t==31?i?NaN:(e?-1:1)*(1/0):(e?-1:1)*Math.pow(2,t-15)*(1+i/Math.pow(2,10))}class dr{static _IsGPUBuffer(e){return e.underlyingResource===void 0}static _FlagsToString(e,t=""){let i=t;for(let s=0;s<=9;++s)e&1<c;)this._device.queue.writeBuffer(r,t+u,i.buffer,o+u,c),u+=c;this._device.queue.writeBuffer(r,t+u,i.buffer,o+u,n-u)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const s=new Uint16Array(t);for(;e--;)i[e]=c_(s[e]);return i}readDataFromBuffer(e,t,i,s,n,r,o=0,l=0,h=null,c=!0,u=!1){const f=o===1?2:o===2?1:0,d=this._engine.uniqueId;return new Promise((p,g)=>{e.mapAsync(1,l,t).then(()=>{const _=e.getMappedRange(l,t);let m=h;if(u)m===null?m=_a(o,t,!0,_):m=_a(o,m.buffer,void 0,_);else if(m===null)switch(f){case 0:m=new Uint8Array(t),m.set(new Uint8Array(_));break;case 1:m=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,_);break;case 2:m=new Float32Array(t/4),m.set(new Float32Array(_));break}else switch(f){case 0:m=new Uint8Array(m.buffer),m.set(new Uint8Array(_));break;case 1:m=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,_,h);break;case 2:m=new Float32Array(m.buffer),m.set(new Float32Array(_));break}if(n!==r){f===1&&!u&&(n*=2,r*=2);const x=new Uint8Array(m.buffer);let I=n,T=0;for(let y=1;y{this._engine.isDisposed||this._engine.uniqueId!==d?p(new Uint8Array):g(_)})})}releaseBuffer(e){return dr._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,e.references===0?(this._deferredReleaseBuffers.push(e.underlyingResource),!0):!1)}destroyDeferredBuffers(){for(let e=0;e1?4:1;return u_[e.samplingMode]+f_[(e._comparisonFunction||514)-512+1]+d_[e.samplingMode]+(((s=e._cachedWrapU)!=null?s:1)<<8)+(((n=e._cachedWrapV)!=null?n:1)<<10)+(((r=e._cachedWrapR)!=null?r:1)<<12)+((e.useMipMaps?1:0)<<14)+(t<<15)}static _GetSamplerFilterDescriptor(e,t){let i,s,n,r,o;const l=e.useMipMaps;switch(e.samplingMode){case 11:i="linear",s="linear",n="nearest",l||(r=o=0);break;case 3:case 3:i="linear",s="linear",l?n="linear":(n="nearest",r=o=0);break;case 8:i="nearest",s="nearest",l?n="linear":(n="nearest",r=o=0);break;case 4:i="nearest",s="nearest",n="nearest",l||(r=o=0);break;case 5:i="nearest",s="linear",n="nearest",l||(r=o=0);break;case 6:i="nearest",s="linear",l?n="linear":(n="nearest",r=o=0);break;case 7:i="nearest",s="linear",n="nearest",r=o=0;break;case 1:case 1:i="nearest",s="nearest",n="nearest",r=o=0;break;case 9:i="linear",s="nearest",n="nearest",l||(r=o=0);break;case 10:i="linear",s="nearest",l?n="linear":(n="nearest",r=o=0);break;case 2:case 2:i="linear",s="linear",n="nearest",r=o=0;break;case 12:i="linear",s="nearest",n="nearest",r=o=0;break;default:i="nearest",s="nearest",n="nearest",r=o=0;break}return t>1&&(r!==0||o!==0)&&n!=="nearest"?{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",anisotropyEnabled:!0}:{magFilter:i,minFilter:s,mipmapFilter:n,lodMinClamp:r,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return"repeat";case 0:return"clamp-to-edge";case 2:return"mirror-repeat"}return"repeat"}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){const i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,s=this._GetSamplerFilterDescriptor(e,i);return{label:t,...s,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?Ms.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:s.anisotropyEnabled?i:1}}static GetCompareFunction(e){switch(e){case 519:return"always";case 514:return"equal";case 516:return"greater";case 518:return"greater-equal";case 513:return"less";case 515:return"less-equal";case 512:return"never";case 517:return"not-equal";default:return"less"}}getSampler(e,t=!1,i=0,s){if(this.disabled)return this._device.createSampler(Ms._GetSamplerDescriptor(e,s));t?i=0:i===0&&(i=Ms.GetSamplerHashCode(e));let n=t?void 0:this._samplers[i];return n||(n=this._device.createSampler(Ms._GetSamplerDescriptor(e,s)),t||(this._samplers[i]=n)),n}}const p_={[E.PositionKind]:!0,[E.NormalKind]:!0,[E.TangentKind]:!0,[E.UVKind]:!0,[E.UV2Kind]:!0,[E.UV3Kind]:!0,[E.UV4Kind]:!0,[E.UV5Kind]:!0,[E.UV6Kind]:!0,[E.ColorKind]:!0,[E.ColorInstanceKind]:!0,[E.MatricesIndicesKind]:!0,[E.MatricesWeightsKind]:!0,[E.MatricesIndicesExtraKind]:!0,[E.MatricesWeightsExtraKind]:!0};function __(a){switch(a){case E.BYTE:case E.SHORT:case E.INT:case E.FLOAT:return!0;case E.UNSIGNED_BYTE:case E.UNSIGNED_SHORT:case E.UNSIGNED_INT:return!1;default:throw new Error("Invalid type '".concat(a,"'"))}}function g_(a,e){const t=e.getEngine(),i=e._pipelineContext;if(!(i!=null&&i.vertexBufferKindToType))return;let s=null;for(const n in a){const r=a[n];if(!r||!p_[n])continue;const o=r.normalized?E.FLOAT:r.type,l=i.vertexBufferKindToType[n];(o!==E.FLOAT&&l===void 0||l!==void 0&&l!==o)&&(s||(s=t._getShaderProcessingContext(e.shaderLanguage)),i.vertexBufferKindToType[n]=o,o!==E.FLOAT&&(s.vertexBufferKindToNumberOfComponents[n]=E.DeduceStride(n),__(o)&&(s.vertexBufferKindToNumberOfComponents[n]*=-1)))}if(s){const n=t._caps.parallelShaderCompile;t._caps.parallelShaderCompile=void 0,e._processShaderCode(null,t._features._checkNonFloatVertexBuffersDontRecreatePipelineContext,s),t._caps.parallelShaderCompile=n}}var dt;(function(a){a[a.StencilReadMask=0]="StencilReadMask",a[a.StencilWriteMask=1]="StencilWriteMask",a[a.DepthBias=2]="DepthBias",a[a.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",a[a.DepthStencilState=4]="DepthStencilState",a[a.MRTAttachments1=5]="MRTAttachments1",a[a.MRTAttachments2=6]="MRTAttachments2",a[a.RasterizationState=7]="RasterizationState",a[a.ColorStates=8]="ColorStates",a[a.ShaderStage=9]="ShaderStage",a[a.TextureStage=10]="TextureStage",a[a.VertexState=11]="VertexState",a[a.NumStates=12]="NumStates"})(dt||(dt={}));const jn={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},ks={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class rt{constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=["bgra8unorm"],this.setColorFormat("bgra8unorm"),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat("depth24plus-stencil8"),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,s=0){if(i=Ve.GetSample(i),this.disabled){const r=rt._GetTopology(e);return this._setVertexState(t),this._setTextureState(s),this._parameter.pipeline=this._createRenderPipeline(t,r,i),rt.NumCacheMiss++,rt._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(s),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,rt.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return rt.NumCacheHitWithHash++,this._parameter.pipeline;const n=rt._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,n,i),this._setRenderPipeline(this._parameter),rt.NumCacheMiss++,rt._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){rt.NumPipelineCreationLastFrame=rt._NumPipelineCreationCurrentFrame,rt._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,s,n,r,o,l){this._depthWriteEnabled=o,this._depthTestEnabled=r,this._depthCompare=(l!=null?l:519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(s),this.setDepthBias(n)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[dt.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[dt.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=Gi[e!=null?e:""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const i=[0,0];let s=0,n=0,r=0;for(let h=0;h=32&&(n=0,s++)}this._mrtFormats.length=r,(this._mrtAttachments1!==i[0]||this._mrtAttachments2!==i[1])&&(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[dt.MRTAttachments1]=i[0],this._states[dt.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=e===void 0?0:Gi[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(e!=null?e:519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(e!=null?e:519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=e===null?1:ks[e]}setStencilPassOp(e){this._stencilFrontPassOp=e===null?2:ks[e]}setStencilFailOp(e){this._stencilFrontFailOp=e===null?1:ks[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[dt.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[dt.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,s,n,r,o){this._stencilEnabled=e,this._stencilFrontCompare=(t!=null?t:519)-512,this._stencilFrontDepthFailOp=i===null?1:ks[i],this._stencilFrontPassOp=s===null?2:ks[s],this._stencilFrontFailOp=n===null?1:ks[n],this.setStencilReadMask(r),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:return"triangle-list";case 2:return"point-list";case 1:return"line-list";case 3:return"point-list";case 4:return"line-list";case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return"line-strip";case 7:return"triangle-strip";case 8:throw"TriangleFan is an unsupported fillmode in WebGPU";default:return"triangle-list"}}static _GetAphaBlendOperation(e){switch(e){case 32774:return"add";case 32778:return"subtract";case 32779:return"reverse-subtract";case 32775:return"min";case 32776:return"max";default:return"add"}}static _GetAphaBlendFactor(e){switch(e){case 0:return"zero";case 1:return"one";case 768:return"src";case 769:return"one-minus-src";case 770:return"src-alpha";case 771:return"one-minus-src-alpha";case 772:return"dst-alpha";case 773:return"one-minus-dst-alpha";case 774:return"dst";case 775:return"one-minus-dst";case 776:return"src-alpha-saturated";case 32769:return"constant";case 32770:return"one-minus-constant";case 32771:return"constant";case 32772:return"one-minus-constant";default:return"one"}}static _GetCompareFunction(e){switch(e){case 0:return"never";case 1:return"less";case 2:return"equal";case 3:return"less-equal";case 4:return"greater";case 5:return"not-equal";case 6:return"greater-equal";case 7:return"always"}return"never"}static _GetStencilOpFunction(e){switch(e){case 0:return"zero";case 1:return"keep";case 2:return"replace";case 3:return"increment-clamp";case 4:return"decrement-clamp";case 5:return"invert";case 6:return"increment-wrap";case 7:return"decrement-wrap"}return"keep"}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,s=e.getSize();switch(t){case E.BYTE:switch(s){case 1:case 2:return i?"snorm8x2":"sint8x2";case 3:case 4:return i?"snorm8x4":"sint8x4"}break;case E.UNSIGNED_BYTE:switch(s){case 1:case 2:return i?"unorm8x2":"uint8x2";case 3:case 4:return i?"unorm8x4":"uint8x4"}break;case E.SHORT:switch(s){case 1:case 2:return i?"snorm16x2":"sint16x2";case 3:case 4:return i?"snorm16x4":"sint16x4"}break;case E.UNSIGNED_SHORT:switch(s){case 1:case 2:return i?"unorm16x2":"uint16x2";case 3:case 4:return i?"unorm16x4":"uint16x4"}break;case E.INT:switch(s){case 1:return"sint32";case 2:return"sint32x2";case 3:return"sint32x3";case 4:return"sint32x4"}break;case E.UNSIGNED_INT:switch(s){case 1:return"uint32";case 2:return"uint32x2";case 3:return"uint32x3";case 4:return"uint32x4"}break;case E.FLOAT:switch(s){case 1:return"float32";case 2:return"float32x2";case 3:return"float32x3";case 4:return"float32x4"}break}throw new Error("Invalid Format '".concat(e.getKind(),"' - type=").concat(t,", normalized=").concat(i,", size=").concat(s))}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:rt._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:rt._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:rt._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:rt._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:rt._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:rt._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[dt.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace,s=this._cullEnabled?this._cullFace:0,n=this._clampDepth?1:0,r=this._alphaToCoverageEnabled?1:0,o=i-1+(s<<1)+(n<<3)+(r<<4)+(e<<5)+(t<<8);this._rasterizationState!==o&&(this._rasterizationState=o,this._states[dt.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=((this._alphaBlendFuncParams[0]===null?2:jn[this._alphaBlendFuncParams[0]])<<0)+((this._alphaBlendFuncParams[1]===null?2:jn[this._alphaBlendFuncParams[1]])<<4)+((this._alphaBlendFuncParams[2]===null?2:jn[this._alphaBlendFuncParams[2]])<<8)+((this._alphaBlendFuncParams[3]===null?2:jn[this._alphaBlendFuncParams[3]])<<12)+((this._alphaBlendEqParams[0]===null?1:this._alphaBlendEqParams[0]-32773)<<16)+((this._alphaBlendEqParams[1]===null?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[dt.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.ColorStates))}_setDepthStencilState(){const e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[dt.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,dt.DepthStencilState))}_setVertexState(e){var h,c;const t=this._statesLength;let i=dt.VertexState;const s=e._pipelineContext,n=s.shaderProcessingContext.attributeNamesFromEffect,r=s.shaderProcessingContext.attributeLocationsFromEffect;let o,l=0;for(let u=0;u0)for(let _=0;_=this._video.HAVE_CURRENT_DATA}dispose(){}}class Rr{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=Rr._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],s=-1;i?s=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?Ms.GetSamplerHashCode(t):0;const n=s!==i.hashCode;n&&this.updateId++,this.isDirty||(this.isDirty=n)}setTexture(e,t){var r,o,l;let i=this.textures[e],s=-1;i?s=(o=(r=i.texture)==null?void 0:r.uniqueId)!=null?o:-1:this.textures[e]=i={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},i.isExternalTexture&&this._numExternalTextures--,i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(i.isFloatOrDepthTexture=t.type===1||t.format>=13&&t.format<=18,i.isExternalTexture=Vh.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const n=s!==((l=t==null?void 0:t.uniqueId)!=null?l:-1);n&&this.updateId++,this.isDirty||(this.isDirty=n)}}Rr._Counter=0;class Pr{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,We.CopyDst|We.Indirect|We.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=Pr._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){var i;this._isDirty||(this._isDirty=(t==null?void 0:t.uniqueId)!==((i=this.buffers[e])==null?void 0:i.uniqueId)),this.buffers[e]=t}setIndirectData(e,t,i){t===this._currentInstanceCount||!this.indirectDrawBuffer||!this._indirectDrawData||(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}Pr._Counter=0;class _n{constructor(){this.values={}}}class Ke{static get Statistics(){return{totalCreated:Ke.NumBindGroupsCreatedTotal,lastFrameCreated:Ke.NumBindGroupsCreatedLastFrame,lookupLastFrame:Ke.NumBindGroupsLookupLastFrame,noLookupLastFrame:Ke.NumBindGroupsNoLookupLastFrame}}static ResetCache(){Ke._Cache=new _n,Ke.NumBindGroupsCreatedTotal=0,Ke.NumBindGroupsCreatedLastFrame=0,Ke.NumBindGroupsLookupLastFrame=0,Ke.NumBindGroupsNoLookupLastFrame=0,Ke._NumBindGroupsCreatedCurrentFrame=0,Ke._NumBindGroupsLookupCurrentFrame=0,Ke._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){Ke.NumBindGroupsCreatedLastFrame=Ke._NumBindGroupsCreatedCurrentFrame,Ke.NumBindGroupsLookupLastFrame=Ke._NumBindGroupsLookupCurrentFrame,Ke.NumBindGroupsNoLookupLastFrame=Ke._NumBindGroupsNoLookupCurrentFrame,Ke._NumBindGroupsCreatedCurrentFrame=0,Ke._NumBindGroupsLookupCurrentFrame=0,Ke._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var l,h,c,u,f,d,p,g,_,m;let s,n=Ke._Cache;const r=this.disabled||i.forceBindGroupCreation;if(!r){if(!t.isDirty(i.updateId)&&!i.isDirty)return Ke._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const x of e.shaderProcessingContext.bufferNames){const I=(h=(l=t.buffers[x])==null?void 0:l.uniqueId)!=null?h:0;let T=n.values[I];T||(T=new _n,n.values[I]=T),n=T}for(const x of e.shaderProcessingContext.samplerNames){const I=(u=(c=i.samplers[x])==null?void 0:c.hashCode)!=null?u:0;let T=n.values[I];T||(T=new _n,n.values[I]=T),n=T}for(const x of e.shaderProcessingContext.textureNames){const I=(p=(d=(f=i.textures[x])==null?void 0:f.texture)==null?void 0:d.uniqueId)!=null?p:0;let T=n.values[I];T||(T=new _n,n.values[I]=T),n=T}s=n.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,s)return t.bindGroups=s,Ke._NumBindGroupsLookupCurrentFrame++,s;s=[],t.bindGroups=s,r||(n.bindGroups=s),Ke.NumBindGroupsCreatedTotal++,Ke._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let x=0;x":z),", materialContext.uniqueId=").concat(i.uniqueId),50);continue}T[b].resource=this._cacheSampler.getSampler(w,!1,C.hashCode,w.label)}else U.Error('Sampler "'.concat(M,'" could not be bound. entry=').concat(JSON.stringify(S),", materialContext=").concat(JSON.stringify(i,(w,P)=>w==="texture"||w==="sampler"?"":P)),50)}else if(S.texture||S.storageTexture){const C=i.textures[M];if(C){if(this._engine.dbgSanityChecks&&C.texture===null){U.Error("Trying to bind a null texture! entry=".concat(JSON.stringify(S),", bindingInfo=").concat(JSON.stringify(C,(P,z)=>P==="texture"?"":z),", materialContext.uniqueId=").concat(i.uniqueId),50);continue}const w=C.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!w||S.texture&&!w.view||S.storageTexture&&!w.viewForWriting)){U.Error("Trying to bind a null gpu texture or view! entry=".concat(JSON.stringify(S),", name=").concat(M,", bindingInfo=").concat(JSON.stringify(C,(P,z)=>P==="texture"?"":z),", isReady=").concat((_=C.texture)==null?void 0:_.isReady,", materialContext.uniqueId=").concat(i.uniqueId),50);continue}T[b].resource=S.storageTexture?w.viewForWriting:w.view}else U.Error('Texture "'.concat(M,'" could not be bound. entry=').concat(JSON.stringify(S),", materialContext=").concat(JSON.stringify(i,(w,P)=>w==="texture"||w==="sampler"?"":P)),50)}else if(S.externalTexture){const C=i.textures[M];if(C){if(this._engine.dbgSanityChecks&&C.texture===null){U.Error("Trying to bind a null external texture! entry=".concat(JSON.stringify(S),", name=").concat(M,", bindingInfo=").concat(JSON.stringify(C,(P,z)=>P==="texture"?"":z),", materialContext.uniqueId=").concat(i.uniqueId),50);continue}const w=C.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!w){U.Error("Trying to bind a null gpu external texture! entry=".concat(JSON.stringify(S),", name=").concat(M,", bindingInfo=").concat(JSON.stringify(C,(P,z)=>P==="texture"?"":z),", isReady=").concat((m=C.texture)==null?void 0:m.isReady,", materialContext.uniqueId=").concat(i.uniqueId),50);continue}T[b].resource=this._device.importExternalTexture({source:w})}else U.Error('Texture "'.concat(M,'" could not be bound. entry=').concat(JSON.stringify(S),", materialContext=").concat(JSON.stringify(i,(w,P)=>w==="texture"||w==="sampler"?"":P)),50)}else if(S.buffer){const C=t.buffers[M];if(C){const w=C.underlyingResource;T[b].resource.buffer=w,T[b].resource.size=C.capacity}else U.Error("Can't find buffer \"".concat(M,'". entry=').concat(JSON.stringify(S),", buffers=").concat(JSON.stringify(t.buffers),", drawContext.uniqueId=").concat(t.uniqueId),50)}}const y=o[x];s[x]=this._device.createBindGroup({layout:y,entries:T})}return s}}Ke.NumBindGroupsCreatedTotal=0;Ke.NumBindGroupsCreatedLastFrame=0;Ke.NumBindGroupsLookupLastFrame=0;Ke.NumBindGroupsNoLookupLastFrame=0;Ke._Cache=new _n;Ke._NumBindGroupsCreatedCurrentFrame=0;Ke._NumBindGroupsLookupCurrentFrame=0;Ke._NumBindGroupsNoLookupCurrentFrame=0;const x_="clearQuadVertexShader",b_="uniform depthValue: f32;const pos=array(\nvec2f(-1.0,1.0),\nvec2f(1.0,1.0),\nvec2f(-1.0,-1.0),\nvec2f(1.0,-1.0)\n);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.position=vec4f(pos[input.vertexIndex],uniforms.depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";K.ShadersStoreWGSL[x_]=b_;const y_="clearQuadPixelShader",T_="uniform color: vec4f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;}\n";K.ShadersStoreWGSL[y_]=T_;class S_{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new Mi(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"],void 0,void 0,void 0,void 0,void 0,void 0,1)}clear(e,t,i,s,n=1){var _,m;let r,o=null,l;const h=!!this._engine._currentRenderTarget;if(e)r=e;else{let x=0;this._keyTemp.length=0;for(let T=0;T1?2**36:0)+I*2**37,l=this._keyTemp.join("_"),o=this._bundleCache[l],o)return o;r=this._device.createRenderBundleEncoder({label:"clearQuadRenderBundle",colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:Ve.GetSample(n)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!s&&!!this._depthTextureFormat&&Ve.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(s?255:0),this._cacheRenderPipeline.setStencilCompare(s?519:512),this._cacheRenderPipeline.setStencilPassOp(s?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const c=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,n),u=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),u.uniformBuffer.update();const f=h?this._engine._ubInvertY:this._engine._ubDontInvertY,d=u.uniformBuffer.getBuffer(),p=d.uniqueId+"-"+f.uniqueId;let g=this._bindGroups[p];if(!g){const x=u.bindGroupLayouts[0];g=this._bindGroups[p]=[],g.push(this._device.createBindGroup({label:"clearQuadBindGroup0-".concat(p),layout:x[0],entries:[]})),ii._SimplifiedKnownBindings||g.push(this._device.createBindGroup({label:"clearQuadBindGroup1-".concat(p),layout:x[1],entries:[]})),g.push(this._device.createBindGroup({label:"clearQuadBindGroup".concat(ii._SimplifiedKnownBindings?1:2,"-").concat(p),layout:x[ii._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:f.underlyingResource,size:f.capacity}},{binding:1,resource:{buffer:d.underlyingResource,size:d.capacity}}]}))}r.setPipeline(c);for(let x=0;x{const n=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,n},n=>{if(this._engine.isDisposed||this._engine.uniqueId!==s)return null;throw n})}async readValue(e=0){const t=this._getBuffer(e,1);if(t===null)return null;const i=this._engine.uniqueId;return t.mapAsync(1).then(()=>{const s=new BigUint64Array(t.getMappedRange()),n=Number(s[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,n},s=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw s})}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(t===null)return null;const i=this._engine.uniqueId;return t.mapAsync(1).then(()=>{const s=new BigUint64Array(t.getMappedRange()),n=Number(s[1]-s[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,n},s=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw s})}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{t!==null&&t>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(t,!0)),this._measureDurationState=0}))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;const i=this._engine.frameId;this._measureDuration.stopPass(e).then(s=>{t._addDuration(i,s!==null&&s>0?s:0)})}dispose(){var e;(e=this._measureDuration)==null||e.dispose()}}class I_{constructor(e,t,i,s=2,n){this._count=s,this._querySet=new Gh(e,s,"timestamp",t,i,!0,n)}start(e){var t;(t=e.writeTimestamp)==null||t.call(e,this._querySet.querySet,0)}async stop(e){var t;return(t=e.writeTimestamp)==null||t.call(e,this._querySet.querySet,1),e.writeTimestamp?this._querySet.readTwoValuesAndSubtract(0):0}startPass(e,t){if(t+3>this._count)throw new Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}}async stopPass(e){return this._querySet.readTwoValuesAndSubtract(e+2)}dispose(){this._querySet.dispose()}}class A_{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;const t=this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet!==void 0;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,s=50,n=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=n,this._allocateNewIndices(s)}createQuery(){this._availableIndices.length===0&&this._allocateNewIndices();const e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e}))}_allocateNewIndices(e){e=e!=null?e:this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose,1e3)}dispose(){var e;(e=this._querySet)==null||e.dispose(),this._availableIndices.length=0}}class wr{get code(){return this._sourceCode}constructor(e,t=20){this.debug=!1,this._sourceCode=e,this._numMaxIterations=t,this._functionDescr=[],this.inlineToken="#define inline"}processCode(){this.debug&&U.Log("Start inlining process (code size=".concat(this._sourceCode.length,")...")),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&U.Log("End of inlining process.")}_collectFunctions(){let e=0;for(;e=0&&d.push(m.substring(x+1))}n!=="void"&&d.push("return"),this._functionDescr.push({name:r,type:n,parameters:d,body:u,callIndex:0}),e=c+1;const p=t>0?this._sourceCode.substring(0,t):"",g=c+1=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:s,parameters:n,body:r}=t;let o=0;for(;o{const c=h[0];return ea(e.charAt(c-1))||ea(e.charAt(c+r))?t[s]:o})}return e}}wr._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;class ti{async initTwgsl(e){if(!ti._Twgsl)return e=e||{},e={...ti._TWgslDefaultOptions,...e},e.twgsl?(ti._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await ee.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(ti._Twgsl=await self.twgsl(ee.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=ti._Twgsl.convertSpirV2WGSL(e,ti.DisableUniformityAnalysis||t);return ti.ShowWGSLShaderCode&&(U.Log(i),U.Log("***********************************************")),ti.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}ti._TWgslDefaultOptions={jsPath:"".concat(ee._DefaultCdnUrl,"/twgsl/twgsl.js"),wasmPath:"".concat(ee._DefaultCdnUrl,"/twgsl/twgsl.wasm")};ti.ShowWGSLShaderCode=!1;ti.DisableUniformityAnalysis=!1;ti._Twgsl=null;class C_{constructor(e,t,i){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._allBundleLists.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endRenderPass(e){if(!this._record&&!this._play)return!1;let t;if(this._record)t=this._bundleList.clone(),this._allBundleLists.push(t),this._bundleList.reset();else{if(this._playBundleListIndex>=this._allBundleLists.length)throw new Error("Invalid playBundleListIndex! Your snapshot is no longer valid for the current frame, you should recreate a new one. playBundleListIndex=".concat(this._playBundleListIndex,", allBundleLists.length=").concat(this._allBundleLists.length,"}"));t=this._allBundleLists[this._playBundleListIndex++]}return t.run(e),this._mode===1&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this.enabled=!1,this.enabled=!0}}const dn=(()=>{const a=new Uint8Array(4),e=new Uint32Array(a.buffer);return!!((e[0]=1)&a[0])})();Object.defineProperty(E.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0});Object.defineProperty(E.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0});Object.defineProperty(E.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0});E.prototype._rebuild=function(){var a,e;(a=this._buffer)==null||a._rebuild(),(e=this._alignedBuffer)==null||e._rebuild()};E.prototype.dispose=function(){var a;this._ownsBuffer&&this._buffer.dispose(),(a=this._alignedBuffer)==null||a.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0};E.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer};E.prototype._alignBuffer=function(){var u,f;const a=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4===0&&this.byteOffset%4===0||!a)return;const e=E.GetTypeByteLength(this.type),t=this.byteStride+3&-4,i=t/e,s=this._maxVerticesCount,r=s*t/e;let o;if(Array.isArray(a)){const d=new Float32Array(a);o=new DataView(d.buffer,d.byteOffset,d.byteLength)}else a instanceof ArrayBuffer?o=new DataView(a,0,a.byteLength):o=new DataView(a.buffer,a.byteOffset,a.byteLength);let l;this.type===E.BYTE?l=new Int8Array(r):this.type===E.UNSIGNED_BYTE?l=new Uint8Array(r):this.type===E.SHORT?l=new Int16Array(r):this.type===E.UNSIGNED_SHORT?l=new Uint16Array(r):this.type===E.INT?l=new Int32Array(r):this.type===E.UNSIGNED_INT?l=new Uint32Array(r):l=new Float32Array(r);const h=this.getSize();let c=this.byteOffset;for(let d=0;d1,a=>a.y,a=>a.z,a=>a.x,a=>a.x*a.y,a=>a.y*a.z,a=>3*a.z*a.z-1,a=>a.x*a.z,a=>a.x*a.x-a.y*a.y],$i=(a,e)=>ki[a]*P_[a](e),ji=[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 _r{constructor(){this.preScaled=!1,this.l00=v.Zero(),this.l1_1=v.Zero(),this.l10=v.Zero(),this.l11=v.Zero(),this.l2_2=v.Zero(),this.l2_1=v.Zero(),this.l20=v.Zero(),this.l21=v.Zero(),this.l22=v.Zero()}addLight(e,t,i){N.Vector3[0].set(t.r,t.g,t.b);const s=N.Vector3[0],n=N.Vector3[1];s.scaleToRef(i,n),n.scaleToRef($i(0,e),N.Vector3[2]),this.l00.addInPlace(N.Vector3[2]),n.scaleToRef($i(1,e),N.Vector3[2]),this.l1_1.addInPlace(N.Vector3[2]),n.scaleToRef($i(2,e),N.Vector3[2]),this.l10.addInPlace(N.Vector3[2]),n.scaleToRef($i(3,e),N.Vector3[2]),this.l11.addInPlace(N.Vector3[2]),n.scaleToRef($i(4,e),N.Vector3[2]),this.l2_2.addInPlace(N.Vector3[2]),n.scaleToRef($i(5,e),N.Vector3[2]),this.l2_1.addInPlace(N.Vector3[2]),n.scaleToRef($i(6,e),N.Vector3[2]),this.l20.addInPlace(N.Vector3[2]),n.scaleToRef($i(7,e),N.Vector3[2]),this.l21.addInPlace(N.Vector3[2]),n.scaleToRef($i(8,e),N.Vector3[2]),this.l22.addInPlace(N.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(ji[0]),this.l1_1.scaleInPlace(ji[1]),this.l10.scaleInPlace(ji[2]),this.l11.scaleInPlace(ji[3]),this.l2_2.scaleInPlace(ji[4]),this.l2_1.scaleInPlace(ji[5]),this.l20.scaleInPlace(ji[6]),this.l21.scaleInPlace(ji[7]),this.l22.scaleInPlace(ji[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(ki[0]),this.l1_1.scaleInPlace(ki[1]),this.l10.scaleInPlace(ki[2]),this.l11.scaleInPlace(ki[3]),this.l2_2.scaleInPlace(ki[4]),this.l2_1.scaleInPlace(ki[5]),this.l20.scaleInPlace(ki[6]),this.l21.scaleInPlace(ki[7]),this.l22.scaleInPlace(ki[8])}updateFromArray(e){return v.FromArrayToRef(e[0],0,this.l00),v.FromArrayToRef(e[1],0,this.l1_1),v.FromArrayToRef(e[2],0,this.l10),v.FromArrayToRef(e[3],0,this.l11),v.FromArrayToRef(e[4],0,this.l2_2),v.FromArrayToRef(e[5],0,this.l2_1),v.FromArrayToRef(e[6],0,this.l20),v.FromArrayToRef(e[7],0,this.l21),v.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return v.FromFloatsToRef(e[0],e[1],e[2],this.l00),v.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),v.FromFloatsToRef(e[6],e[7],e[8],this.l10),v.FromFloatsToRef(e[9],e[10],e[11],this.l11),v.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),v.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),v.FromFloatsToRef(e[18],e[19],e[20],this.l20),v.FromFloatsToRef(e[21],e[22],e[23],this.l21),v.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new _r().updateFromArray(e)}static FromPolynomial(e){const t=new _r;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 gr{constructor(){this.x=v.Zero(),this.y=v.Zero(),this.z=v.Zero(),this.xx=v.Zero(),this.yy=v.Zero(),this.zz=v.Zero(),this.xy=v.Zero(),this.yz=v.Zero(),this.zx=v.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=_r.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){N.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=N.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),N.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),N.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(N.Vector3[0]).addInPlace(N.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(N.Vector3[0]).subtractInPlace(N.Vector3[1]),this.zz.copyFrom(e.l00),N.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(N.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 gr().updateFromHarmonics(e)}static FromArray(e){const t=new gr;return v.FromArrayToRef(e[0],0,t.x),v.FromArrayToRef(e[1],0,t.y),v.FromArrayToRef(e[2],0,t.z),v.FromArrayToRef(e[3],0,t.xx),v.FromArrayToRef(e[4],0,t.yy),v.FromArrayToRef(e[5],0,t.zz),v.FromArrayToRef(e[6],0,t.yz),v.FromArrayToRef(e[7],0,t.zx),v.FromArrayToRef(e[8],0,t.xy),t}}class w_ extends Vh{constructor(e){super(e)}}const Q0={label:"TextureView_SwapChain_ResolveTarget",dimension:"2d",format:void 0,mipLevelCount:1,arrayLayerCount:1},J0={label:"TextureView_SwapChain",dimension:"2d",format:void 0,mipLevelCount:1,arrayLayerCount:1},D_=new X;class Se extends me{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return this._cacheSampler?this._cacheSampler.disabled:!1}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return this._cacheRenderPipeline?this._cacheRenderPipeline.disabled:!1}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return this._cacheBindGroups?this._cacheBindGroups.disabled:!1}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}areAllEffectsReady(){return!0}getFontOffset(e){return vh(e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return U.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new zh:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new Se(e,t);return new Promise(s=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>s(i))})}constructor(e,t={}){var i,s;if(super((i=t.antialias)!=null?i:!0,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._timestampIndex=0,this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this.scenes=[],this._virtualScenes=new Array,this._commandBuffers=[null,null],this._currentRenderPass=null,this._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._pendingDebugCommands=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this._snapshotRenderingMode=0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._performanceMonitor=new _h,this._name="WebGPU",this._drawCalls=new ui,t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=(s=t.enableGPUDebugMarkers)!=null?s:!1,U.Log("Babylon.js v".concat(ie.Version," - ").concat(this.description," engine")),!navigator.gpu){U.Error("WebGPU is not supported by your browser.");return}t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,navigator&&navigator.userAgent&&this._setupMobileChecks(),this._sharedInit(this._renderingCanvas),this._shaderProcessor=new ad,this._shaderProcessorWGSL=new Pp}initAsync(e,t){var i;return this.uniqueId=Se._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,this._initGlslang(e!=null?e:(i=this._options)==null?void 0:i.glslangOptions).then(s=>{var n;return this._glslang=s,this._tintWASM=Se.UseTWGSL?new ti:null,this._tintWASM?this._tintWASM.initTwgsl(t!=null?t:(n=this._options)==null?void 0:n.twgslOptions).then(()=>navigator.gpu.requestAdapter(this._options)):navigator.gpu.requestAdapter(this._options)}).then(s=>{var n,r,o;if(s){this._adapter=s,this._adapterSupportedExtensions=[],(n=this._adapter.features)==null||n.forEach(c=>this._adapterSupportedExtensions.push(c)),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then(c=>{this._adapterInfo=c});const l=(r=this._options.deviceDescriptor)!=null?r:{},h=(o=l==null?void 0:l.requiredFeatures)!=null?o:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(h){const c=h,u=[];for(const f of c)this._adapterSupportedExtensions.indexOf(f)!==-1&&u.push(f);l.requiredFeatures=u}if(this._options.setMaximumLimits&&!l.requiredLimits){l.requiredLimits={};for(const c in this._adapterSupportedLimits)c==="minSubgroupSize"||c==="maxSubgroupSize"||(l.requiredLimits[c]=this._adapterSupportedLimits[c])}return l.label="BabylonWebGPUDevice".concat(this.uniqueId),this._adapter.requestDevice(l)}else throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(s=>{var r,o;this._device=s,this._deviceEnabledExtensions=[],(r=this._device.features)==null||r.forEach(l=>this._deviceEnabledExtensions.push(l)),this._deviceLimits=s.limits;let n=-1;this._device.addEventListener("uncapturederror",l=>{++n{this._isDisposed||(this._contextWasLost=!0,U.Warn("WebGPU context lost. "+l),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(async()=>{var g,_,m,x;const h=this.snapshotRenderingMode,c=this.snapshotRendering,u=this.disableCacheSamplers,f=this.disableCacheRenderPipelines,d=this.disableCacheBindGroups,p=this.enableGPUTimingMeasurements;await this.initAsync((_=this._glslangOptions)!=null?_:(g=this._options)==null?void 0:g.glslangOptions,(x=this._twgslOptions)!=null?x:(m=this._options)==null?void 0:m.twgslOptions),this.snapshotRenderingMode=h,this.snapshotRendering=c,this.disableCacheSamplers=u,this.disableCacheRenderPipelines=f,this.disableCacheBindGroups=d,this.enableGPUTimingMeasurements=p,this._currentRenderPass=null}))})}).then(()=>{this._bufferManager=new dr(this,this._device),this._textureHelper=new Gp(this,this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new Ms(this._device),this._cacheBindGroups=new Ke(this._device,this._cacheSampler,this),this._timestampQuery=new E_(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new A_(this,this._device,this._bufferManager):void 0,this._bundleList=new ho(this._device),this._snapshotRendering=new C_(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),We.Uniform|We.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),We.Uniform|We.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&this._count===void 0&&(this._count=0,U.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._initializeLimits(),this._emptyVertexBuffer=new E(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new Mi(this._device,this._emptyVertexBuffer),this._depthCullingState=new v_(this._cacheRenderPipeline),this._stencilStateComposer=new m_(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new S_(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()}).catch(s=>{throw U.Error("A fatal error occurred during WebGPU creation/initialization."),s})}_initGlslang(e){return e=e||{},e={...Se._GLSLslangDefaultOptions,...e},e.glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?ee.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(ee.GetBabylonScriptURL(e.wasmPath))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage*2,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf("texture-compression-astc")>=0?!0:void 0,s3tc:this._deviceEnabledExtensions.indexOf("texture-compression-bc")>=0?!0:void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf("texture-compression-etc2")>=0?!0:void 0,bptc:this._deviceEnabledExtensions.indexOf("texture-compression-bc")>=0?!0:void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf("rg11b10ufloat-renderable")>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf("float32-filterable")>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:typeof BigUint64Array<"u"&&this._deviceEnabledExtensions.indexOf("timestamp-query")!==-1?!0:void 0,supportOcclusionQuery:typeof BigUint64Array<"u",canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new ir],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e);let t;if(this._options.antialias){const n={label:"Texture_MainColor_".concat(this._mainTextureExtends.width,"x").concat(this._mainTextureExtends.height,"_antialiasing"),size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:"2d",format:this._options.swapChainFormat,usage:16};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(n),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:"2d",format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new X(0,0,0,1),loadOp:"clear",storeOp:"store"}]}else t=[{view:void 0,clearValue:new X(0,0,0,1),loadOp:"clear",storeOp:"store"}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?"depth24plus-stencil8":"depth32float",this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);const i={label:"Texture_MainDepthStencil_".concat(this._mainTextureExtends.width,"x").concat(this._mainTextureExtends.height),size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:"2d",format:this._mainRenderPassWrapper.depthTextureFormat,usage:16};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const s={view:this._depthTexture.createView({label:"TextureView_MainDepthStencil_".concat(this._mainTextureExtends.width,"x").concat(this._mainTextureExtends.height),dimension:"2d",format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:"clear",depthStoreOp:"store",stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?"clear":void 0,stencilStoreOp:this.isStencilEnable?"store":void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:s}}_sharedInit(e){super._sharedInit(e),gh(this,e,this._creationOptions)}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:17,alphaMode:this.premultipliedAlpha?"premultiplied":"opaque"})}resizeImageBitmap(e,t,i){return bh(this,e,t,i)}_createImageBitmapFromSource(e,t){return xh(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&yh(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&Th()}enterPointerlock(){this._renderingCanvas&&Ka(this._renderingCanvas)}exitPointerlock(){Sh()}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){Mi.ResetCache(),Ke.ResetCache();const t=s=>{var n;for(const r of s){for(const o of r.meshes){const l=o.subMeshes;if(l)for(const h of l)h._drawWrappers=[]}for(const o of r.materials)(n=o._materialContext)==null||n.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const s of this._uniformBuffers)s.name.indexOf("leftOver")<0&&i.push(s);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return super.setSize(e,t,i)?(this.dbgVerboseLogsForFirstFrames&&(this._count===void 0&&(this._count=0),(!this._count||this._count=0,n=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,r=i===0?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===0?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(r,o,i,s,n)}_compilePipelineStageDescriptor(e,t,i,s){this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,r=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,o="#version 450\n",l=s===0?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),h=s===0?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),c=this._createPipelineStageDescriptor(l,h,s,n,r);return this.onAfterShaderCompilationObservable.notifyObservers(this),c}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new wr(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new td(e,this)}createMaterialContext(){return new Rr}createDrawContext(){return new Pr(this._bufferManager)}_preparePipelineContext(e,t,i,s,n,r,o,l){const h=e,c=h.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(U.Log(["defines",l]),U.Log(t),U.Log(i),U.Log("***********************************************")),h.sources={fragment:i,vertex:t,rawVertex:n,rawFragment:r},s?h.stages=this._compileRawPipelineStageDescriptor(t,i,c):h.stages=this._compilePipelineStageDescriptor(t,i,l,c)}getAttributes(e,t){const i=new Array(t.length),s=e;for(let n=0;n0,r.is3D=h>0,r._cachedWrapU=0,r._cachedWrapV=0,r._useSRGBBuffer=n.useSRGBBuffer,r.label=n.label,this._internalTexturesCache.push(r),i||this._textureHelper.createGPUTextureForInternalTexture(r,o,l,c||1,n.creationFlags),r}createTexture(e,t,i,s,n=3,r=null,o=null,l=null,h=null,c=null,u=null,f,d,p,g){return this._createTextureBase(e,t,i,s,n,r,o,(_,m,x,I,T,y,b,S)=>{var M;const A=I;if(_.baseWidth=A.width,_.baseHeight=A.height,_.width=A.width,_.height=A.height,_.format=_.format!==-1?_.format:c!=null?c:5,_.type=_.type!==-1?_.type:0,_._creationFlags=p!=null?p:0,S(_.width,_.height,A,m,_,()=>{}),(M=_._hardwareTexture)!=null&&M.underlyingResource)!y&&!b&&this._generateMipmaps(_,this._uploadEncoder);else{const C=this._textureHelper.createGPUTextureForInternalTexture(_,A.width,A.height,void 0,p);Ve.IsImageBitmap(A)&&(this._textureHelper.updateTexture(A,_,A.width,A.height,_.depth,C.format,0,0,T,!1,0,0),!y&&!b&&this._generateMipmaps(_,this._uploadEncoder))}x&&x.removePendingData(_),_.isReady=!0,_.onLoadedObservable.notifyObservers(_),_.onLoadedObservable.clear()},()=>!1,l,h,c,u,f,d,g)}wrapWebGPUTexture(e){const t=new ir(e),i=new Et(this,0,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers}_unpackFlipY(e){}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,s=null){t!==null&&(e._cachedWrapU=t),i!==null&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&s!==null&&(e._cachedWrapR=s)}updateTextureDimensions(e,t,i,s=1){if(!e._hardwareTexture||e.width===t&&e.height===i&&e.depth===s)return;const n=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,s,n)}_setInternalTexture(e,t,i){if(i=i!=null?i:e,this._currentEffect){const n=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),n&&n.autoBindSampler){const r=i+"Sampler";this._currentMaterialContext.setSampler(r,t)}}}createPrefilteredCubeTexture(e,t,i,s,n=null,r=null,o,l=null,h=!0){const c=u=>{if(!u){n&&n(null);return}const f=u.texture;h?u.info.sphericalPolynomial&&(f._sphericalPolynomial=u.info.sphericalPolynomial):f._sphericalPolynomial=new gr,f._source=9,n&&n(f)};return this.createCubeTexture(e,t,null,!1,c,r,o,l,h,i,s)}setTexture(e,t,i,s){this._setTexture(e,i,!1,!1,s,s)}setTextureArray(e,t,i,s){for(let n=0;n{const o=()=>{e.mapAsync(1,0,t).then(()=>{const l=e.getMappedRange(0,t);let h=i;if(h===void 0)h=new Uint8Array(t),h.set(new Uint8Array(l));else{const c=h.constructor;h=new c(h.buffer),h.set(new c(l))}e.unmap(),this._bufferManager.releaseBuffer(e),n(h)},l=>{this.isDisposed?n(new Uint8Array):r(l)})};s?(this.flushFramebuffer(),o()):this.onEndFrameObservable.addOnce(()=>{o()})})}readFromStorageBuffer(e,t,i,s,n){i=i||e.capacity;const r=this._bufferManager.createRawBuffer(i,We.MapRead|We.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(e.underlyingResource,t!=null?t:0,r,0,i),this._readFromGPUBuffer(r,i,s,n)}readFromMultipleStorageBuffers(e,t,i,s,n){i=i||e[0].capacity;const r=this._bufferManager.createRawBuffer(i*e.length,We.MapRead|We.CopyDst,void 0,"TempReadFromMultipleStorageBuffers");for(let o=0;othis.add(t,i))}get(e){const t=this._data[e];if(t!==void 0)return t}getOrAddWithFactory(e,t){let i=this.get(e);return i!==void 0||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return i!==void 0?i:(this.add(e,t),t)}contains(e){return this._data[e]!==void 0}add(e,t){return this._data[e]!==void 0?!1:(this._data[e]=t,++this._count,!0)}set(e,t){return this._data[e]===void 0?!1:(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return t!==void 0?(delete this._data[e],--this._count,t):null}remove(e){return this.contains(e)?(delete this._data[e],--this._count,!0):!1}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data){const i=this._data[t];e(t,i)}}first(e){for(const t in this._data){const i=this._data[t],s=e(t,i);if(s)return s}return null}}class Xi{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,s){for(const n in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,n)&&this._BabylonFileParsers[n](e,t,i,s)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach(t=>e=e.concat(t.bones)),e}}Xi._BabylonFileParsers={};Xi._IndividualBabylonFileParsers={};ft("BABYLON.AbstractScene",Xi);function Wh(a){a.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class ot{constructor(){this._dirty=!0,this._tempColor=new X(0,0,0,0),this._globalCurve=new X(0,0,0,0),this._highlightsCurve=new X(0,0,0,0),this._midtonesCurve=new X(0,0,0,0),this._shadowsCurve=new X(0,0,0,0),this._positiveCurve=new X(0,0,0,0),this._negativeCurve=new X(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",s="vCameraColorCurveNeutral",n="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(s,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(n,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,s,n){e!=null&&(e=ot._Clamp(e,0,360),t=ot._Clamp(t,-100,100),i=ot._Clamp(i,-100,100),s=ot._Clamp(s,-100,100),t=ot._ApplyColorGradingSliderNonlinear(t),t*=.5,s=ot._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),ot._FromHSBToRef(e,t,50+.25*s,n),n.scaleToRef(2,n),n.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,s){let n=ot._Clamp(e,0,360);const r=ot._Clamp(t/100,0,1),o=ot._Clamp(i/100,0,1);if(r===0)s.r=o,s.g=o,s.b=o;else{n/=60;const l=Math.floor(n),h=n-l,c=o*(1-r),u=o*(1-r*h),f=o*(1-r*(1-h));switch(l){case 0:s.r=o,s.g=f,s.b=c;break;case 1:s.r=u,s.g=o,s.b=c;break;case 2:s.r=c,s.g=o,s.b=f;break;case 3:s.r=c,s.g=u,s.b=o;break;case 4:s.r=f,s.g=c,s.b=o;break;default:s.r=o,s.g=c,s.b=u;break}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return Ae.Clone(()=>new ot,this)}serialize(){return Ae.Serialize(this)}static Parse(e){return Ae.Parse(()=>new ot,e,null,null)}}ot.PrepareUniforms=Wh;D([B()],ot.prototype,"_globalHue",void 0);D([B()],ot.prototype,"_globalDensity",void 0);D([B()],ot.prototype,"_globalSaturation",void 0);D([B()],ot.prototype,"_globalExposure",void 0);D([B()],ot.prototype,"_highlightsHue",void 0);D([B()],ot.prototype,"_highlightsDensity",void 0);D([B()],ot.prototype,"_highlightsSaturation",void 0);D([B()],ot.prototype,"_highlightsExposure",void 0);D([B()],ot.prototype,"_midtonesHue",void 0);D([B()],ot.prototype,"_midtonesDensity",void 0);D([B()],ot.prototype,"_midtonesSaturation",void 0);D([B()],ot.prototype,"_midtonesExposure",void 0);Ae._ColorCurvesParser=ot.Parse;function F_(a,e){e.EXPOSURE&&a.push("exposureLinear"),e.CONTRAST&&a.push("contrast"),e.COLORGRADING&&a.push("colorTransformSettings"),(e.VIGNETTE||e.DITHER)&&a.push("vInverseScreenSize"),e.VIGNETTE&&(a.push("vignetteSettings1"),a.push("vignetteSettings2")),e.COLORCURVES&&Wh(a),e.DITHER&&a.push("ditherIntensity")}function O_(a,e){e.COLORGRADING&&a.push("txColorTransform")}class Ue{constructor(){this.colorCurves=new ot,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=Ue.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new X(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=Ue.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new Q}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=0,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===Ue._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,!this._toneMappingEnabled)e.TONEMAPPING=0;else switch(this._toneMappingType){case Ue.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case Ue.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1;break}e.CONTRAST=this.contrast!==1,e.EXPOSURE=this.exposure!==1,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&&ot.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),s=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const n=t!=null?t:s/i;let r=Math.tan(this.vignetteCameraFov*.5),o=r*n;const l=Math.sqrt(o*r);o=da(o,l,this.vignetteStretch),r=da(r,l,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,r,-o*this.vignetteCenterX,-r*this.vignetteCenterY);const h=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,h)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const i=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(i-1)/i,.5/i,i,this.colorGradingTexture.level)}}clone(){return Ae.Clone(()=>new Ue,this)}serialize(){return Ae.Serialize(this)}static Parse(e){const t=Ae.Parse(()=>new Ue,e,null,null);return e.vignetteCentreX!==void 0&&(t.vignetteCenterX=e.vignetteCentreX),e.vignetteCentreY!==void 0&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}Ue.TONEMAPPING_STANDARD=0;Ue.TONEMAPPING_ACES=1;Ue.TONEMAPPING_KHR_PBR_NEUTRAL=2;Ue.PrepareUniforms=F_;Ue.PrepareSamplers=O_;Ue._VIGNETTEMODE_MULTIPLY=0;Ue._VIGNETTEMODE_OPAQUE=1;D([Hp()],Ue.prototype,"colorCurves",void 0);D([B()],Ue.prototype,"_colorCurvesEnabled",void 0);D([pi("colorGradingTexture")],Ue.prototype,"_colorGradingTexture",void 0);D([B()],Ue.prototype,"_colorGradingEnabled",void 0);D([B()],Ue.prototype,"_colorGradingWithGreenDepth",void 0);D([B()],Ue.prototype,"_colorGradingBGR",void 0);D([B()],Ue.prototype,"_exposure",void 0);D([B()],Ue.prototype,"_toneMappingEnabled",void 0);D([B()],Ue.prototype,"_toneMappingType",void 0);D([B()],Ue.prototype,"_contrast",void 0);D([B()],Ue.prototype,"vignetteStretch",void 0);D([B()],Ue.prototype,"vignetteCenterX",void 0);D([B()],Ue.prototype,"vignetteCenterY",void 0);D([B()],Ue.prototype,"vignetteWeight",void 0);D([to()],Ue.prototype,"vignetteColor",void 0);D([B()],Ue.prototype,"vignetteCameraFov",void 0);D([B()],Ue.prototype,"_vignetteBlendMode",void 0);D([B()],Ue.prototype,"_vignetteEnabled",void 0);D([B()],Ue.prototype,"_ditheringEnabled",void 0);D([B()],Ue.prototype,"_ditheringIntensity",void 0);D([B()],Ue.prototype,"_skipFinalColorClamp",void 0);D([B()],Ue.prototype,"_applyByPostProcess",void 0);D([B()],Ue.prototype,"_isEnabled",void 0);Ae._ImageProcessingConfigurationParser=Ue.Parse;ft("BABYLON.ImageProcessingConfiguration",Ue);class ns{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(E.NormalKind))return null;let i=this.pickedMesh.getIndices();(i==null?void 0:i.length)===0&&(i=null);let s;const n=N.Vector3[0],r=N.Vector3[1],o=N.Vector3[2];if(t){const h=this.pickedMesh.getVerticesData(E.NormalKind);let c=i?v.FromArrayToRef(h,i[this.faceId*3]*3,n):n.copyFromFloats(h[this.faceId*3*3],h[this.faceId*3*3+1],h[this.faceId*3*3+2]),u=i?v.FromArrayToRef(h,i[this.faceId*3+1]*3,r):r.copyFromFloats(h[(this.faceId*3+1)*3],h[(this.faceId*3+1)*3+1],h[(this.faceId*3+1)*3+2]),f=i?v.FromArrayToRef(h,i[this.faceId*3+2]*3,o):o.copyFromFloats(h[(this.faceId*3+2)*3],h[(this.faceId*3+2)*3+1],h[(this.faceId*3+2)*3+2]);c=c.scale(this.bu),u=u.scale(this.bv),f=f.scale(1-this.bu-this.bv),s=new v(c.x+u.x+f.x,c.y+u.y+f.y,c.z+u.z+f.z)}else{const h=this.pickedMesh.getVerticesData(E.PositionKind),c=i?v.FromArrayToRef(h,i[this.faceId*3]*3,n):n.copyFromFloats(h[this.faceId*3*3],h[this.faceId*3*3+1],h[this.faceId*3*3+2]),u=i?v.FromArrayToRef(h,i[this.faceId*3+1]*3,r):r.copyFromFloats(h[(this.faceId*3+1)*3],h[(this.faceId*3+1)*3+1],h[(this.faceId*3+1)*3+2]),f=i?v.FromArrayToRef(h,i[this.faceId*3+2]*3,o):o.copyFromFloats(h[(this.faceId*3+2)*3],h[(this.faceId*3+2)*3+1],h[(this.faceId*3+2)*3+2]),d=c.subtract(u),p=f.subtract(u);s=v.Cross(d,p)}const l=(h,c)=>{let u=h.getWorldMatrix();h.nonUniformScaling&&(N.Matrix[0].copyFrom(u),u=N.Matrix[0],u.setTranslationFromFloats(0,0,0),u.invert(),u.transposeToRef(N.Matrix[1]),u=N.Matrix[1]),v.TransformNormalToRef(c,u,c)};if(e&&l(this.pickedMesh,s),this.ray){const h=N.Vector3[0].copyFrom(s);e||l(this.pickedMesh,h),v.Dot(h,this.ray.direction)>0&&s.negateInPlace()}return s.normalize(),s}getTextureCoordinates(e=E.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let s=fe.FromArray(i,t[this.faceId*3]*2),n=fe.FromArray(i,t[this.faceId*3+1]*2),r=fe.FromArray(i,t[this.faceId*3+2]*2);return s=s.scale(this.bu),n=n.scale(this.bv),r=r.scale(1-this.bu-this.bv),new fe(s.x+n.x+r.x,s.y+n.y+r.y)}}class Dt{constructor(e,t,i,s,n,r){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=n,this.additionalData=r}static CreateNew(e,t,i){const s=e.getScene();return new Dt(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new Dt(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new Dt(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new Dt(e,t.x,t.y,null,i,s)}}class be{}be.NAME_EFFECTLAYER="EffectLayer";be.NAME_LAYER="Layer";be.NAME_LENSFLARESYSTEM="LensFlareSystem";be.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer";be.NAME_PARTICLESYSTEM="ParticleSystem";be.NAME_GAMEPAD="Gamepad";be.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue";be.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer";be.NAME_PREPASSRENDERER="PrePassRenderer";be.NAME_DEPTHRENDERER="DepthRenderer";be.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer";be.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager";be.NAME_SPRITE="Sprite";be.NAME_SUBSURFACE="SubSurface";be.NAME_OUTLINERENDERER="Outline";be.NAME_PROCEDURALTEXTURE="ProceduralTexture";be.NAME_SHADOWGENERATOR="ShadowGenerator";be.NAME_OCTREE="Octree";be.NAME_PHYSICSENGINE="PhysicsEngine";be.NAME_AUDIO="Audio";be.NAME_FLUIDRENDERER="FluidRenderer";be.STEP_ISREADYFORMESH_EFFECTLAYER=0;be.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0;be.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0;be.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0;be.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1;be.STEP_BEFORECAMERADRAW_PREPASS=0;be.STEP_BEFORECAMERADRAW_EFFECTLAYER=1;be.STEP_BEFORECAMERADRAW_LAYER=2;be.STEP_BEFORERENDERTARGETDRAW_PREPASS=0;be.STEP_BEFORERENDERTARGETDRAW_LAYER=1;be.STEP_BEFORERENDERINGMESH_PREPASS=0;be.STEP_BEFORERENDERINGMESH_OUTLINE=1;be.STEP_AFTERRENDERINGMESH_PREPASS=0;be.STEP_AFTERRENDERINGMESH_OUTLINE=1;be.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0;be.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1;be.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0;be.STEP_BEFORECAMERAUPDATE_GAMEPAD=1;be.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0;be.STEP_BEFORECLEAR_PREPASS=1;be.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0;be.STEP_AFTERRENDERTARGETDRAW_PREPASS=0;be.STEP_AFTERRENDERTARGETDRAW_LAYER=1;be.STEP_AFTERCAMERADRAW_PREPASS=0;be.STEP_AFTERCAMERADRAW_EFFECTLAYER=1;be.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2;be.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3;be.STEP_AFTERCAMERADRAW_LAYER=4;be.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5;be.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0;be.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0;be.STEP_AFTERRENDER_AUDIO=0;be.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0;be.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1;be.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2;be.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3;be.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0;be.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1;be.STEP_POINTERMOVE_SPRITE=0;be.STEP_POINTERDOWN_SPRITE=0;be.STEP_POINTERUP_SPRITE=0;class pt extends Array{constructor(e){super(...e)}static Create(){return Object.create(pt.prototype)}registerStep(e,t,i){let s=0,n=Number.MAX_VALUE;for(;s=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in hi.Triggers)if(Object.prototype.hasOwnProperty.call(hi.Triggers,t)&&parseInt(t)===e)return!0;return!1}}hi.Triggers={};class Cn{}Cn.KEYDOWN=1;Cn.KEYUP=2;class ya{constructor(e,t){this.type=e,this.event=t}}class tl extends ya{get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}}var ge;(function(a){a[a.Generic=0]="Generic",a[a.Keyboard=1]="Keyboard",a[a.Mouse=2]="Mouse",a[a.Touch=3]="Touch",a[a.DualShock=4]="DualShock",a[a.Xbox=5]="Xbox",a[a.Switch=6]="Switch",a[a.DualSense=7]="DualSense"})(ge||(ge={}));var ye;(function(a){a[a.Horizontal=0]="Horizontal",a[a.Vertical=1]="Vertical",a[a.LeftClick=2]="LeftClick",a[a.MiddleClick=3]="MiddleClick",a[a.RightClick=4]="RightClick",a[a.BrowserBack=5]="BrowserBack",a[a.BrowserForward=6]="BrowserForward",a[a.MouseWheelX=7]="MouseWheelX",a[a.MouseWheelY=8]="MouseWheelY",a[a.MouseWheelZ=9]="MouseWheelZ",a[a.Move=12]="Move"})(ye||(ye={}));var il;(function(a){a[a.Horizontal=0]="Horizontal",a[a.Vertical=1]="Vertical",a[a.LeftClick=2]="LeftClick",a[a.MiddleClick=3]="MiddleClick",a[a.RightClick=4]="RightClick",a[a.BrowserBack=5]="BrowserBack",a[a.BrowserForward=6]="BrowserForward",a[a.MouseWheelX=7]="MouseWheelX",a[a.MouseWheelY=8]="MouseWheelY",a[a.MouseWheelZ=9]="MouseWheelZ",a[a.DeltaHorizontal=10]="DeltaHorizontal",a[a.DeltaVertical=11]="DeltaVertical"})(il||(il={}));var sl;(function(a){a[a.Cross=0]="Cross",a[a.Circle=1]="Circle",a[a.Square=2]="Square",a[a.Triangle=3]="Triangle",a[a.L1=4]="L1",a[a.R1=5]="R1",a[a.L2=6]="L2",a[a.R2=7]="R2",a[a.Share=8]="Share",a[a.Options=9]="Options",a[a.L3=10]="L3",a[a.R3=11]="R3",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.TouchPad=17]="TouchPad",a[a.LStickXAxis=18]="LStickXAxis",a[a.LStickYAxis=19]="LStickYAxis",a[a.RStickXAxis=20]="RStickXAxis",a[a.RStickYAxis=21]="RStickYAxis"})(sl||(sl={}));var nl;(function(a){a[a.Cross=0]="Cross",a[a.Circle=1]="Circle",a[a.Square=2]="Square",a[a.Triangle=3]="Triangle",a[a.L1=4]="L1",a[a.R1=5]="R1",a[a.L2=6]="L2",a[a.R2=7]="R2",a[a.Create=8]="Create",a[a.Options=9]="Options",a[a.L3=10]="L3",a[a.R3=11]="R3",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.TouchPad=17]="TouchPad",a[a.LStickXAxis=18]="LStickXAxis",a[a.LStickYAxis=19]="LStickYAxis",a[a.RStickXAxis=20]="RStickXAxis",a[a.RStickYAxis=21]="RStickYAxis"})(nl||(nl={}));var rl;(function(a){a[a.A=0]="A",a[a.B=1]="B",a[a.X=2]="X",a[a.Y=3]="Y",a[a.LB=4]="LB",a[a.RB=5]="RB",a[a.LT=6]="LT",a[a.RT=7]="RT",a[a.Back=8]="Back",a[a.Start=9]="Start",a[a.LS=10]="LS",a[a.RS=11]="RS",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.LStickXAxis=17]="LStickXAxis",a[a.LStickYAxis=18]="LStickYAxis",a[a.RStickXAxis=19]="RStickXAxis",a[a.RStickYAxis=20]="RStickYAxis"})(rl||(rl={}));var al;(function(a){a[a.B=0]="B",a[a.A=1]="A",a[a.Y=2]="Y",a[a.X=3]="X",a[a.L=4]="L",a[a.R=5]="R",a[a.ZL=6]="ZL",a[a.ZR=7]="ZR",a[a.Minus=8]="Minus",a[a.Plus=9]="Plus",a[a.LS=10]="LS",a[a.RS=11]="RS",a[a.DPadUp=12]="DPadUp",a[a.DPadDown=13]="DPadDown",a[a.DPadLeft=14]="DPadLeft",a[a.DPadRight=15]="DPadRight",a[a.Home=16]="Home",a[a.Capture=17]="Capture",a[a.LStickXAxis=18]="LStickXAxis",a[a.LStickYAxis=19]="LStickYAxis",a[a.RStickXAxis=20]="RStickXAxis",a[a.RStickYAxis=21]="RStickYAxis"})(al||(al={}));var ol;(function(a){a[a.PointerMove=0]="PointerMove",a[a.PointerDown=1]="PointerDown",a[a.PointerUp=2]="PointerUp"})(ol||(ol={}));class Nn{}Nn.DOM_DELTA_PIXEL=0;Nn.DOM_DELTA_LINE=1;Nn.DOM_DELTA_PAGE=2;class As{static CreateDeviceEvent(e,t,i,s,n,r,o){switch(e){case ge.Keyboard:return this._CreateKeyboardEvent(i,s,n,r);case ge.Mouse:if(i===ye.MouseWheelX||i===ye.MouseWheelY||i===ye.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,n,r);case ge.Touch:return this._CreatePointerEvent(e,t,i,s,n,r,o);default:throw"Unable to generate event for device ".concat(ge[e])}}static _CreatePointerEvent(e,t,i,s,n,r,o){const l=this._CreateMouseEvent(e,t,i,s,n,r);e===ge.Mouse?(l.deviceType=ge.Mouse,l.pointerId=1,l.pointerType="mouse"):(l.deviceType=ge.Touch,l.pointerId=o!=null?o:t,l.pointerType="touch");let h=0;return h+=n.pollInput(e,t,ye.LeftClick),h+=n.pollInput(e,t,ye.RightClick)*2,h+=n.pollInput(e,t,ye.MiddleClick)*4,l.buttons=h,i===ye.Move?l.type="pointermove":i>=ye.LeftClick&&i<=ye.RightClick&&(l.type=s===1?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,s,n,r){const o=this._CreateMouseEvent(e,t,i,s,n,r);switch(o.pointerId=1,o.type="wheel",o.deltaMode=Nn.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case ye.MouseWheelX:o.deltaX=s;break;case ye.MouseWheelY:o.deltaY=s;break;case ye.MouseWheelZ:o.deltaZ=s;break}return o}static _CreateMouseEvent(e,t,i,s,n,r){const o=this._CreateEvent(r),l=n.pollInput(e,t,ye.Horizontal),h=n.pollInput(e,t,ye.Vertical);return r?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-r.getBoundingClientRect().x,o.offsetY=o.movementY-r.getBoundingClientRect().y):(o.movementX=n.pollInput(e,t,10),o.movementY=n.pollInput(e,t,11),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,n),o.clientX=l,o.clientY=h,o.x=l,o.y=h,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){const n=this._CreateEvent(s);return this._CheckNonCharacterKeys(n,i),n.deviceType=ge.Keyboard,n.deviceSlot=0,n.inputIndex=e,n.type=t===1?"keydown":"keyup",n.key=String.fromCharCode(e),n.keyCode=e,n}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(ge.Keyboard),s=i&&t.pollInput(ge.Keyboard,0,18)===1,n=i&&t.pollInput(ge.Keyboard,0,17)===1,r=i&&(t.pollInput(ge.Keyboard,0,91)===1||t.pollInput(ge.Keyboard,0,92)===1||t.pollInput(ge.Keyboard,0,93)===1),o=i&&t.pollInput(ge.Keyboard,0,16)===1;e.altKey=s,e.ctrlKey=n,e.metaKey=r,e.shiftKey=o}static _CreateEvent(e){const t={};return t.preventDefault=()=>{},t.target=e,t}}class B_{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(s,n,r,o)=>{const l=As.CreateDeviceEvent(s,n,r,o,this);i(s,n,l)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===ge.Mouse||e===ge.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const ll=255,hl=Object.keys(ye).length/2;class N_{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=ee.IsSafari(),this._usingMacOS=Xs()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=n=>{},this._keyboardUpEvent=n=>{},this._keyboardBlurEvent=n=>{},this._pointerMoveEvent=n=>{},this._pointerDownEvent=n=>{},this._pointerUpEvent=n=>{},this._pointerCancelEvent=n=>{},this._pointerWheelEvent=n=>{},this._pointerBlurEvent=n=>{},this._pointerMacOSChromeOutEvent=n=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=Xs()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._isUsingChromium=Xs()&&navigator.userAgent&&navigator.userAgent.indexOf("Chrome")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=n=>{},this._gamepadDisconnectedEvent=n=>{},this._eventPrefix=ee.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=s,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const s=this._inputs[e][t];if(!s)throw"Unable to find device ".concat(ge[e]);e>=ge.DualShock&&e<=ge.DualSense&&this._updateDevice(e,t,i);const n=s[i];if(n===void 0)throw"Unable to find input ".concat(i," for device ").concat(ge[e]," in slot ").concat(t);return i===ye.Move&&ee.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),n}isDeviceAvailable(e){return this._inputs[e]!==void 0}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this==null?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(const t of this._inputs)if(t)for(const i in t){const s=+i,n=t[s];if(n)for(let r=0;r{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(ge.Keyboard,0,ll));const t=this._inputs[ge.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&e.key!=="Meta"&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(ge.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(ge.Keyboard,0,ll));const t=this._inputs[ge.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&e.key==="Meta"&&this._metaKeys.length>0){for(const s of this._metaKeys){const n=As.CreateDeviceEvent(ge.Keyboard,0,s,0,this,this._elementToAttachTo);t[s]=0,this._onInputChanged(ge.Keyboard,0,n)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(ge.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[ge.Keyboard][0];for(let t=0;t{const s=this._getPointerType(i);let n=s===ge.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(s===ge.Touch&&n===-1){const o=this._activeTouchIds.indexOf(-1);if(o>=0)n=o,this._activeTouchIds[o]=i.pointerId,this._onDeviceConnected(s,n);else{ee.Warn("Max number of touches exceeded. Ignoring touches in excess of ".concat(this._maxTouchPoints));return}}this._inputs[s]||(this._inputs[s]={}),this._inputs[s][n]||this._addPointerDevice(s,n,i.clientX,i.clientY);const r=this._inputs[s][n];if(r){const o=i;o.inputIndex=ye.Move,r[ye.Horizontal]=i.clientX,r[ye.Vertical]=i.clientY,s===ge.Touch&&r[ye.LeftClick]===0&&(r[ye.LeftClick]=1),i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(s,n,o),!this._usingSafari&&i.button!==-1&&(o.inputIndex=i.button+2,r[i.button+2]=r[i.button+2]?0:1,this._onInputChanged(s,n,o))}},this._pointerDownEvent=i=>{const s=this._getPointerType(i);let n=s===ge.Mouse?0:i.pointerId;if(s===ge.Touch){let o=this._activeTouchIds.indexOf(i.pointerId);if(o===-1&&(o=this._activeTouchIds.indexOf(-1)),o>=0)n=o,this._activeTouchIds[o]=i.pointerId;else{ee.Warn("Max number of touches exceeded. Ignoring touches in excess of ".concat(this._maxTouchPoints));return}}this._inputs[s]||(this._inputs[s]={}),this._inputs[s][n]?s===ge.Touch&&this._onDeviceConnected(s,n):this._addPointerDevice(s,n,i.clientX,i.clientY);const r=this._inputs[s][n];if(r){const o=r[ye.Horizontal],l=r[ye.Vertical];if(s===ge.Mouse){if(i.pointerId===void 0&&(i.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch{}}else if(i.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(i.pointerId)}catch{}r[ye.Horizontal]=i.clientX,r[ye.Vertical]=i.clientY,r[i.button+2]=1;const h=i;h.inputIndex=i.button+2,this._onInputChanged(s,n,h),(o!==i.clientX||l!==i.clientY)&&(h.inputIndex=ye.Move,this._onInputChanged(s,n,h))}},this._pointerUpEvent=i=>{var o,l,h,c,u;const s=this._getPointerType(i),n=s===ge.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(s===ge.Touch){if(n===-1)return;this._activeTouchIds[n]=-1}const r=(o=this._inputs[s])==null?void 0:o[n];if(r&&r[i.button+2]!==0){const f=r[ye.Horizontal],d=r[ye.Vertical];r[ye.Horizontal]=i.clientX,r[ye.Vertical]=i.clientY,r[i.button+2]=0;const p=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(f!==i.clientX||d!==i.clientY)&&(p.inputIndex=ye.Move,this._onInputChanged(s,n,p)),p.inputIndex=i.button+2,s===ge.Mouse&&this._mouseId>=0&&((h=(l=this._elementToAttachTo).hasPointerCapture)!=null&&h.call(l,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&((u=(c=this._elementToAttachTo).hasPointerCapture)!=null&&u.call(c,i.pointerId))&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(s,n,p),s===ge.Touch&&this._onDeviceDisconnected(s,n)}},this._pointerCancelEvent=i=>{var s,n,r,o;if(i.pointerType==="mouse"){const l=this._inputs[ge.Mouse][0];this._mouseId>=0&&((n=(s=this._elementToAttachTo).hasPointerCapture)!=null&&n.call(s,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let h=ye.LeftClick;h<=ye.BrowserForward;h++)if(l[h]===1){l[h]=0;const c=As.CreateDeviceEvent(ge.Mouse,0,h,0,this,this._elementToAttachTo);this._onInputChanged(ge.Mouse,0,c)}}else{const l=this._activeTouchIds.indexOf(i.pointerId);if(l===-1)return;(o=(r=this._elementToAttachTo).hasPointerCapture)!=null&&o.call(r,i.pointerId)&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._inputs[ge.Touch][l][ye.LeftClick]=0;const h=As.CreateDeviceEvent(ge.Touch,l,ye.LeftClick,0,this,this._elementToAttachTo,i.pointerId);this._onInputChanged(ge.Touch,l,h),this._activeTouchIds[l]=-1,this._onDeviceDisconnected(ge.Touch,l)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":document.onmousewheel!==void 0?"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{}this._pointerBlurEvent=()=>{var i,s,n,r,o;if(this.isDeviceAvailable(ge.Mouse)){const l=this._inputs[ge.Mouse][0];this._mouseId>=0&&((s=(i=this._elementToAttachTo).hasPointerCapture)!=null&&s.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let h=ye.LeftClick;h<=ye.BrowserForward;h++)if(l[h]===1){l[h]=0;const c=As.CreateDeviceEvent(ge.Mouse,0,h,0,this,this._elementToAttachTo);this._onInputChanged(ge.Mouse,0,c)}}if(this.isDeviceAvailable(ge.Touch)){const l=this._inputs[ge.Touch];for(let h=0;h{const s=ge.Mouse,n=0;this._inputs[s]||(this._inputs[s]=[]),this._inputs[s][n]||(this._pointerActive=!0,this._registerDevice(s,n,hl));const r=this._inputs[s][n];if(r){r[ye.MouseWheelX]=i.deltaX||0,r[ye.MouseWheelY]=i.deltaY||i.wheelDelta||0,r[ye.MouseWheelZ]=i.deltaZ||0;const o=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),r[ye.MouseWheelX]!==0&&(o.inputIndex=ye.MouseWheelX,this._onInputChanged(s,n,o)),r[ye.MouseWheelY]!==0&&(o.inputIndex=ye.MouseWheelY,this._onInputChanged(s,n,o)),r[ye.MouseWheelZ]!==0&&(o.inputIndex=ye.MouseWheelZ,this._onInputChanged(s,n,o))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=i=>{i.buttons>1&&this._pointerCancelEvent(i)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,e?{passive:!1}:!1),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add(()=>{if(this.isDeviceAvailable(ge.Mouse)){const i=this._inputs[ge.Mouse][0];i[ye.MouseWheelX]=0,i[ye.MouseWheelY]=0,i[ye.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const s=navigator.getGamepads()[t];if(s&&e===this._gamepads[t]){const n=this._inputs[e][t];i>=s.buttons.length?n[i]=s.axes[i-s.buttons.length].valueOf():n[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return e.indexOf("054c")!==-1?e.indexOf("0ce6")!==-1?ge.DualSense:ge.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?ge.Xbox:e.indexOf("057e")!==-1?ge.Switch:ge.Generic}_getPointerType(e){let t=ge.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=ge.Touch),t}}class cl{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new Q,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class U_{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=r=>{for(let o=0;o{const o=this._registeredManagers.indexOf(r);o>-1&&this._registeredManagers.splice(o,1)};const t=Object.keys(ge).length/2;this._devices=new Array(t);const i=(r,o)=>{this._devices[r]||(this._devices[r]=new Array),this._devices[r][o]||(this._devices[r][o]=o);for(const l of this._registeredManagers){const h=new cl(this._deviceInputSystem,r,o);l._addDevice(h)}},s=(r,o)=>{var l;(l=this._devices[r])!=null&&l[o]&&delete this._devices[r][o];for(const h of this._registeredManagers)h._removeDevice(r,o)},n=(r,o,l)=>{if(l)for(const h of this._registeredManagers)h._onInputChanged(r,o,l)};typeof _native<"u"?this._deviceInputSystem=new B_(i,s,n):this._deviceInputSystem=new N_(e,i,s,n)}dispose(){this._deviceInputSystem.dispose()}}class k_{getDeviceSource(e,t){if(t===void 0){if(this._firstDevice[e]===void 0)return null;t=this._firstDevice[e]}return!this._devices[e]||this._devices[e][t]===void 0?null:this._devices[e][t]}getDeviceSources(e){return this._devices[e]?this._devices[e].filter(t=>!!t):[]}constructor(e){const t=Object.keys(ge).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new U_(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new Q(i=>{for(const s of this._devices)if(s)for(const n of s)n&&this.onDeviceConnectedObservable.notifyObserver(i,n)}),this.onDeviceDisconnectedObservable=new Q,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var s,n;const i=(s=this._devices[e])==null?void 0:s[t];this.onDeviceDisconnectedObservable.notifyObservers(i),(n=this._devices[e])!=null&&n[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var s,n;(n=(s=this._devices[e])==null?void 0:s[t])==null||n.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case ge.Keyboard:case ge.Mouse:this._firstDevice[e]=0;break;case ge.Touch:case ge.DualSense:case ge.DualShock:case ge.Xbox:case ge.Switch:case ge.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t){for(let i=0;i=ye.MouseWheelX&&t.inputIndex<=ye.MouseWheelZ?Re.POINTERWHEEL:Re.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,r));let o;e?(o=new Zi(r,t,e),this._setRayOnPointerInfo(e,t)):(o=new Zi(r,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,r)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,O.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const s=this._scene,n=new L_(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(n.originalPickingInfo=e,n.ray=e.ray,t.pointerType==="xr-near"&&e.originMesh&&(n.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(n,i),!!n.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const n=i.getEngine().getInputElement();if(e!=null&&e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&n&&this._pointerOverMesh){const r=this._pointerOverMesh._getActionManagerForTrigger();r&&r.hasPointerTriggers&&(n.style.cursor=r.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=ye.Move,!this._checkPrePointerObservable(e,i,Re.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,Re.POINTERDOWN)&&this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e!=null&&e.pickedMesh){this._pickedDownMesh=e.pickedMesh;const r=e.pickedMesh._getActionManagerForTrigger();if(r){if(r.hasPickTriggers)switch(r.processTrigger(5,Dt.CreateNew(e.pickedMesh,t,e)),t.button){case 0:r.processTrigger(2,Dt.CreateNew(e.pickedMesh,t,e));break;case 1:r.processTrigger(4,Dt.CreateNew(e.pickedMesh,t,e));break;case 2:r.processTrigger(3,Dt.CreateNew(e.pickedMesh,t,e));break}r.hasSpecificTrigger(8)&&window.setTimeout(()=>{const o=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,l=>l.isPickable&&l.isVisible&&l.isReady()&&l.actionManager&&l.actionManager.hasSpecificTrigger(8)&&l===this._pickedDownMesh,!1,i.cameraToUseForPointers);o!=null&&o.pickedMesh&&r&&this._totalPointersPressed!==0&&Date.now()-this._startingPointerTime>_t.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,r.processTrigger(8,Dt.CreateNew(o.pickedMesh,t)))},_t.LongPressDelay)}}else for(const r of i._pointerDownStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const n=Re.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,n),s=new Zi(n,t,e),this._setRayOnPointerInfo(e,t)):s=new Zi(n,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,n)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=ye.Move;const n=new ul;i?n.doubleClick=!0:n.singleClick=!0,!this._checkPrePointerObservable(e,s,Re.POINTERUP)&&this._processPointerUp(e,s,n)}_processPointerUp(e,t,i){const s=this._scene;if(e!=null&&e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const r=Re.POINTERPICK,o=new Zi(r,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(o,r)}const n=e.pickedMesh._getActionManagerForTrigger();if(n&&!i.ignore){n.processTrigger(7,Dt.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&n.processTrigger(1,Dt.CreateNew(e.pickedMesh,t,e));const r=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&r&&r.processTrigger(6,Dt.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const n of s._pointerUpStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const n=this._pickedDownMesh._getActionManagerForTrigger(16);n&&n.processTrigger(16,Dt.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const n=new Zi(Re.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(n,Re.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,Re.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=Re.POINTERTAP:i.doubleClick&&(r=Re.POINTERDOUBLETAP),r){const o=new Zi(r,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(r)&&s.onPointerObservable.notifyObservers(o,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const n=this._scene,r=n.getEngine();s||(s=r.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new k_(r),this._initActionManager=o=>{if(!this._meshPickProceed){const l=n.skipPointerUpPicking||n._registeredActions===0&&!this._checkForPicking()&&!n.onPointerUp?null:n.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,n.pointerUpPredicate,n.pointerUpFastCheck,n.cameraToUseForPointers,n.pointerUpTrianglePredicate);this._currentPickResult=l,l&&(o=l.hit&&l.pickedMesh?l.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return o},this._delayedSimpleClick=(o,l,h)=>{if((Date.now()-this._previousStartingPointerTime>_t.DoubleClickDelay&&!this._doubleClickOccured||o!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,l.singleClick=!0,l.ignore=!1,this._delayedClicks[o])){const c=this._delayedClicks[o].evt,u=Re.POINTERTAP,f=new Zi(u,c,this._currentPickResult);n.onPointerObservable.hasObservers()&&n.onPointerObservable.hasSpecificMask(u)&&n.onPointerObservable.notifyObservers(f,u),this._delayedClicks[o]=null}},this._initClickEvent=(o,l,h,c)=>{var g,_;const u=new ul;this._currentPickResult=null;let f=null,d=o.hasSpecificMask(Re.POINTERPICK)||l.hasSpecificMask(Re.POINTERPICK)||o.hasSpecificMask(Re.POINTERTAP)||l.hasSpecificMask(Re.POINTERTAP)||o.hasSpecificMask(Re.POINTERDOUBLETAP)||l.hasSpecificMask(Re.POINTERDOUBLETAP);!d&&hi&&(f=this._initActionManager(f,u),f&&(d=f.hasPickTriggers));let p=!1;if(d){const m=h.button;if(u.hasSwiped=this._isPointerSwiping(),!u.hasSwiped){let x=!_t.ExclusiveDoubleClickMode;if(x||(x=!o.hasSpecificMask(Re.POINTERDOUBLETAP)&&!l.hasSpecificMask(Re.POINTERDOUBLETAP),x&&!hi.HasSpecificTrigger(6)&&(f=this._initActionManager(f,u),f&&(x=!f.hasSpecificTrigger(6)))),x)(Date.now()-this._previousStartingPointerTime>_t.DoubleClickDelay||m!==this._previousButtonPressed)&&(u.singleClick=!0,c(u,this._currentPickResult),p=!0);else{const T={evt:h,clickInfo:u,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,m,u,c),_t.DoubleClickDelay)};this._delayedClicks[m]=T}let I=o.hasSpecificMask(Re.POINTERDOUBLETAP)||l.hasSpecificMask(Re.POINTERDOUBLETAP);!I&&hi.HasSpecificTrigger(6)&&(f=this._initActionManager(f,u),f&&(I=f.hasSpecificTrigger(6))),I&&(m===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime<_t.DoubleClickDelay&&!this._doubleClickOccured?(!u.hasSwiped&&!this._isPointerSwiping()?(this._previousStartingPointerTime=0,this._doubleClickOccured=!0,u.doubleClick=!0,u.ignore=!1,_t.ExclusiveDoubleClickMode&&this._delayedClicks[m]&&(clearTimeout((g=this._delayedClicks[m])==null?void 0:g.timeoutId),this._delayedClicks[m]=null),c(u,this._currentPickResult)):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=m,_t.ExclusiveDoubleClickMode?(this._delayedClicks[m]&&(clearTimeout((_=this._delayedClicks[m])==null?void 0:_.timeoutId),this._delayedClicks[m]=null),c(u,this._previousPickResult)):c(u,this._currentPickResult)),p=!0):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=m))}}p||c(u,this._currentPickResult)},this._onPointerMove=o=>{if(this._updatePointerPosition(o),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>_t.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>_t.DragMovementThreshold),r.isPointerLock&&r._verifyPointerLock(),this._checkPrePointerObservable(null,o,o.inputIndex>=ye.MouseWheelX&&o.inputIndex<=ye.MouseWheelZ?Re.POINTERWHEEL:Re.POINTERMOVE)||!n.cameraToUseForPointers&&!n.activeCamera)return;if(n.skipPointerMovePicking){this._processPointerMove(new ns,o);return}n.pointerMovePredicate||(n.pointerMovePredicate=h=>h.isPickable&&h.isVisible&&h.isReady()&&h.isEnabled()&&(h.enablePointerMoveEvents||n.constantlyUpdateMeshUnderPointer||h._getActionManagerForTrigger()!==null)&&(!n.cameraToUseForPointers||(n.cameraToUseForPointers.layerMask&h.layerMask)!==0));const l=n._registeredActions>0||n.constantlyUpdateMeshUnderPointer?this._pickMove(o):null;this._processPointerMove(l,o)},this._onPointerDown=o=>{var h;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,_t.ExclusiveDoubleClickMode){for(let c=0;cc.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(!n.cameraToUseForPointers||(n.cameraToUseForPointers.layerMask&c.layerMask)!==0)),this._pickedDownMesh=null;let l;n.skipPointerDownPicking||n._registeredActions===0&&!this._checkForPicking()&&!n.onPointerDown?l=new ns:l=n.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,n.pointerDownPredicate,n.pointerDownFastCheck,n.cameraToUseForPointers,n.pointerDownTrianglePredicate),this._processPointerDown(l,o)},this._onPointerUp=o=>{this._totalPointersPressed!==0&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(o),n.preventDefaultOnPointerUp&&s&&(o.preventDefault(),s.focus()),this._initClickEvent(n.onPrePointerObservable,n.onPointerObservable,o,(l,h)=>{if(n.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!l.ignore)){if(this._checkPrePointerObservable(null,o,Re.POINTERUP)){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1);return}l.hasSwiped||(l.singleClick&&n.onPrePointerObservable.hasSpecificMask(Re.POINTERTAP)&&this._checkPrePointerObservable(null,o,Re.POINTERTAP)&&(this._skipPointerTap=!0),l.doubleClick&&n.onPrePointerObservable.hasSpecificMask(Re.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,o,Re.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[o.pointerId]){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1),!(!n.cameraToUseForPointers&&!n.activeCamera)&&(n.pointerUpPredicate||(n.pointerUpPredicate=c=>c.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(!n.cameraToUseForPointers||(n.cameraToUseForPointers.layerMask&c.layerMask)!==0)),!this._meshPickProceed&&(hi&&hi.HasTriggers||this._checkForPicking()||n.onPointerUp)&&this._initActionManager(null,l),h||(h=this._currentPickResult),this._processPointerUp(h,o,l),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=o=>{const l=Cn.KEYDOWN;if(n.onPreKeyboardObservable.hasObservers()){const h=new tl(l,o);if(n.onPreKeyboardObservable.notifyObservers(h,l),h.skipOnKeyboardObservable)return}if(n.onKeyboardObservable.hasObservers()){const h=new ya(l,o);n.onKeyboardObservable.notifyObservers(h,l)}n.actionManager&&n.actionManager.processTrigger(14,Dt.CreateNewFromScene(n,o))},this._onKeyUp=o=>{const l=Cn.KEYUP;if(n.onPreKeyboardObservable.hasObservers()){const h=new tl(l,o);if(n.onPreKeyboardObservable.notifyObservers(h,l),h.skipOnKeyboardObservable)return}if(n.onKeyboardObservable.hasObservers()){const h=new ya(l,o);n.onKeyboardObservable.notifyObservers(h,l)}n.actionManager&&n.actionManager.processTrigger(15,Dt.CreateNewFromScene(n,o))},this._deviceSourceManager.onDeviceConnectedObservable.add(o=>{o.deviceType===ge.Mouse?o.onInputChangedObservable.add(l=>{this._originMouseEvent=l,l.inputIndex===ye.LeftClick||l.inputIndex===ye.MiddleClick||l.inputIndex===ye.RightClick||l.inputIndex===ye.BrowserBack||l.inputIndex===ye.BrowserForward?t&&o.getInput(l.inputIndex)===1?this._onPointerDown(l):e&&o.getInput(l.inputIndex)===0&&this._onPointerUp(l):i&&(l.inputIndex===ye.Move?this._onPointerMove(l):(l.inputIndex===ye.MouseWheelX||l.inputIndex===ye.MouseWheelY||l.inputIndex===ye.MouseWheelZ)&&this._onPointerMove(l))}):o.deviceType===ge.Touch?o.onInputChangedObservable.add(l=>{l.inputIndex===ye.LeftClick&&(t&&o.getInput(l.inputIndex)===1?(this._onPointerDown(l),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&o.getInput(l.inputIndex)===0&&(this._onPointerUp(l),this._totalPointersPressed===0&&(this._isMultiTouchGesture=!1))),i&&l.inputIndex===ye.Move&&this._onPointerMove(l)}):o.deviceType===ge.Keyboard&&o.onInputChangedObservable.add(l=>{l.type==="keydown"?this._onKeyDown(l):l.type==="keyup"&&this._onKeyUp(l)})}),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,s){if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const n=this._meshUnderPointerId[t];let r;n&&(r=n._getActionManagerForTrigger(10),r&&r.processTrigger(10,Dt.CreateNew(n,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,r=e._getActionManagerForTrigger(9),r&&r.processTrigger(9,Dt.CreateNew(e,s,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}_t.DragMovementThreshold=10;_t.LongPressDelay=500;_t.DoubleClickDelay=300;_t.ExclusiveDoubleClickMode=!1;class Hh{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}Hh._UniqueIdCounter=1;class Xe{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}Xe.FALLOFF_DEFAULT=0;Xe.FALLOFF_PHYSICAL=1;Xe.FALLOFF_GLTF=2;Xe.FALLOFF_STANDARD=3;Xe.LIGHTMAP_DEFAULT=0;Xe.LIGHTMAP_SPECULAR=1;Xe.LIGHTMAP_SHADOWSONLY=2;Xe.INTENSITYMODE_AUTOMATIC=0;Xe.INTENSITYMODE_LUMINOUSPOWER=1;Xe.INTENSITYMODE_LUMINOUSINTENSITY=2;Xe.INTENSITYMODE_ILLUMINANCE=3;Xe.INTENSITYMODE_LUMINANCE=4;Xe.LIGHTTYPEID_POINTLIGHT=0;Xe.LIGHTTYPEID_DIRECTIONALLIGHT=1;Xe.LIGHTTYPEID_SPOTLIGHT=2;Xe.LIGHTTYPEID_HEMISPHERICLIGHT=3;class V_{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var Ta;(function(a){a[a.BackwardCompatible=0]="BackwardCompatible",a[a.Intermediate=1]="Intermediate",a[a.Aggressive=2]="Aggressive"})(Ta||(Ta={}));class Qe extends Xi{static DefaultMaterialFactory(e){throw Te("StandardMaterial")}static CollisionCoordinatorFactory(){throw Te("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 0:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case 1:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case 2:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1;break}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return _t.DragMovementThreshold}static set DragMovementThreshold(e){_t.DragMovementThreshold=e}static get LongPressDelay(){return _t.LongPressDelay}static set LongPressDelay(e){_t.LongPressDelay=e}static get DoubleClickDelay(){return _t.DoubleClickDelay}static set DoubleClickDelay(e){_t.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return _t.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){_t.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,n=this.useRightHandedSystem===(this._mirroredCameraPosition!=null);return N.Vector4[0].set(s.x,s.y,s.z,n?-1:1),e&&(i?e.setFloat3(t,N.Vector4[0].x,N.Vector4[0].y,N.Vector4[0].z):e.setVector4(t,N.Vector4[0])),N.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=Eh(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=Qe.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=Qe.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new _t(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new X(.2,.2,.3,1),this.ambientColor=new pe(0,0,0),this.environmentIntensity=1,this._performancePriority=0,this.onScenePerformancePriorityChangedObservable=new Q,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new Q,this._onDisposeObserver=null,this.onBeforeRenderObservable=new Q,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new Q,this.onAfterRenderCameraObservable=new Q,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new Q,this.onAfterAnimationsObservable=new Q,this.onBeforeDrawPhaseObservable=new Q,this.onAfterDrawPhaseObservable=new Q,this.onReadyObservable=new Q,this.onBeforeCameraRenderObservable=new Q,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new Q,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new Q,this.onAfterActiveMeshesEvaluationObservable=new Q,this.onBeforeParticlesRenderingObservable=new Q,this.onAfterParticlesRenderingObservable=new Q,this.onDataLoadedObservable=new Q,this.onNewCameraAddedObservable=new Q,this.onCameraRemovedObservable=new Q,this.onNewLightAddedObservable=new Q,this.onLightRemovedObservable=new Q,this.onNewGeometryAddedObservable=new Q,this.onGeometryRemovedObservable=new Q,this.onNewTransformNodeAddedObservable=new Q,this.onTransformNodeRemovedObservable=new Q,this.onNewMeshAddedObservable=new Q,this.onMeshRemovedObservable=new Q,this.onNewSkeletonAddedObservable=new Q,this.onSkeletonRemovedObservable=new Q,this.onNewMaterialAddedObservable=new Q,this.onNewMultiMaterialAddedObservable=new Q,this.onMaterialRemovedObservable=new Q,this.onMultiMaterialRemovedObservable=new Q,this.onNewTextureAddedObservable=new Q,this.onTextureRemovedObservable=new Q,this.onBeforeRenderTargetsRenderObservable=new Q,this.onAfterRenderTargetsRenderObservable=new Q,this.onBeforeStepObservable=new Q,this.onAfterStepObservable=new Q,this.onActiveCameraChanged=new Q,this.onActiveCamerasChanged=new Q,this.onBeforeRenderingGroupObservable=new Q,this.onAfterRenderingGroupObservable=new Q,this.onMeshImportedObservable=new Q,this.onAnimationFileImportedObservable=new Q,this._registeredForLateAnimationBindings=new Is(256),this._pointerPickingConfiguration=new V_,this.onPrePointerObservable=new Q,this.onPointerObservable=new Q,this.onPreKeyboardObservable=new Q,this.onKeyboardObservable=new Q,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Qe.FOGMODE_NONE,this.fogColor=new pe(.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 v(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new Is(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new ui,this._activeIndices=new ui,this._activeParticles=new ui,this._activeBones=new ui,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 Vt(256),this._processedMaterials=new Vt(256),this._renderTargets=new Is(256),this._materialsRenderTargets=new Is(256),this._activeParticleSystems=new Vt(256),this._activeSkeletons=new Is(32),this._softwareSkinnedMeshes=new Is(32),this._activeAnimatables=new Array,this._transformMatrix=O.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=pt.Create(),this._beforeClearStage=pt.Create(),this._beforeRenderTargetClearStage=pt.Create(),this._gatherRenderTargetsStage=pt.Create(),this._gatherActiveCameraRenderTargetsStage=pt.Create(),this._isReadyForMeshStage=pt.Create(),this._beforeEvaluateActiveMeshStage=pt.Create(),this._evaluateSubMeshStage=pt.Create(),this._preActiveMeshStage=pt.Create(),this._cameraDrawRenderTargetStage=pt.Create(),this._beforeCameraDrawStage=pt.Create(),this._beforeRenderTargetDrawStage=pt.Create(),this._beforeRenderingGroupDrawStage=pt.Create(),this._beforeRenderingMeshStage=pt.Create(),this._afterRenderingMeshStage=pt.Create(),this._afterRenderingGroupDrawStage=pt.Create(),this._afterCameraDrawStage=pt.Create(),this._afterCameraPostProcessStage=pt.Create(),this._afterRenderTargetDrawStage=pt.Create(),this._afterRenderTargetPostProcessStage=pt.Create(),this._afterRenderStage=pt.Create(),this._pointerMoveStage=pt.Create(),this._pointerDownStage=pt.Create(),this._pointerUpStage=pt.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};e=this._engine=e||Ce.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(Ce._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new Ut(this),xa&&(this.postProcessManager=new xa(this)),St()&&this.attachControl(),this._createUbo(),Ue&&(this._imageProcessingConfiguration=new Ue),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,(!t||!t.virtual)&&e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return this._animationRatio!==void 0?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){var r,o,l;if(this._isDisposed)return!1;let t;const i=this.getEngine(),s=i.currentRenderPassId;i.currentRenderPassId=(o=(r=this.activeCamera)==null?void 0:r.renderPassId)!=null?o:s;let n=!0;for(this._pendingData.length>0&&(n=!1),(l=this.prePassRenderer)==null||l.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&n&&(n=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const f of this._isReadyForMeshStage)f.action(h,c)||(n=!1);if(!e)continue;const u=h.material||this.defaultMaterial;if(u)if(u._storeEffectOnSubMeshes)for(const f of h.subMeshes){const d=f.getMaterial();d&&d.hasRenderTargetTextures&&d.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(d)===-1&&(this._processedMaterials.push(d),this._materialsRenderTargets.concatWithNoDuplicate(d.getRenderTargetTextures()))}else u.hasRenderTargetTextures&&u.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(u)===-1&&(this._processedMaterials.push(u),this._materialsRenderTargets.concatWithNoDuplicate(u.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const h of this.activeCameras)h.isReady(!0)||(n=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(n=!1));for(const h of this.particleSystems)h.isReady()||(n=!1);if(this.layers)for(const h of this.layers)h.isReady()||(n=!1);return i.areAllEffectsReady()||(n=!1),i.currentRenderPassId=s,n}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout(()=>{this.unregisterBeforeRender(t)})};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){t!==void 0?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);i!==-1&&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),this._executeWhenReadyTimeoutId===null&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise(t=>{this.executeWhenReady(()=>{t()},e)})}_checkIsReady(e=!1){if(this._registerTransientComponents(),this.isReady(e)){this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}if(this._isDisposed){this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=xi.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,s){!i&&!s&&this._multiviewSceneUbo&&(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),!(this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag)&&(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?mi.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=mi.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,s):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new de(this._engine,void 0,!1,e!=null?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 Hh.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(i=>{this.addMesh(i)}))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return i!==-1&&(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(s=>{this.removeMesh(s)}),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneTransformNodesArray!==-1||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(t!==-1){if(t!==this.transformNodes.length-1){const i=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=i,i._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 t!==-1&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return t!==-1&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(t!==-1){for(const i of this.meshes)i._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(t!==-1&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const i=this.activeCameras.indexOf(e);i!==-1&&this.activeCameras.splice(i,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 t!==-1&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return t!==-1&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return t!==-1&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return t!==-1&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(t!==-1&&ti.uniqueId===e)}getMaterialById(e,t=!1){return this._getMaterial(t,i=>i.id===e)}getMaterialByName(e,t=!1){return this._getMaterial(t,i=>i.name===e)}getLastMaterialById(e,t=!1){for(let i=this.materials.length-1;i>=0;i--)if(this.materials[i].id===e)return this.materials[i];if(t){for(let i=this.multiMaterials.length-1;i>=0;i--)if(this.multiMaterials[i].id===e)return this.multiMaterials[i]}return null}getTextureByUniqueId(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const n=this.getCameraById(e);if(n)return n;const r=this.getBoneById(e);return r||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const s=this.getLightByName(e);if(s)return s;const n=this.getCameraByName(e);if(n)return n;const r=this.getBoneByName(e);return r||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(!this.activeCamera){i&&i("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=n,this._skipEvaluateActiveMeshesCompletely=e,s)for(let r=0;re.dispose())}_evaluateActiveMeshes(){var i;if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1){this._activeMeshes.length>0&&((i=this.activeCamera)==null||i._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const s=this._activeMeshes.length;for(let n=0;n0&&n.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||n.alwaysSelectAsActiveMesh||n.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(n),this.activeCamera._activeMeshes.push(n),r!==n&&r._activate(this._renderId,!1);for(const o of this._preActiveMeshStage)o.action(n);n._activate(this._renderId,!1)&&(n.isAnInstance?n._internalAbstractMeshDataInfo._actAsRegularMesh&&(r=n):r._internalAbstractMeshDataInfo._onlyForInstances=!1,r._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(n,r)),n._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let s=0;s0){const s=this.getActiveSubMeshCandidates(t),n=s.length;i=i||n===1;for(let r=0;r0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const h of this._gatherActiveCameraRenderTargetsStage)h.action(this._renderTargets);let n=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){ee.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let h=0;h0),this._renderId++}for(const h of this._cameraDrawRenderTargetStage)n=h.action(this.activeCamera)||n;this._intermediateRendering=!1}this._engine.currentRenderPassId=(l=(o=(r=e.outputRenderTarget)==null?void 0:r.renderPassId)!=null?o:e.renderPassId)!=null?l:0,n&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&!this.prePass&&this.postProcessManager._prepareFrame();for(const h of this._beforeCameraDrawStage)h.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),s.snapshotRendering&&s.snapshotRenderingMode===1&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const h of this._afterCameraDrawStage)h.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const h=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,h)}for(const h of this._afterCameraPostProcessStage)h.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(e.cameraRigMode===0||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let i=0;i-1&&(s.trigger===13&&s._executeCurrent(Dt.CreateNew(t,void 0,r)),(!t.actionManager.hasSpecificTrigger(13,h=>{const c=h.mesh?h.mesh:h;return r===c})||s.trigger===13)&&t._intersectionsInProgress.splice(l,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Qe.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Qe.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const n=this._engine.getLockstepMaxSteps();let r=Math.floor(e/t);for(r=Math.min(r,n);e>0&&s0)for(let l=0;l0),this._intermediateRendering=!0;for(let l=0;l0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=(o=s==null?void 0:s.renderPassId)!=null?o:0,this.activeCamera=s,this._activeCamera&&this._activeCamera.cameraRigMode!==22&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const l of this._beforeClearStage)l.action();this._clearFrameBuffer(this.activeCamera);for(const l of this._gatherRenderTargetsStage)l.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let l=0;l0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const l of this._afterRenderStage)l.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let l=0;l{n.onAnimationEndObservable.clear(),n.onAnimationEnd=null}),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const n of e)n.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(n){U.Error("An error occurred while calling onDisposeObservable!",n)}if(this.detachControl(),this._engine.getInputElement())for(let n=0;nn.dispose(!0)),this._disposeList(this.transformNodes,n=>n.dispose(!0));const i=this.cameras;this._disposeList(i),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 s=this._engine.scenes.indexOf(this);s>-1&&this._engine.scenes.splice(s,1),Ce._LastCreatedScene===this&&(this._engine.scenes.length>0?Ce._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:Ce._LastCreatedScene=null),s=this._engine._virtualScenes.indexOf(this),s>-1&&this._engine._virtualScenes.splice(s,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t!=null?t:s=>s.dispose();for(const s of i)t(s);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach(s=>{if(s.computeWorldMatrix(!0),!s.subMeshes||s.subMeshes.length===0||s.infiniteDistance)return;const n=s.getBoundingInfo(),r=n.boundingBox.minimumWorld,o=n.boundingBox.maximumWorld;v.CheckExtends(r,t,i),v.CheckExtends(o,t,i)}),{min:t,max:i}}createPickingRay(e,t,i,s,n=!1){throw Te("Ray")}createPickingRayToRef(e,t,i,s,n,r=!1,o=!1){throw Te("Ray")}createPickingRayInCameraSpace(e,t,i){throw Te("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw Te("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,n,r){const o=Te("Ray",!0);return o&&U.Warn(o),new ns}pickWithBoundingInfo(e,t,i,s,n){const r=Te("Ray",!0);return r&&U.Warn(r),new ns}pickWithRay(e,t,i,s){throw Te("Ray")}multiPick(e,t,i,s,n){throw Te("Ray")}multiPickWithRay(e,t,i){throw Te("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(t===void 0)return e;const s=[];for(const n in e){const r=e[n];ze&&ze.MatchesQuery(r,t)&&(!i||i(r))&&s.push(r)}return s}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,s)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,s,n,r,o){const l=vs(e,t,i,s?this.offlineProvider:void 0,n,r,o);return this._activeRequests.push(l),l.onCompleteObservable.add(h=>{this._activeRequests.splice(this._activeRequests.indexOf(h),1)}),l}_loadFileAsync(e,t,i,s,n){return new Promise((r,o)=>{this._loadFile(e,l=>{r(l)},t,i,s,(l,h)=>{o(h)},n)})}_requestFile(e,t,i,s,n,r,o){const l=Za(e,t,i,s?this.offlineProvider:void 0,n,r,o);return this._activeRequests.push(l),l.onCompleteObservable.add(h=>{this._activeRequests.splice(this._activeRequests.indexOf(h),1)}),l}_requestFileAsync(e,t,i,s,n){return new Promise((r,o)=>{this._requestFile(e,l=>{r(l)},t,i,s,l=>{o(l)},n)})}_readFile(e,t,i,s,n){const r=An(e,t,i,s,n);return this._activeRequests.push(r),r.onCompleteObservable.add(o=>{this._activeRequests.splice(this._activeRequests.indexOf(o),1)}),r}_readFileAsync(e,t,i){return new Promise((s,n)=>{this._readFile(e,r=>{s(r)},t,i,r=>{n(r)})})}getPerfCollector(){throw Te("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}Qe.FOGMODE_NONE=0;Qe.FOGMODE_EXP=1;Qe.FOGMODE_EXP2=2;Qe.FOGMODE_LINEAR=3;Qe.MinDeltaTime=1;Qe.MaxDeltaTime=1e3;ft("BABYLON.Scene",Qe);class G_{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new Q,this._onClonedObservable=new Q}}class mt{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,s){const n=this._NodeConstructors[e];return n?n(t,i,s):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return this._nodeDataStorage._doNotSerialize?!0:this._parentNode?this._parentNode.doNotSerialize:!1}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&&this._parentNode._children!==void 0&&this._parentNode._children!==null){const i=this._parentNode._children.indexOf(this);i!==-1&&this._parentNode._children.splice(i,1),!e&&!this._nodeDataStorage._isDisposed&&this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&((this._parentNode._children===void 0||this._parentNode._children===null)&&(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(){this._nodeDataStorage._sceneRootNodesIndex===-1&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(this._nodeDataStorage._sceneRootNodesIndex!==-1){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,i=!0){this._isDirty=!1,this._nodeDataStorage=new G_,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new Q,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=O.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new Q,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||Ce.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&this._addToSceneRootNodes()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return this._behaviors.indexOf(e)!==-1?this:(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 t===-1?this:(this._behaviors[t].detach(),this._behaviors.splice(t,1),this)}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={}}updateCache(e){!e&&this.isSynchronized()||this._updateCache()}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return this._parentNode?this._parentNode._isDirty||this._parentUpdateId!==this._parentNode._childUpdateId?!1:this._parentNode.isSynchronized():!0}isSynchronized(){return this._parentNode&&!this.isSynchronizedWithParent()?!1: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 e===!1?this._nodeDataStorage._isEnabled:this._nodeDataStorage._isEnabled?this._nodeDataStorage._isParentEnabled:!1}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=this._parentNode?this._parentNode.isEnabled():!0,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?!0:this.parent.isDescendantOf(e):!1}_getDescendants(e,t=!1,i){if(this._children)for(let s=0;s(!t||t(s))&&s.cullingStrategy!==void 0),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;tnew mt(e,this.getScene()),this);if(t&&(s.parent=t),!i){const n=this.getDescendants(!0);for(let r=0;r{throw Te("AnimationRange")};mt._NodeConstructors={};D([B()],mt.prototype,"name",void 0);D([B()],mt.prototype,"id",void 0);D([B()],mt.prototype,"uniqueId",void 0);D([B()],mt.prototype,"state",void 0);D([B()],mt.prototype,"metadata",void 0);const z_=O.Compose(v.One(),le.FromEulerAngles(0,Math.PI,0),v.Zero());class Ie extends mt{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&Ie.BILLBOARDMODE_USE_POSITION)!==0,this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==Ie.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t,!1),this._forward=new v(0,0,1),this._up=new v(0,1,0),this._right=new v(1,0,0),this._position=v.Zero(),this._rotation=v.Zero(),this._rotationQuaternion=null,this._scaling=v.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=Ie.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=O.Zero(),this._usePivotMatrix=!1,this._absolutePosition=v.Zero(),this._absoluteScaling=v.Zero(),this._absoluteRotationQuaternion=le.Identity(),this._pivotMatrix=O.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new Q,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return v.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return v.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return v.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=O.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==Ie.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)}_initCache(){super._initCache();const e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1,e.useBillboardPath=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=O.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const s=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);s&&i&&i(this,s);for(const n of this.getChildTransformNodes(!0))n.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||le.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,s;if(e.x===void 0){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],s=arguments[2]}else t=e.x,i=e.y,s=e.z;if(this.parent){const n=N.Matrix[0];this.parent.getWorldMatrix().invertToRef(n),v.TransformCoordinatesFromFloatsToRef(t,i,s,n,this.position)}else this.position.x=t,this.position.y=i,this.position.z=s;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=v.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=N.Matrix[0];return this._localMatrix.invertToRef(e),v.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=v.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,n=0){const r=Ie._LookAtVectorCache,o=n===0?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,r),this.setDirection(r,t,i,s),n===1&&this.parent)if(this.rotationQuaternion){const l=N.Matrix[0];this.rotationQuaternion.toRotationMatrix(l);const h=N.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(h),h.invert(),l.multiplyToRef(h,l),this.rotationQuaternion.fromRotationMatrix(l)}else{const l=N.Quaternion[0];le.FromEulerVectorToRef(this.rotation,l);const h=N.Matrix[0];l.toRotationMatrix(h);const c=N.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),h.multiplyToRef(c,h),l.fromRotationMatrix(h),l.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=v.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return v.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const n=-Math.atan2(e.z,e.x)+Math.PI/2,r=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,r);return this.rotationQuaternion?le.RotationYawPitchRollToRef(n+t,o+i,s,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=n+t,this.rotation.z=s),this}setPivotPoint(e,t=0){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==1){const s=N.Matrix[0];i.invertToRef(s),e=v.TransformCoordinates(e,s)}return this.setPivotMatrix(O.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=v.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=v.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),v.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;const s=N.Quaternion[0],n=N.Vector3[0],r=N.Vector3[1],o=N.Matrix[1];O.IdentityToRef(o);const l=N.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=Ie._TmpRotation,le.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),O.ComposeToRef(this.scaling,h,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(o),l.multiplyToRef(o,l)),l.decompose(r,s,n,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(r),this.position.copyFrom(n),this.parent=e,i&&this.setPivotMatrix(O.Identity()),this}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.setParent(null,t),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling===e?!1:(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0));let s;if(!i||i===0)s=le.RotationAxisToRef(e,t,Ie._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);else{if(this.parent){const n=this.parent.getWorldMatrix(),r=N.Matrix[0];n.invertToRef(r),e=v.TransformNormal(e,r),n.determinant()<0&&(t*=-1)}s=le.RotationAxisToRef(e,t,Ie._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=le.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=N.Vector3[0],n=N.Vector3[1],r=N.Vector3[2],o=N.Quaternion[0],l=N.Matrix[0],h=N.Matrix[1],c=N.Matrix[2],u=N.Matrix[3];return e.subtractToRef(this.position,s),O.TranslationToRef(s.x,s.y,s.z,l),O.TranslationToRef(-s.x,-s.y,-s.z,h),O.RotationAxisToRef(t,i,c),h.multiplyToRef(c,u),u.multiplyToRef(l,u),u.decompose(n,o,r),this.position.addInPlace(r),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(!i||i===0){const n=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(n)}else this.setAbsolutePosition(this.getAbsolutePosition().add(s));return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=N.Quaternion[1],le.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const n=N.Quaternion[0];return le.RotationYawPitchRollToRef(t,e,i,n),s.multiplyInPlace(n),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==Ie.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const n=this._getEffectiveParent(),r=Ie._TmpScaling;let o=this._position;if(this._infiniteDistance&&!this.parent&&t){const h=t.getWorldMatrix(),c=new v(h.m[12],h.m[13],h.m[14]);o=Ie._TmpTranslation,o.copyFromFloats(this._position.x+c.x,this._position.y+c.y,this._position.z+c.z)}r.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant);let l;if(this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,l=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(le.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(l=Ie._TmpRotation,le.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),this._usePivotMatrix){const h=N.Matrix[1];O.ScalingToRef(r.x,r.y,r.z,h);const c=N.Matrix[0];l.toRotationMatrix(c),this._pivotMatrix.multiplyToRef(h,N.Matrix[4]),N.Matrix[4].multiplyToRef(c,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else O.ComposeToRef(r,l,o,this._localMatrix);if(n&&n.getWorldMatrix){if(e&&n.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){const f=this.parent;f.getSkeleton().prepare(),f.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),N.Matrix[7])}else N.Matrix[7].copyFrom(n.getWorldMatrix());const h=N.Vector3[5],c=N.Vector3[6],u=N.Quaternion[0];N.Matrix[7].decompose(c,u,h),O.ScalingToRef(c.x,c.y,c.z,N.Matrix[7]),N.Matrix[7].setTranslation(h),Ie.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(u,h),this._localMatrix.setTranslation(h)),this._localMatrix.multiplyToRef(N.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const h=this.parent;h.getSkeleton().prepare(),this._localMatrix.multiplyToRef(h.getFinalMatrix(),N.Matrix[6]),N.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(n.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const h=N.Vector3[0];if(this._worldMatrix.getTranslationToRef(h),N.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&N.Matrix[1].multiplyToRef(z_,N.Matrix[1]),N.Matrix[1].setTranslationFromFloats(0,0,0),N.Matrix[1].invertToRef(N.Matrix[0]),(this.billboardMode&Ie.BILLBOARDMODE_ALL)!==Ie.BILLBOARDMODE_ALL){N.Matrix[0].decompose(void 0,N.Quaternion[0],void 0);const c=N.Vector3[1];N.Quaternion[0].toEulerAnglesToRef(c),(this.billboardMode&Ie.BILLBOARDMODE_X)!==Ie.BILLBOARDMODE_X&&(c.x=0),(this.billboardMode&Ie.BILLBOARDMODE_Y)!==Ie.BILLBOARDMODE_Y&&(c.y=0),(this.billboardMode&Ie.BILLBOARDMODE_Z)!==Ie.BILLBOARDMODE_Z&&(c.z=0),O.RotationYawPitchRollToRef(c.y,c.x,c.z,N.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(N.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(N.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const h=N.Vector3[0];this._worldMatrix.getTranslationToRef(h);const c=t.globalPosition;this._worldMatrix.invertToRef(N.Matrix[1]);const u=N.Vector3[1];v.TransformCoordinatesToRef(c,N.Matrix[1],u),u.normalize();const f=-Math.atan2(u.z,u.x)+Math.PI/2,d=Math.sqrt(u.x*u.x+u.z*u.z),p=-Math.atan2(u.y,d);if(le.RotationYawPitchRollToRef(f,p,0,N.Quaternion[0]),(this.billboardMode&Ie.BILLBOARDMODE_ALL)!==Ie.BILLBOARDMODE_ALL){const g=N.Vector3[1];N.Quaternion[0].toEulerAnglesToRef(g),(this.billboardMode&Ie.BILLBOARDMODE_X)!==Ie.BILLBOARDMODE_X&&(g.x=0),(this.billboardMode&Ie.BILLBOARDMODE_Y)!==Ie.BILLBOARDMODE_Y&&(g.y=0),(this.billboardMode&Ie.BILLBOARDMODE_Z)!==Ie.BILLBOARDMODE_Z&&(g.z=0),O.RotationYawPitchRollToRef(g.y,g.x,g.z,N.Matrix[0])}else O.FromQuaternionToRef(N.Quaternion[0],N.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(N.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(N.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):n&&n._nonUniformScaling?this._updateNonUniformScalingState(n._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=O.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const t=this.getChildren();for(let i=0;inew Ie(e,this.getScene()),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const n=this.getDescendants(!0);for(let r=0;rnew Ie(e.name,t),e,t,i);if(e.localMatrix?s.setPreTransformMatrix(O.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(O.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let n=0;n(!t||t(s))&&s instanceof Ie),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const i=this._parentContainer.transformNodes.indexOf(this);i>-1&&this._parentContainer.transformNodes.splice(i,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const i=this.getChildTransformNodes(!0);for(const s of i)s.parent=null,s.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let s=null,n=null;t&&(this.rotationQuaternion?(n=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const r=this.getHierarchyBoundingVectors(e,i),o=r.max.subtract(r.min),l=Math.max(o.x,o.y,o.z);if(l===0)return this;const h=1/l;return this.scaling.scaleInPlace(h),t&&(this.rotationQuaternion&&n?this.rotationQuaternion.copyFrom(n):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}Ie.BILLBOARDMODE_NONE=0;Ie.BILLBOARDMODE_X=1;Ie.BILLBOARDMODE_Y=2;Ie.BILLBOARDMODE_Z=4;Ie.BILLBOARDMODE_ALL=7;Ie.BILLBOARDMODE_USE_POSITION=128;Ie.BillboardUseParentOrientation=!1;Ie._TmpRotation=le.Zero();Ie._TmpScaling=v.Zero();Ie._TmpTranslation=v.Zero();Ie._LookAtVectorCache=new v(0,0,0);Ie._RotationAxisCache=new le;D([bi("position")],Ie.prototype,"_position",void 0);D([bi("rotation")],Ie.prototype,"_rotation",void 0);D([Kp("rotationQuaternion")],Ie.prototype,"_rotationQuaternion",void 0);D([bi("scaling")],Ie.prototype,"_scaling",void 0);D([B("billboardMode")],Ie.prototype,"_billboardMode",void 0);D([B()],Ie.prototype,"scalingDeterminant",void 0);D([B("infiniteDistance")],Ie.prototype,"_infiniteDistance",void 0);D([B()],Ie.prototype,"ignoreNonUniformScaling",void 0);D([B()],Ie.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);function Sa(a,e,t){try{const i=a.next();i.done?e(i):i.value?i.value.then(()=>{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function W_(a=25){let e;return(t,i,s)=>{const n=performance.now();e===void 0||n-e>a?(e=n,setTimeout(()=>{Sa(t,i,s)},0)):Sa(t,i,s)}}function Kh(a,e,t,i,s){const n=()=>{let r;const o=l=>{l.done?t(l.value):r===void 0?r=!0:n()};do r=void 0,!s||!s.aborted?e(a,o,i):i(new Error("Aborted")),r===void 0&&(r=!1);while(r)};n()}function co(a,e){let t;return Kh(a,Sa,i=>t=i,i=>{throw i},e),t}function X_(a,e,t){return new Promise((i,s)=>{Kh(a,e,i,s,t)})}function H_(a,e){return(...t)=>co(a(...t),e)}class ve extends mt{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 i,s,n,r;let e=0,t=0;if(this.mode===ve.PERSPECTIVE_CAMERA)this.fovMode===ve.FOVMODE_VERTICAL_FIXED?(t=this.minZ*2*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=this.minZ*2*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const o=this.getEngine().getRenderWidth()/2,l=this.getEngine().getRenderHeight()/2;e=((i=this.orthoRight)!=null?i:o)-((s=this.orthoLeft)!=null?s:-o),t=((n=this.orthoTop)!=null?n:l)-((r=this.orthoBottom)!=null?r:-l)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,s=!0){super(e,i,!1),this._position=v.Zero(),this._upVector=v.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=ve.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Qs(0,0,1,1),this.layerMask=268435455,this.fovMode=ve.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=ve.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new Q,this.onProjectionMatrixChangedObservable=new Q,this.onAfterCheckInputsObservable=new Q,this.onRestoreStateObservable=new Q,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new O,this._postProcesses=new Array,this._activeMeshes=new Vt(256),this._globalPosition=v.Zero(),this._computedViewMatrix=O.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=O.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=le.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId("Camera ".concat(e))}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_restoreStateValues(){return this._stateStored?(this.fov=this._storedFov,!0):!1}restoreState(){return this._restoreStateValues()?(this.onRestoreStateObservable.notifyObservers(this),!0):!1}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(U.Error("You're trying to reuse a post process not defined as reusable."),0):(t==null||t<0?this._postProcesses.push(e):this._postProcesses[t]===null?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);t!==-1&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()?this._worldMatrix:(this.getViewMatrix(),this._worldMatrix)}_getViewMatrix(){return O.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._computedViewMatrix)}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,e!==void 0&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){var n,r,o,l,h,c,u,f,d,p,g,_,m,x,I,T,y,b,S;if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),i=this.getScene(),s=t.useReverseDepthBuffer;if(this.mode===ve.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=t.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let A;i.useRightHandedSystem?A=O.PerspectiveFovRHToRef:A=O.PerspectiveFovLHToRef,A(this.fov,t.getAspectRatio(this),s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===ve.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{const A=t.getRenderWidth()/2,M=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?O.ObliqueOffCenterRHToRef((n=this.orthoLeft)!=null?n:-A,(r=this.orthoRight)!=null?r:A,(o=this.orthoBottom)!=null?o:-M,(l=this.orthoTop)!=null?l:M,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):O.OrthoOffCenterRHToRef((h=this.orthoLeft)!=null?h:-A,(c=this.orthoRight)!=null?c:A,(u=this.orthoBottom)!=null?u:-M,(f=this.orthoTop)!=null?f:M,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?O.ObliqueOffCenterLHToRef((d=this.orthoLeft)!=null?d:-A,(p=this.orthoRight)!=null?p:A,(g=this.orthoBottom)!=null?g:-M,(_=this.orthoTop)!=null?_:M,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):O.OrthoOffCenterLHToRef((m=this.orthoLeft)!=null?m:-A,(x=this.orthoRight)!=null?x:A,(I=this.orthoBottom)!=null?I:-M,(T=this.orthoTop)!=null?T:M,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=(y=this.oblique)==null?void 0:y.angle,this._cache.obliqueLength=(b=this.oblique)==null?void 0:b.length,this._cache.obliqueOffset=(S=this.oblique)==null?void 0:S.offset,this._cache.renderWidth=t.getRenderWidth(),this._cache.renderHeight=t.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){const t=this,i=this;return(t.radius||(i.target?v.Distance(this.position,i.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?mi.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=mi.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let i=!1;return this.rigCameras.forEach(s=>{s._updateFrustumPlanes(),i=i||e.isInFrustum(s._frustumPlanes)}),i}else return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw Te("Ray")}getForwardRayToRef(e,t=100,i,s){throw Te("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 s=this._rigCameras.pop();s&&s.dispose()}if(this._parentContainer){const s=this._parentContainer.cameras.indexOf(this);s>-1&&this._parentContainer.cameras.splice(s,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==ve.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let s=this._postProcesses.length;for(;--s>=0;){const n=this._postProcesses[s];n&&n.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 i=this._rigCameras.pop();i&&i.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=ee.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==ve.RIG_MODE_NONE){const i=this.createRigCamera(this.name+"_L",0);i&&(i._isLeftCamera=!0);const s=this.createRigCamera(this.name+"_R",1);s&&(s._isRightCamera=!0),i&&s&&(this._rigCameras.push(i),this._rigCameras.push(s))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return O.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,e==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=ee.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eve._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=ve.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),n=Ae.Parse(s,e,t);if(e.parentId!==void 0&&(n._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),n.inputs&&(n.inputs.parse(e),n._setupInputs()),e.upVector&&(n.upVector=v.FromArray(e.upVector)),n.setPosition&&(n.position.copyFromFloats(0,0,0),n.setPosition(v.FromArray(e.position))),e.target&&n.setTarget&&n.setTarget(v.FromArray(e.target)),e.cameraRigMode){const r=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};n.setCameraRigMode(e.cameraRigMode,r)}if(e.animations){for(let r=0;r{throw Te("UniversalCamera")};ve.PERSPECTIVE_CAMERA=0;ve.ORTHOGRAPHIC_CAMERA=1;ve.FOVMODE_VERTICAL_FIXED=0;ve.FOVMODE_HORIZONTAL_FIXED=1;ve.RIG_MODE_NONE=0;ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;ve.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;ve.RIG_MODE_STEREOSCOPIC_INTERLACED=14;ve.RIG_MODE_VR=20;ve.RIG_MODE_CUSTOM=22;ve.ForceAttachControlToAlwaysPreventDefault=!1;D([bi("position")],ve.prototype,"_position",void 0);D([bi("upVector")],ve.prototype,"_upVector",void 0);D([B()],ve.prototype,"orthoLeft",null);D([B()],ve.prototype,"orthoRight",null);D([B()],ve.prototype,"orthoBottom",null);D([B()],ve.prototype,"orthoTop",null);D([B()],ve.prototype,"fov",void 0);D([B()],ve.prototype,"projectionPlaneTilt",void 0);D([B()],ve.prototype,"minZ",void 0);D([B()],ve.prototype,"maxZ",void 0);D([B()],ve.prototype,"inertia",void 0);D([B()],ve.prototype,"mode",null);D([B()],ve.prototype,"layerMask",void 0);D([B()],ve.prototype,"fovMode",void 0);D([B()],ve.prototype,"cameraRigMode",void 0);D([B()],ve.prototype,"interaxialDistance",void 0);D([B()],ve.prototype,"isStereoscopicSideBySide",void 0);class Ea{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class es{constructor(e,t,i){this.vectors=Bt.BuildArray(8,v.Zero),this.center=v.Zero(),this.centerWorld=v.Zero(),this.extendSize=v.Zero(),this.extendSizeWorld=v.Zero(),this.directions=Bt.BuildArray(3,v.Zero),this.vectorsWorld=Bt.BuildArray(8,v.Zero),this.minimumWorld=v.Zero(),this.maximumWorld=v.Zero(),this.minimum=v.Zero(),this.maximum=v.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,n=e.y,r=e.z,o=t.x,l=t.y,h=t.z,c=this.vectors;this.minimum.copyFromFloats(s,n,r),this.maximum.copyFromFloats(o,l,h),c[0].copyFromFloats(s,n,r),c[1].copyFromFloats(o,l,h),c[2].copyFromFloats(o,n,r),c[3].copyFromFloats(s,l,r),c[4].copyFromFloats(s,n,h),c[5].copyFromFloats(o,l,r),c[6].copyFromFloats(s,l,h),c[7].copyFromFloats(o,n,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||O.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=es._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const n=s*e,r=i.scaleInPlace(n*.5),o=this.center.subtractToRef(r,t[1]),l=this.center.addToRef(r,t[2]);return this.reConstruct(o,l,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,n=this.vectorsWorld,r=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let o=0;o<8;++o)n[o].copyFrom(r[o]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let o=0;o<8;++o){const l=n[o];v.TransformCoordinatesToRef(r[o],e,l),t.minimizeInPlace(l),i.maximizeInPlace(l)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}v.FromArrayToRef(e.m,0,s[0]),v.FromArrayToRef(e.m,4,s[1]),v.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return es.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return es.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,n=t.y,r=t.z,o=i.x,l=i.y,h=i.z,c=e.x,u=e.y,f=e.z,d=-Ne;return!(o-cc-s||l-uu-n||h-ff-r)}intersectsSphere(e){return es.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,n=i.x,r=i.y,o=i.z,l=s.x,h=s.y,c=s.z,u=e.x,f=e.y,d=e.z,p=t.x,g=t.y,_=t.z;return!(lp||hg||c_)}dispose(){var e,t;(e=this._drawWrapperFront)==null||e.dispose(),(t=this._drawWrapperBack)==null||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const n=es._TmpVector3[0];return v.ClampToRef(i,e,t,n),v.DistanceSquared(i,n)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let n=0;n<8;++n)if(s.dotCoordinate(e[n])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const n=t[i];for(let r=0;r<8;++r)if(n.dotCoordinate(e[r])>=0){s=!1;break}if(s)return!1}return!0}}es._TmpVector3=Bt.BuildArray(3,v.Zero);class ws{constructor(e,t,i){this.center=v.Zero(),this.centerWorld=v.Zero(),this.minimum=v.Zero(),this.maximum=v.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=v.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=s*.5,this._update(i||O.IdentityReadOnly)}scale(e){const t=this.radius*e,i=ws._TmpVector3,s=i[0].setAll(t),n=this.center.subtractToRef(s,i[1]),r=this.center.addToRef(s,i[2]);return this.reConstruct(n,r,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{v.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=ws._TmpVector3[0];v.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,i=this.radiusWorld;for(let s=0;s<6;s++)if(e[s].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=v.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const i=v.Dot(e.centerWorld,a),s=Math.abs(v.Dot(e.directions[0],a))*e.extendSize.x,n=Math.abs(v.Dot(e.directions[1],a))*e.extendSize.y,r=Math.abs(v.Dot(e.directions[2],a))*e.extendSize.z,o=s+n+r;t.min=i-o,t.max=i+o},$t=(a,e,t)=>(fl(a,e,ia),fl(a,t,sa),!(ia.min>sa.max||sa.min>ia.max));class si{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new es(e,t,i),this.boundingSphere=new ws(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=si._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=si._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=v.Minimize(this.minimum,e),i=v.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=N.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=N.Vector3[0];return v.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),v.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return(t===2||t===3)&&this.boundingSphere.isCenterInFrustum(e)?!0:this.boundingSphere.isInFrustum(e)?t===1||t===3?!0:this.boundingBox.isInFrustum(e):!1}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,si._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(!ws.Intersects(this.boundingSphere,e.boundingSphere)||!es.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!(!$t(i.directions[0],i,s)||!$t(i.directions[1],i,s)||!$t(i.directions[2],i,s)||!$t(s.directions[0],i,s)||!$t(s.directions[1],i,s)||!$t(s.directions[2],i,s)||!$t(v.Cross(i.directions[0],s.directions[0]),i,s)||!$t(v.Cross(i.directions[0],s.directions[1]),i,s)||!$t(v.Cross(i.directions[0],s.directions[2]),i,s)||!$t(v.Cross(i.directions[1],s.directions[0]),i,s)||!$t(v.Cross(i.directions[1],s.directions[1]),i,s)||!$t(v.Cross(i.directions[1],s.directions[2]),i,s)||!$t(v.Cross(i.directions[2],s.directions[0]),i,s)||!$t(v.Cross(i.directions[2],s.directions[1]),i,s)||!$t(v.Cross(i.directions[2],s.directions[2]),i,s))}}si._TmpVector3=Bt.BuildArray(2,v.Zero);class Dr{static extractMinAndMaxIndexed(e,t,i,s,n,r){for(let o=i;o!Array.isArray(a)&&!Array.isArray(e))],Dr,"extractMinAndMaxIndexed",null);D([ss.filter((...[a])=>!Array.isArray(a))],Dr,"extractMinAndMax",null);function K_(a,e,t,i,s=null){const n=new v(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new v(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return Dr.extractMinAndMaxIndexed(a,e,t,i,n,r),s&&(n.x-=n.x*s.x+s.y,n.y-=n.y*s.x+s.y,n.z-=n.z*s.x+s.y,r.x+=r.x*s.x+s.y,r.y+=r.y*s.x+s.y,r.z+=r.z*s.x+s.y),{minimum:n,maximum:r}}function Yh(a,e,t,i=null,s){const n=new v(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new v(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return s||(s=3),Dr.extractMinAndMax(a,e,t,s,n,r),i&&(n.x-=n.x*i.x+i.y,n.y-=n.y*i.x+i.y,n.z-=n.z*i.x+i.y,r.x+=r.x*i.x+i.y,r.y+=r.y*i.x+i.y,r.z+=r.z*i.x+i.y),{minimum:n,maximum:r}}class vi{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:(e=this._getDrawWrapper())==null?void 0:e.defines}set materialDefines(e){var i;const t=(i=this._mainDrawWrapperOverride)!=null?i:this._getDrawWrapper(void 0,!0);t.defines=e}_getDrawWrapper(e,t=!1){e=e!=null?e:this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new ln(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&((i=this._drawWrappers[e])==null||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:(t=(e=this._getDrawWrapper())==null?void 0:e.effect)!=null?t:null}get _drawWrapper(){var e;return(e=this._mainDrawWrapperOverride)!=null?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const n=this._drawWrapper;n.setEffect(e,t,s),i!==void 0&&(n.materialContext=i),e||(n.defines=null,n.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers)if(e!==void 0){this._removeDrawWrapper(e);return}else for(const t of this._drawWrappers)t==null||t.dispose();this._drawWrappers=[]}static AddToMesh(e,t,i,s,n,r,o,l=!0){return new vi(e,t,i,s,n,r,o,l)}constructor(e,t,i,s,n,r,o,l=!0,h=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=n,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=r,this._renderingMesh=o||r,h&&r.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=r.subMeshes.length-1,l&&(this.refreshBoundingInfo(),r.computeWorldMatrix(!0))}get IsGlobal(){return this.verticesStart===0&&this.verticesCount===this._mesh.getTotalVertices()&&this.indexStart===0&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){const e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){var i;const t=(i=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))!=null?i:this._renderingMesh.material;if(t){if(this._isMultiMaterial(t)){const s=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==s&&(this._currentMaterial=s,this.resetDrawCache()),s}}else return e?this._mesh.getScene().defaultMaterial:null;return t}_isMultiMaterial(e){return e.getSubMaterial!==void 0}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(E.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(this.indexStart===0&&this.indexCount===t.length){const s=this._renderingMesh.getBoundingInfo();i={minimum:s.minimum.clone(),maximum:s.maximum.clone()}}else i=K_(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new si(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):!1}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return t?t.isCompletelyInFrustum(e):!1}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 s=this.indexStart;sl&&(l=f)}return new vi(e,o,l-o+1,t,i,s,n,r)}}class na{}class j{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=H_(this._applyToCoroutine.bind(this)),this.uniqueId=j._UniqueIDGenerator,j._UniqueIDGenerator++}set(e,t){switch(e.length||U.Warn("Setting vertex data kind '".concat(t,"' with an empty array")),t){case E.PositionKind:this.positions=e;break;case E.NormalKind:this.normals=e;break;case E.TangentKind:this.tangents=e;break;case E.UVKind:this.uvs=e;break;case E.UV2Kind:this.uvs2=e;break;case E.UV3Kind:this.uvs3=e;break;case E.UV4Kind:this.uvs4=e;break;case E.UV5Kind:this.uvs5=e;break;case E.UV6Kind:this.uvs6=e;break;case E.ColorKind:this.colors=e;break;case E.MatricesIndicesKind:this.matricesIndices=e;break;case E.MatricesWeightsKind:this.matricesWeights=e;break;case E.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case E.MatricesWeightsExtraKind:this.matricesWeightsExtra=e;break}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData(E.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(E.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(E.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(E.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(E.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(E.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(E.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(E.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(E.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(E.ColorKind,this.colors,t),this.hasVertexAlpha&&e.hasVertexAlpha!==void 0&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(E.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(E.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(E.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(E.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const s=e;s.subMeshes=[];for(const n of this.materialInfos)new vi(n.materialIndex,n.verticesStart,n.verticesCount,n.indexStart,n.indexCount,s)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(E.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(E.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(E.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(E.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(E.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(E.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(E.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(E.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(E.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(E.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(E.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(E.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(E.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(E.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const n=N.Vector3[0],r=N.Vector3[1];for(let o=i;o({vertexData:o})):[{vertexData:e}];return co(this._mergeCoroutine(void 0,r,t,!1,i,s,n))}*_mergeCoroutine(e,t,i=!1,s,n,r=!1,o=!1){var d,p,g,_;this._validate();let l=t.map(m=>m.vertexData),h=this;if(o)for(const m of l)m&&(m._validate(),!this.normals&&m.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&m.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&m.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&m.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&m.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&m.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&m.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&m.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&m.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&m.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&m.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&m.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&m.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const m of l)if(m){if(o)this.normals&&!m.normals&&(m.normals=new Float32Array(m.positions.length)),this.tangents&&!m.tangents&&(m.tangents=new Float32Array(m.positions.length/3*4)),this.uvs&&!m.uvs&&(m.uvs=new Float32Array(m.positions.length/3*2)),this.uvs2&&!m.uvs2&&(m.uvs2=new Float32Array(m.positions.length/3*2)),this.uvs3&&!m.uvs3&&(m.uvs3=new Float32Array(m.positions.length/3*2)),this.uvs4&&!m.uvs4&&(m.uvs4=new Float32Array(m.positions.length/3*2)),this.uvs5&&!m.uvs5&&(m.uvs5=new Float32Array(m.positions.length/3*2)),this.uvs6&&!m.uvs6&&(m.uvs6=new Float32Array(m.positions.length/3*2)),this.colors&&!m.colors&&(m.colors=new Float32Array(m.positions.length/3*4),m.colors.fill(1)),this.matricesIndices&&!m.matricesIndices&&(m.matricesIndices=new Float32Array(m.positions.length/3*4)),this.matricesWeights&&!m.matricesWeights&&(m.matricesWeights=new Float32Array(m.positions.length/3*4)),this.matricesIndicesExtra&&!m.matricesIndicesExtra&&(m.matricesIndicesExtra=new Float32Array(m.positions.length/3*4)),this.matricesWeightsExtra&&!m.matricesWeightsExtra&&(m.matricesWeightsExtra=new Float32Array(m.positions.length/3*4));else if(m._validate(),!this.normals!=!m.normals||!this.tangents!=!m.tangents||!this.uvs!=!m.uvs||!this.uvs2!=!m.uvs2||!this.uvs3!=!m.uvs3||!this.uvs4!=!m.uvs4||!this.uvs5!=!m.uvs5||!this.uvs6!=!m.uvs6||!this.colors!=!m.colors||!this.matricesIndices!=!m.matricesIndices||!this.matricesWeights!=!m.matricesWeights||!this.matricesIndicesExtra!=!m.matricesIndicesExtra||!this.matricesWeightsExtra!=!m.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes")}if(r){let m=0,x=0,I=0;const T=[];let y=null;const b=[];for(const A of this.splitBasedOnMaterialID())b.push({vertexData:A,transform:e});for(const A of t)if(A.vertexData)for(const M of A.vertexData.splitBasedOnMaterialID())b.push({vertexData:M,transform:A.transform});b.sort((A,M)=>{const C=A.vertexData.materialInfos?A.vertexData.materialInfos[0].materialIndex:0,w=M.vertexData.materialInfos?M.vertexData.materialInfos[0].materialIndex:0;return C>w?1:C===w?0:-1});for(const A of b){const M=A.vertexData;if(M.materialInfos?m=M.materialInfos[0].materialIndex:m=0,y&&y.materialIndex===m)y.indexCount+=M.indices.length,y.verticesCount+=M.positions.length/3;else{const C=new na;C.materialIndex=m,C.indexStart=x,C.indexCount=M.indices.length,C.verticesStart=I,C.verticesCount=M.positions.length/3,T.push(C),y=C}x+=M.indices.length,I+=M.positions.length/3}const S=b.splice(0,1)[0];h=S.vertexData,e=S.transform,l=b.map(A=>A.vertexData),t=b,this.materialInfos=T}const c=l.reduce((m,x)=>{var I,T;return m+((T=(I=x.indices)==null?void 0:I.length)!=null?T:0)},(p=(d=h.indices)==null?void 0:d.length)!=null?p:0);let f=n||l.some(m=>m.indices===h.indices)?(g=h.indices)==null?void 0:g.slice():h.indices;if(c>0){let m=(_=f==null?void 0:f.length)!=null?_:0;if(f||(f=new Array(c)),f.length!==c){if(Array.isArray(f))f.length=c;else{const I=i||f instanceof Uint32Array?new Uint32Array(c):new Uint16Array(c);I.set(f),f=I}e&&e.determinant()<0&&j._FlipFaces(f,0,m)}let x=h.positions?h.positions.length/3:0;for(const{vertexData:I,transform:T}of t)if(I.indices){for(let y=0;y[m.vertexData.positions,m.transform])),s&&(yield),h.normals&&(this.normals=j._MergeElement(E.NormalKind,h.normals,e,t.map(m=>[m.vertexData.normals,m.transform])),s&&(yield)),h.tangents&&(this.tangents=j._MergeElement(E.TangentKind,h.tangents,e,t.map(m=>[m.vertexData.tangents,m.transform])),s&&(yield)),h.uvs&&(this.uvs=j._MergeElement(E.UVKind,h.uvs,e,t.map(m=>[m.vertexData.uvs,m.transform])),s&&(yield)),h.uvs2&&(this.uvs2=j._MergeElement(E.UV2Kind,h.uvs2,e,t.map(m=>[m.vertexData.uvs2,m.transform])),s&&(yield)),h.uvs3&&(this.uvs3=j._MergeElement(E.UV3Kind,h.uvs3,e,t.map(m=>[m.vertexData.uvs3,m.transform])),s&&(yield)),h.uvs4&&(this.uvs4=j._MergeElement(E.UV4Kind,h.uvs4,e,t.map(m=>[m.vertexData.uvs4,m.transform])),s&&(yield)),h.uvs5&&(this.uvs5=j._MergeElement(E.UV5Kind,h.uvs5,e,t.map(m=>[m.vertexData.uvs5,m.transform])),s&&(yield)),h.uvs6&&(this.uvs6=j._MergeElement(E.UV6Kind,h.uvs6,e,t.map(m=>[m.vertexData.uvs6,m.transform])),s&&(yield)),h.colors&&(this.colors=j._MergeElement(E.ColorKind,h.colors,e,t.map(m=>[m.vertexData.colors,m.transform])),(h.hasVertexAlpha!==void 0||t.some(m=>m.vertexData.hasVertexAlpha!==void 0))&&(this.hasVertexAlpha=h.hasVertexAlpha||t.some(m=>m.vertexData.hasVertexAlpha)),s&&(yield)),h.matricesIndices&&(this.matricesIndices=j._MergeElement(E.MatricesIndicesKind,h.matricesIndices,e,t.map(m=>[m.vertexData.matricesIndices,m.transform])),s&&(yield)),h.matricesWeights&&(this.matricesWeights=j._MergeElement(E.MatricesWeightsKind,h.matricesWeights,e,t.map(m=>[m.vertexData.matricesWeights,m.transform])),s&&(yield)),h.matricesIndicesExtra&&(this.matricesIndicesExtra=j._MergeElement(E.MatricesIndicesExtraKind,h.matricesIndicesExtra,e,t.map(m=>[m.vertexData.matricesIndicesExtra,m.transform])),s&&(yield)),h.matricesWeightsExtra&&(this.matricesWeightsExtra=j._MergeElement(E.MatricesWeightsExtraKind,h.matricesWeightsExtra,e,t.map(m=>[m.vertexData.matricesWeightsExtra,m.transform]))),this}static _MergeElement(e,t,i,s){const n=s.filter(l=>l[0]!==null&&l[0]!==void 0);if(!t&&n.length==0)return t;if(!t)return this._MergeElement(e,n[0][0],n[0][1],n.slice(1));const r=n.reduce((l,h)=>l+h[0].length,t.length),o=e===E.PositionKind?j._TransformVector3Coordinates:e===E.NormalKind?j._TransformVector3Normals:e===E.TangentKind?j._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const l=new Float32Array(r);l.set(t),i&&o(l,i,0,t.length);let h=t.length;for(const[c,u]of n)l.set(c,h),u&&o(l,u,h,c.length),h+=c.length;return l}else{const l=new Array(r);for(let c=0;c{const r=E.DeduceStride(s);if(n.length%r!==0)throw new Error("The "+s+"s array count must be a multiple of "+r);return n.length/r},t=e(E.PositionKind,this.positions),i=(s,n)=>{const r=e(s,n);if(r!==t)throw new Error("The "+s+"s element count ("+r+") does not match the positions count ("+t+")")};this.normals&&i(E.NormalKind,this.normals),this.tangents&&i(E.TangentKind,this.tangents),this.uvs&&i(E.UVKind,this.uvs),this.uvs2&&i(E.UV2Kind,this.uvs2),this.uvs3&&i(E.UV3Kind,this.uvs3),this.uvs4&&i(E.UV4Kind,this.uvs4),this.uvs5&&i(E.UV5Kind,this.uvs5),this.uvs6&&i(E.UV6Kind,this.uvs6),this.colors&&i(E.ColorKind,this.colors),this.matricesIndices&&i(E.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(E.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(E.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(E.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return j.Parse(e)}serialize(){const e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return j._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return j._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new j;if(e.isVerticesDataPresent(E.PositionKind)&&(s.positions=e.getVerticesData(E.PositionKind,t,i)),e.isVerticesDataPresent(E.NormalKind)&&(s.normals=e.getVerticesData(E.NormalKind,t,i)),e.isVerticesDataPresent(E.TangentKind)&&(s.tangents=e.getVerticesData(E.TangentKind,t,i)),e.isVerticesDataPresent(E.UVKind)&&(s.uvs=e.getVerticesData(E.UVKind,t,i)),e.isVerticesDataPresent(E.UV2Kind)&&(s.uvs2=e.getVerticesData(E.UV2Kind,t,i)),e.isVerticesDataPresent(E.UV3Kind)&&(s.uvs3=e.getVerticesData(E.UV3Kind,t,i)),e.isVerticesDataPresent(E.UV4Kind)&&(s.uvs4=e.getVerticesData(E.UV4Kind,t,i)),e.isVerticesDataPresent(E.UV5Kind)&&(s.uvs5=e.getVerticesData(E.UV5Kind,t,i)),e.isVerticesDataPresent(E.UV6Kind)&&(s.uvs6=e.getVerticesData(E.UV6Kind,t,i)),e.isVerticesDataPresent(E.ColorKind)){const n=e.geometry||e,r=n.getVertexBuffer(E.ColorKind),o=n.getVerticesData(E.ColorKind,t,i);if(r.getSize()===3){const l=new Float32Array(o.length*4/3);for(let h=0,c=0;h!Array.isArray(a))],j,"_TransformVector3Coordinates",null);D([ss.filter((...[a])=>!Array.isArray(a))],j,"_TransformVector3Normals",null);D([ss.filter((...[a])=>!Array.isArray(a))],j,"_TransformVector4Normals",null);D([ss.filter((...[a])=>!Array.isArray(a))],j,"_FlipFaces",null);class Tt{static get ForceFullSceneLoadingForIncremental(){return Tt._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Tt._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Tt._ShowLoadingScreen}static set ShowLoadingScreen(e){Tt._ShowLoadingScreen=e}static get loggingLevel(){return Tt._LoggingLevel}static set loggingLevel(e){Tt._LoggingLevel=e}static get CleanBoneMatrixWeights(){return Tt._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Tt._CleanBoneMatrixWeights=e}}Tt._ForceFullSceneLoadingForIncremental=!1;Tt._ShowLoadingScreen=!0;Tt._CleanBoneMatrixWeights=!1;Tt._LoggingLevel=0;function Y_(a,e,t,i,s,n,r,o){const l=e*E.GetTypeByteLength(t),h=r*e;if(o.length!==h)throw new Error("Output length is not valid");if(t!==E.FLOAT||s!==l){E.ForEach(a,i,s,e,t,h,n,(c,u)=>o[u]=c);return}if(a instanceof Array){const c=i/4;o.set(a,c)}else if(a instanceof ArrayBuffer){const c=new Float32Array(a,i,h);o.set(c)}else{let c=a.byteOffset+i;const u=c%4;u&&(c=Math.max(0,c-u));const f=new Float32Array(a.buffer,c,h);o.set(f)}}class kt{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 kt(kt.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,n=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||Ce.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=s,i?this.setAllVerticesData(i,s):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),n&&(this.applyToMesh(n),n.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return this.delayLoadState===1||this.delayLoadState===0}get doNotSerialize(){for(let e=0;e{t._rebuild()})}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,s){i&&Array.isArray(t)&&(t=new Float32Array(t));const n=new E(this._engine,t,e,{updatable:i,postponeInternalCreation:this._meshes.length===0,stride:s,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(n)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const s=e.getKind();this._vertexBuffers[s]&&i&&this._vertexBuffers[s].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[s]=e;const n=this._meshes,r=n.length;if(s===E.PositionKind){this._totalVertices=t!=null?t:e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const o=this._extend&&this._extend.minimum||new v(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),l=this._extend&&this._extend.maximum||new v(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let h=0;h65535);for(const s of this._meshes)s._createGlobalSubMesh(!0),s.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,this._meshes.length!==0&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),t!=null&&(this._totalVertices=t);for(const s of this._meshes)s._createGlobalSubMesh(!0),s.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?this._totalIndices!==void 0?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return!t&&(!e||this._meshes.length===1)?i:i.slice()}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){!e||!this._vertexArrayObjects||this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const i=this._meshes,s=i.indexOf(e);s!==-1&&(i.splice(s,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,i.length===0&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&(e=this.getVerticesData(E.PositionKind),!e))return;this._extend=Yh(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)t===1&&this._vertexBuffers[i].create(),i===E.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());t===1&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const t of this._meshes)t._markSubMeshesAsAttributesDirty()}load(e,t){if(this.delayLoadState!==2){if(this.isReady()){t&&t();return}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 s=this._meshes,n=s.length;for(let r=0;r0){for(let s=0;s0){for(let s=0;s0){for(let s=0;s-1&&this._parentContainer.geometries.splice(s,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new j;t.indices=[];const i=this.getIndices();if(i)for(let l=0;l0){const o=new Float32Array(e,r.positionsAttrDesc.offset,r.positionsAttrDesc.count);t.setVerticesData(E.PositionKind,o,!1)}if(r.normalsAttrDesc&&r.normalsAttrDesc.count>0){const o=new Float32Array(e,r.normalsAttrDesc.offset,r.normalsAttrDesc.count);t.setVerticesData(E.NormalKind,o,!1)}if(r.tangetsAttrDesc&&r.tangetsAttrDesc.count>0){const o=new Float32Array(e,r.tangetsAttrDesc.offset,r.tangetsAttrDesc.count);t.setVerticesData(E.TangentKind,o,!1)}if(r.uvsAttrDesc&&r.uvsAttrDesc.count>0){const o=new Float32Array(e,r.uvsAttrDesc.offset,r.uvsAttrDesc.count);if(Le.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,r.uvs2AttrDesc.offset,r.uvs2AttrDesc.count);if(Le.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,r.uvs3AttrDesc.offset,r.uvs3AttrDesc.count);if(Le.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,r.uvs4AttrDesc.offset,r.uvs4AttrDesc.count);if(Le.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,r.uvs5AttrDesc.offset,r.uvs5AttrDesc.count);if(Le.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,r.uvs6AttrDesc.offset,r.uvs6AttrDesc.count);if(Le.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,r.colorsAttrDesc.offset,r.colorsAttrDesc.count);t.setVerticesData(E.ColorKind,o,!1,r.colorsAttrDesc.stride)}if(r.matricesIndicesAttrDesc&&r.matricesIndicesAttrDesc.count>0){const o=new Int32Array(e,r.matricesIndicesAttrDesc.offset,r.matricesIndicesAttrDesc.count),l=[];for(let h=0;h>8),l.push((c&16711680)>>16),l.push(c>>24&255)}t.setVerticesData(E.MatricesIndicesKind,l,!1)}if(r.matricesIndicesExtraAttrDesc&&r.matricesIndicesExtraAttrDesc.count>0){const o=new Int32Array(e,r.matricesIndicesExtraAttrDesc.offset,r.matricesIndicesExtraAttrDesc.count),l=[];for(let h=0;h>8),l.push((c&16711680)>>16),l.push(c>>24&255)}t.setVerticesData(E.MatricesIndicesExtraKind,l,!1)}if(r.matricesWeightsAttrDesc&&r.matricesWeightsAttrDesc.count>0){const o=new Float32Array(e,r.matricesWeightsAttrDesc.offset,r.matricesWeightsAttrDesc.count);t.setVerticesData(E.MatricesWeightsKind,o,!1)}if(r.indicesAttrDesc&&r.indicesAttrDesc.count>0){const o=new Int32Array(e,r.indicesAttrDesc.offset,r.indicesAttrDesc.count);t.setIndices(o,null)}if(r.subMeshesAttrDesc&&r.subMeshesAttrDesc.count>0){const o=new Int32Array(e,r.subMeshesAttrDesc.offset,r.subMeshesAttrDesc.count*5);t.subMeshes=[];for(let l=0;l>8),r.push((l&16711680)>>16),r.push(l>>24&255)}t.setVerticesData(E.MatricesIndicesKind,r,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(E.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const r=[];for(let o=0;o>8),r.push((l&16711680)>>16),r.push(l>>24&255)}t.setVerticesData(E.MatricesIndicesExtraKind,r,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(kt._CleanMatricesWeights(e,t),t.setVerticesData(E.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(E.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let r=0;r-1){const u=t.getScene().getLastSkeletonById(e.skeletonId);if(!u)return;s=u.bones.length}else return;const n=t.getVerticesData(E.MatricesIndicesKind),r=t.getVerticesData(E.MatricesIndicesExtraKind),o=e.matricesWeights,l=e.matricesWeightsExtra,h=e.numBoneInfluencer,c=o.length;for(let u=0;uh-1)&&(d=h-1),f>.001){const p=1/f;for(let g=0;g<4;g++)o[u+g]*=p;if(l)for(let g=0;g<4;g++)l[u+g]*=p}else d>=4?(l[u+d-4]=1-f,r[u+d-4]=s):(o[u+d]=1-f,n[u+d]=s)}t.setVerticesData(E.MatricesIndicesKind,n),e.matricesWeightsExtra&&t.setVerticesData(E.MatricesIndicesExtraKind,r)}static Parse(e,t,i){const s=new kt(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,ze&&ze.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new si(v.FromArray(e.boundingBoxMinimum),v.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(E.UVKind),e.hasUVs2&&s._delayInfo.push(E.UV2Kind),e.hasUVs3&&s._delayInfo.push(E.UV3Kind),e.hasUVs4&&s._delayInfo.push(E.UV4Kind),e.hasUVs5&&s._delayInfo.push(E.UV5Kind),e.hasUVs6&&s._delayInfo.push(E.UV6Kind),e.hasColors&&s._delayInfo.push(E.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(E.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(E.MatricesWeightsKind),s._delayLoadingFunction=j.ImportVertexData):j.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class q_{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new v(0,0,0),this._diffPositionForCollisions=new v(0,0,0),this._collisionResponse=!0}}function $_(a,e,t){let i=null;switch(e){case E.PositionKind:i=s=>s.getPositions();break;case E.NormalKind:i=s=>s.getNormals();break;case E.TangentKind:i=s=>s.getTangents();break;case E.UVKind:i=s=>s.getUVs();break;default:return}for(let s=0;s0&&(O.FromFloat32ArrayToRefScaled(t,Math.floor(i[f+d]*16),p,h),l.addToSelf(h));if(n&&r)for(d=0;d<4;d++)p=r[f+d],p>0&&(O.FromFloat32ArrayToRefScaled(t,Math.floor(n[f+d]*16),p,h),l.addToSelf(h));c(a[u],a[u+1],a[u+2],l,o),o.toArray(a,u)}}class Z_{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=v.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class Q_{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Z_,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 q_,this._enableDistantPicking=!1,this._rawBoundingInfo=null,this._sideOrientationHint=!1}}class et extends Ie{static get BILLBOARDMODE_NONE(){return Ie.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Ie.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Ie.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Ie.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Ie.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Ie.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):!1}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(t===1&&e!==1||t!==1&&e===1)&&this._markSubMeshesAsDirty(i=>{i.markAsMiscDirty(),i.markAsPrePassDirty()})}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._setMaterial(e)}_setMaterial(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){var t;return(t=this._internalAbstractMeshDataInfo._materialForRenderPass)==null?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}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new Q_,this._waitingMaterialId=null,this.cullingStrategy=et.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new Q,this.onCollisionPositionChangeObservable=new Q,this.onMaterialChangedObservable=new Q,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=pe.Red(),this.outlineWidth=.02,this.overlayColor=pe.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 v(.5,1,.5),this.ellipsoidOffset=new v(0,0,0),this.edgesWidth=1,this.edgesColor=new X(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 Q,this._onCollisionPositionChange=(i,s,n=null)=>{s.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>ie.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),n&&this.onCollideObservable.notifyObservers(n),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},t=this.getScene(),t.addMesh(this),this._resyncLightSources(),this._uniformBuffer=new de(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case 2:this.doNotSyncBoundingInfo=!0;case 1:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1;break}}_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: "+(this.getClassName()!=="InstancedMesh"?"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!==Ie.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive))if(e){if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}else return this.actionManager;return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery!==null&&(this._occlusionQuery=null),!!this.subMeshes){for(const t of this.subMeshes)t._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let s=!1;if(i===-1){if(!t)return;this._lightSources.push(e)}else{if(t)return;s=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(s)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);i!==-1&&(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,s){return this}updateVerticesData(e,t,i,s){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){var e;return(e=this.rawBoundingInfo)!=null?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return this._boundingInfo!==null}buildBoundingInfo(e,t,i){return this._boundingInfo=new si(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(E.MatricesIndicesKind)&&this.isVerticesDataPresent(E.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===Ie.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const s=new O;(this.rotationQuaternion?this.rotationQuaternion:le.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const r=v.Zero(),o=this.definedFacingForward?-1:1;return v.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,s,r),r}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const s=this.definedFacingForward?1:-1;return new v(e*s,t,i*s)}_refreshBoundingInfo(e,t){if(e){const i=Yh(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new si(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i{if(s){const o=s._vertexData||(s._vertexData={});return o[r]||this.copyVerticesData(r,o),o[r]}return this.getVerticesData(r)};if(t||(t=n(i)),!t)return null;if(s?(s._outputData?s._outputData.set(t):s._outputData=new Float32Array(t),t=s._outputData):(e.applyMorph&&this.morphTargetManager||e.applySkeleton&&this.skeleton)&&(t=t.slice()),e.applyMorph&&this.morphTargetManager&&$_(t,i,this.morphTargetManager),e.applySkeleton&&this.skeleton){const r=n(E.MatricesIndicesKind),o=n(E.MatricesWeightsKind);if(o&&r){const l=this.numBoneInfluencers>4,h=l?n(E.MatricesIndicesExtraKind):null,c=l?n(E.MatricesWeightsExtraKind):null,u=this.skeleton.getTransformMatrices(this);et._ApplySkeleton(t,i,u,r,o,h,c)}}if(e.updatePositionsArray!==!1&&i===E.PositionKind){const r=this._internalAbstractMeshDataInfo._positions||[],o=r.length;if(r.length=t.length/3,o1||!s.IsGlobal)&&s.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const s=this.getBoundingInfo(),n=e.getBoundingInfo();if(s.intersects(n,t))return!0;if(i){for(const r of this.getChildMeshes())if(r.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 i=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=i.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,i.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){var s;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const n=e.verticesStart,r=e.verticesStart+e.verticesCount;for(let o=n;o1&&!r._checkCollision(e)||this._collideForSubMesh(r,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=N.Matrix[0],i=N.Matrix[1];return O.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,s=!1,n,r=!1){const o=new ns,l=this.getClassName(),h=l==="InstancedLinesMesh"||l==="LinesMesh"||l==="GreasedLineMesh"?this.intersectionThreshold:0,c=this.getBoundingInfo();if(!this.subMeshes||!r&&(!e.intersectsSphere(c.boundingSphere,h)||!e.intersectsBox(c.boundingBox,h)))return o;if(s)return o.hit=!r,o.pickedMesh=r?null:this,o.distance=r?0:v.Distance(e.origin,c.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let u=null;const f=this._scene.getIntersectingSubMeshCandidates(this,e),d=f.length;let p=!1;for(let g=0;g1&&!r&&!_.canIntersects(e))continue;const m=_.intersects(e,this._positions,this.getIndices(),t,i);if(m&&(t||!u||m.distanceo!==this&&o.actionManager===this.actionManager)&&this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let l=o.includedOnlyMeshes.indexOf(this);l!==-1&&o.includedOnlyMeshes.splice(l,1),l=o.excludedMeshes.indexOf(this),l!==-1&&o.excludedMeshes.splice(l,1);const h=o.getShadowGenerators();if(h){const c=h.values();for(let u=c.next();u.done!==!0;u=c.next()){const d=u.value.getShadowMap();d&&d.renderList&&(l=d.renderList.indexOf(this),l!==-1&&d.renderList.splice(l,1))}}}),(this.getClassName()!=="InstancedMesh"||this.getClassName()!=="InstancedLinesMesh")&&this.releaseSubMeshes();const r=s.getEngine();if(this._occlusionQuery!==null&&(this.isOcclusionQueryInProgress=!1,r.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),r.wipeCaches(),s.removeMesh(this),this._parentContainer){const o=this._parentContainer.meshes.indexOf(this);o>-1&&this._parentContainer.meshes.splice(o,1),this._parentContainer=null}if(t&&this.material&&(this.material.getClassName()==="MultiMaterial"?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){o=!0;break}o?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(o,l){return l.sqDistance-o.sqDistance},!e.facetDepthSortFrom){const o=this.getScene().activeCamera;e.facetDepthSortFrom=o?o.position:v.Zero()}e.depthSortedFacets=[];for(let o=0;oNe?n.maximum.x-n.minimum.x:Ne,e.bbSize.y=n.maximum.y-n.minimum.y>Ne?n.maximum.y-n.minimum.y:Ne,e.bbSize.z=n.maximum.z-n.minimum.z>Ne?n.maximum.z-n.minimum.z:Ne;let r=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(r=r>e.bbSize.z?r:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/r),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/r),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/r),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=n,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),v.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&j.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const o=e.depthSortedIndices.length/3|0;for(let l=0;ln.subDiv.max||o<0||o>n.subDiv.max||l<0||l>n.subDiv.max?null:n.facetPartitioning[r+n.subDiv.max*o+n.subDiv.max*n.subDiv.max*l]}getClosestFacetAtCoordinates(e,t,i,s,n=!1,r=!0){const o=this.getWorldMatrix(),l=N.Matrix[5];o.invertToRef(l);const h=N.Vector3[8];v.TransformCoordinatesFromFloatsToRef(e,t,i,l,h);const c=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,s,n,r);return s&&v.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,o,s),c}getClosestFacetAtLocalCoordinates(e,t,i,s,n=!1,r=!0){let o=null,l=0,h=0,c=0,u=0,f=0,d=0,p=0,g=0;const _=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),x=this.getFacetsAtLocalCoordinates(e,t,i);if(!x)return null;let I=Number.MAX_VALUE,T=I,y,b,S;for(let A=0;A=0||n&&!r&&u<=0)&&(u=b.x*S.x+b.y*S.y+b.z*S.z,f=-(b.x*e+b.y*t+b.z*i-u)/(b.x*b.x+b.y*b.y+b.z*b.z),d=e+b.x*f,p=t+b.y*f,g=i+b.z*f,l=d-e,h=p-t,c=g-i,T=l*l+h*h+c*c,Te.emitter===this)}}et.OCCLUSION_TYPE_NONE=0;et.OCCLUSION_TYPE_OPTIMISTIC=1;et.OCCLUSION_TYPE_STRICT=2;et.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;et.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;et.CULLINGSTRATEGY_STANDARD=0;et.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;et.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;et.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;D([ss.filter((...[a,e,t,i,s])=>!Array.isArray(a)&&!Array.isArray(e)&&!Array.isArray(t)&&!Array.isArray(i)&&!Array.isArray(s))],et,"_ApplySkeleton",null);ft("BABYLON.AbstractMesh",et);class hs{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){Ae.Clone(()=>e,this)}serialize(){return Ae.Serialize(this)}parse(e,t,i){Ae.Parse(()=>this,e,t,i)}}D([B()],hs.prototype,"func",null);D([B()],hs.prototype,"funcRef",null);D([B()],hs.prototype,"funcMask",null);D([B()],hs.prototype,"opStencilFail",null);D([B()],hs.prototype,"opDepthFail",null);D([B()],hs.prototype,"opStencilDepthPass",null);D([B()],hs.prototype,"mask",null);D([B()],hs.prototype,"enabled",null);function uo(a){a.indexOf("vClipPlane")===-1&&a.push("vClipPlane"),a.indexOf("vClipPlane2")===-1&&a.push("vClipPlane2"),a.indexOf("vClipPlane3")===-1&&a.push("vClipPlane3"),a.indexOf("vClipPlane4")===-1&&a.push("vClipPlane4"),a.indexOf("vClipPlane5")===-1&&a.push("vClipPlane5"),a.indexOf("vClipPlane6")===-1&&a.push("vClipPlane6")}function qh(a,e,t){var h,c,u,f,d,p;const i=!!((h=a.clipPlane)!=null?h:e.clipPlane),s=!!((c=a.clipPlane2)!=null?c:e.clipPlane2),n=!!((u=a.clipPlane3)!=null?u:e.clipPlane3),r=!!((f=a.clipPlane4)!=null?f:e.clipPlane4),o=!!((d=a.clipPlane5)!=null?d:e.clipPlane5),l=!!((p=a.clipPlane6)!=null?p:e.clipPlane6);i&&t.push("#define CLIPPLANE"),s&&t.push("#define CLIPPLANE2"),n&&t.push("#define CLIPPLANE3"),r&&t.push("#define CLIPPLANE4"),o&&t.push("#define CLIPPLANE5"),l&&t.push("#define CLIPPLANE6")}function J_(a,e,t){var c,u,f,d,p,g;let i=!1;const s=!!((c=a.clipPlane)!=null?c:e.clipPlane),n=!!((u=a.clipPlane2)!=null?u:e.clipPlane2),r=!!((f=a.clipPlane3)!=null?f:e.clipPlane3),o=!!((d=a.clipPlane4)!=null?d:e.clipPlane4),l=!!((p=a.clipPlane5)!=null?p:e.clipPlane5),h=!!((g=a.clipPlane6)!=null?g:e.clipPlane6);return t.CLIPPLANE!==s&&(t.CLIPPLANE=s,i=!0),t.CLIPPLANE2!==n&&(t.CLIPPLANE2=n,i=!0),t.CLIPPLANE3!==r&&(t.CLIPPLANE3=r,i=!0),t.CLIPPLANE4!==o&&(t.CLIPPLANE4=o,i=!0),t.CLIPPLANE5!==l&&(t.CLIPPLANE5=l,i=!0),t.CLIPPLANE6!==h&&(t.CLIPPLANE6=h,i=!0),i}function fo(a,e,t){var s,n,r,o,l,h;let i=(s=e.clipPlane)!=null?s:t.clipPlane;Vs(a,"vClipPlane",i),i=(n=e.clipPlane2)!=null?n:t.clipPlane2,Vs(a,"vClipPlane2",i),i=(r=e.clipPlane3)!=null?r:t.clipPlane3,Vs(a,"vClipPlane3",i),i=(o=e.clipPlane4)!=null?o:t.clipPlane4,Vs(a,"vClipPlane4",i),i=(l=e.clipPlane5)!=null?l:t.clipPlane5,Vs(a,"vClipPlane5",i),i=(h=e.clipPlane6)!=null?h:t.clipPlane6,Vs(a,"vClipPlane6",i)}function Vs(a,e,t){t&&a.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d)}const dl=pe.Black(),pl={NUM_MORPH_INFLUENCERS:0};function po(a,e,t){if(!a||a.LOGARITHMICDEPTH||a.indexOf&&a.indexOf("LOGARITHMICDEPTH")>=0){const i=t.activeCamera;i.mode===1&&U.Error("Logarithmic depth is not compatible with orthographic cameras!",20),e.setFloat("logarithmicDepthConstant",2/(Math.log(i.maxZ+1)/Math.LN2))}}function _o(a,e,t,i=!1){t&&a.fogEnabled&&(!e||e.applyFog)&&a.fogMode!==0&&(t.setFloat4("vFogInfos",a.fogMode,a.fogStart,a.fogEnd,a.fogDensity),i?(a.fogColor.toLinearSpaceToRef(dl,a.getEngine().useExactSrgbConversions),t.setColor3("vFogColor",dl)):t.setColor3("vFogColor",a.fogColor))}function eg(a,e,t){pl.NUM_MORPH_INFLUENCERS=t,$h(a,e,pl)}function $h(a,e,t){const i=t.NUM_MORPH_INFLUENCERS;if(i>0&&Ce.LastCreatedEngine){const s=Ce.LastCreatedEngine.getCaps().maxVertexAttribs,n=e.morphTargetManager;if(n!=null&&n.isUsingTextureForTargets)return;const r=n&&n.supportsNormals&&t.NORMAL,o=n&&n.supportsTangents&&t.TANGENT,l=n&&n.supportsUVs&&t.UV1;for(let h=0;hs&&U.Error("Cannot add more vertex attributes for mesh "+e.name)}}function go(a,e=!1){a.push("world0"),a.push("world1"),a.push("world2"),a.push("world3"),e&&(a.push("previousWorld0"),a.push("previousWorld1"),a.push("previousWorld2"),a.push("previousWorld3"))}function mo(a,e){const t=a.morphTargetManager;!a||!t||e.setFloatArray("morphTargetInfluences",t.influences)}function jh(a,e){e.bindToEffect(a,"Scene")}function ds(a,e,t){e._needUVs=!0,e[t]=!0,a.optimizeUVAllocation&&a.getTextureMatrix().isIdentityAs3x2()?(e[t+"DIRECTUV"]=a.coordinatesIndex+1,e["MAINUV"+(a.coordinatesIndex+1)]=!0):e[t+"DIRECTUV"]=0}function ps(a,e,t){const i=a.getTextureMatrix();e.updateMatrix(t+"Matrix",i)}function Zh(a,e,t){t.BAKED_VERTEX_ANIMATION_TEXTURE&&t.INSTANCES&&a.push("bakedVertexAnimationSettingsInstanced")}function tg(a,e){return e.set(a),e}function Qh(a,e,t){if(!(!e||!a)&&(a.computeBonesUsingShaders&&e._bonesComputationForcedToCPU&&(a.computeBonesUsingShaders=!1),a.useBones&&a.computeBonesUsingShaders&&a.skeleton)){const i=a.skeleton;if(i.isUsingTextureForMatrices&&e.getUniformIndex("boneTextureWidth")>-1){const s=i.getTransformMatrixTexture(a);e.setTexture("boneSampler",s),e.setFloat("boneTextureWidth",4*(i.bones.length+1))}else{const s=i.getTransformMatrices(a);s&&(e.setMatrices("mBones",s),t&&a.getScene().prePassRenderer&&a.getScene().prePassRenderer.getIndex(2)&&(t.previousBones[a.uniqueId]||(t.previousBones[a.uniqueId]=s.slice()),e.setMatrices("mPreviousBones",t.previousBones[a.uniqueId]),tg(s,t.previousBones[a.uniqueId])))}}}function ig(a,e,t,i,s,n=!0){a._bindLight(e,t,i,s,n)}function sg(a,e,t,i,s=4){const n=Math.min(e.lightSources.length,s);for(let r=0;r0&&(i.addCPUSkinningFallback(0,e),a.push("matricesIndices"),a.push("matricesWeights"),t.NUM_BONE_INFLUENCERS>4&&(a.push("matricesIndicesExtra"),a.push("matricesWeightsExtra")))}function Jh(a,e){(e.INSTANCES||e.THIN_INSTANCES)&&go(a,!!e.PREPASS_VELOCITY),e.INSTANCESCOLOR&&a.push("instanceColor")}function rg(a,e,t=4,i=0){let s=0;for(let n=0;n0&&(s=i+n,e.addFallback(s,"LIGHT"+n)),a.SHADOWS||(a["SHADOW"+n]&&e.addFallback(i,"SHADOW"+n),a["SHADOWPCF"+n]&&e.addFallback(i,"SHADOWPCF"+n),a["SHADOWPCSS"+n]&&e.addFallback(i,"SHADOWPCSS"+n),a["SHADOWPOISSON"+n]&&e.addFallback(i,"SHADOWPOISSON"+n),a["SHADOWESM"+n]&&e.addFallback(i,"SHADOWESM"+n),a["SHADOWCLOSEESM"+n]&&e.addFallback(i,"SHADOWCLOSEESM"+n));return s++}function ag(a,e){return e.fogEnabled&&a.applyFog&&e.fogMode!==0}function ec(a,e,t,i,s,n,r,o=!1){r._areMiscDirty&&(r.LOGARITHMICDEPTH=t,r.POINTSIZE=i,r.FOG=s&&ag(a,e),r.NONUNIFORMSCALING=a.nonUniformScaling,r.ALPHATEST=n,r.DECAL_AFTER_DETAIL=o)}function og(a,e,t,i,s=4,n=!1){if(!t._areLightsDirty)return t._needNormals;let r=0;const o={needNormals:t._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(a.lightsEnabled&&!n){for(const h of e.lightSources)if(lg(a,e,h,r,t,i,o),r++,r===s)break}t.SPECULARTERM=o.specularEnabled,t.SHADOWS=o.shadowEnabled;for(let h=r;h0&&(r.shadowEnabled=!0,l.prepareDefines(s,i))}}t.lightmapMode!=Xe.LIGHTMAP_DEFAULT?(r.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+i]=!0,s["LIGHTMAPNOSPECULAR"+i]=t.lightmapMode==Xe.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+i]=!1,s["LIGHTMAPNOSPECULAR"+i]=!1)}function tc(a,e,t,i,s,n=null,r=!1){let o=_g(a,i);n!==!1&&(o=J_(t,a,i)),i.DEPTHPREPASS!==!e.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==s&&(i.INSTANCES=s,o=!0),i.THIN_INSTANCES!==r&&(i.THIN_INSTANCES=r,o=!0),o&&i.markAsUnprocessed()}function hg(a,e){if(a.useBones&&a.computeBonesUsingShaders&&a.skeleton){e.NUM_BONE_INFLUENCERS=a.numBoneInfluencers;const t=e.BONETEXTURE!==void 0;if(a.skeleton.isUsingTextureForMatrices&&t)e.BONETEXTURE=!0;else{e.BonesPerMesh=a.skeleton.bones.length+1,e.BONETEXTURE=t?!1:void 0;const i=a.getScene().prePassRenderer;if(i&&i.enabled){const s=i.excludedSkinnedMesh.indexOf(a)===-1;e.BONES_VELOCITY_ENABLED=s}}}else e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE!==void 0&&(e.BONETEXTURE=!1)}function cg(a,e){const t=a.morphTargetManager;t?(e.MORPHTARGETS_UV=t.supportsUVs&&e.UV1,e.MORPHTARGETS_TANGENT=t.supportsTangents&&e.TANGENT,e.MORPHTARGETS_NORMAL=t.supportsNormals&&e.NORMAL,e.NUM_MORPH_INFLUENCERS=t.numMaxInfluencers||t.numInfluencers,e.MORPHTARGETS=e.NUM_MORPH_INFLUENCERS>0,e.MORPHTARGETS_TEXTURE=t.isUsingTextureForTargets):(e.MORPHTARGETS_UV=!1,e.MORPHTARGETS_TANGENT=!1,e.MORPHTARGETS_NORMAL=!1,e.MORPHTARGETS=!1,e.NUM_MORPH_INFLUENCERS=0)}function ug(a,e){const t=a.bakedVertexAnimationManager;e.BAKED_VERTEX_ANIMATION_TEXTURE=!!(t&&t.isEnabled)}function ic(a,e,t,i,s=!1,n=!0,r=!0){if(!e._areAttributesDirty&&e._needNormals===e._normals&&e._needUVs===e._uvs)return!1;e._normals=e._needNormals,e._uvs=e._needUVs,e.NORMAL=e._needNormals&&a.isVerticesDataPresent("normal"),e._needNormals&&a.isVerticesDataPresent("tangent")&&(e.TANGENT=!0);for(let o=1;o<=6;++o)e["UV"+o]=e._needUVs?a.isVerticesDataPresent("uv".concat(o===1?"":o)):!1;if(t){const o=a.useVertexColors&&a.isVerticesDataPresent("color");e.VERTEXCOLOR=o,e.VERTEXALPHA=a.hasVertexAlpha&&o&&n}return a.isVerticesDataPresent("instanceColor")&&(a.hasInstances||a.hasThinInstances)&&(e.INSTANCESCOLOR=!0),i&&hg(a,e),s&&cg(a,e),r&&ug(a,e),!0}function fg(a,e){if(a.activeCamera){const t=e.MULTIVIEW;e.MULTIVIEW=a.activeCamera.outputRenderTarget!==null&&a.activeCamera.outputRenderTarget.getViewCount()>1,e.MULTIVIEW!=t&&e.markAsUnprocessed()}}function dg(a,e,t){const i=e.ORDER_INDEPENDENT_TRANSPARENCY,s=e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;e.ORDER_INDEPENDENT_TRANSPARENCY=a.useOrderIndependentTransparency&&t,e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!a.getEngine().getCaps().textureFloatLinearFiltering,(i!==e.ORDER_INDEPENDENT_TRANSPARENCY||s!==e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&e.markAsUnprocessed()}function pg(a,e,t){const i=e.PREPASS;if(!e._arePrePassDirty)return;const s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(a.prePassRenderer&&a.prePassRenderer.enabled&&t){e.PREPASS=!0,e.SCENE_MRT_COUNT=a.prePassRenderer.mrtCount,e.PREPASS_NORMAL_WORLDSPACE=a.prePassRenderer.generateNormalsInWorldSpace;for(let n=0;n{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const s=t||Ce.LastCreatedScene;s&&(this._scene=s,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||ee.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new ln(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._uniformBuffer=new de(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),q.OnEventObservable.notifyObservers(this,1))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const s=t.materialDefines;return s?(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh):!1}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}_getEffectiveOrientation(e){return this.sideOrientation!==null?this.sideOrientation:e.sideOrientation}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===q.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===q.MATERIAL_OPAQUE||this._transparencyMode===q.MATERIAL_ALPHATEST}needAlphaBlending(){return this._disableAlphaBlending?!1:this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1?!0:this._disableAlphaBlending?!1: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 s of i.subMeshes)if(s.getMaterial()===this)for(const n of s._drawWrappers)n&&this._materialContext===n.materialContext&&(n._wasPreviouslyReady=!1,n._wasPreviouslyUsingInstances=null,n._forceRebindOnNextCall=e)}e&&this.markAsDirty(q.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),n=(t==null?this.sideOrientation:t)===q.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(8,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),s._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,jh(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const s=this._scene.getEngine();this._cachedDepthWriteState=s.getDepthWrite(),s.setDepthWrite(!1)}if(this.disableColorWrite){const s=this._scene.getEngine();this._cachedColorWriteState=s.getColorWrite(),s.setColorWrite(!1)}if(this.depthFunction!==0){const s=this._scene.getEngine();this._cachedDepthFunctionState=s.getDepthFunction()||0,s.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),this.depthFunction!==0&&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(256,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(512,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(1024,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),q._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const s of this.pluginManager._plugins){const n=e.pluginManager.getPlugin(s.name);n&&s.copyTo(n)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}else return this._scene.meshes.filter(t=>t.material===this)}forceCompilation(e,t,i,s){const n={clipPlane:!1,useInstances:!1,...i},r=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const l=()=>{if(!this._scene||!this._scene.getEngine())return;const h=r.clipPlane;if(n.clipPlane&&(r.clipPlane=new Yt(0,0,0,1)),this._storeEffectOnSubMeshes){let c=!0,u=null;if(e.subMeshes){const f=new vi(0,0,0,0,0,e,void 0,!1,!1);f.materialDefines&&(f.materialDefines._renderId=-1),this.isReadyForSubMesh(e,f,n.useInstances)||(f.effect&&f.effect.getCompilationError()&&f.effect.allFallbacksProcessed()?u=f.effect.getCompilationError():(c=!1,setTimeout(l,16)))}c&&(this.allowShaderHotSwapping=o,u&&s&&s(u),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(l,16);n.clipPlane&&(r.clipPlane=h)};l()}forceCompilationAsync(e,t){return new Promise((i,s)=>{this.forceCompilation(e,()=>{i()},t,n=>{s(n)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(q._DirtyCallbackArray.length=0,e&q.TextureDirtyFlag&&q._DirtyCallbackArray.push(q._TextureDirtyCallBack),e&q.LightDirtyFlag&&q._DirtyCallbackArray.push(q._LightsDirtyCallBack),e&q.FresnelDirtyFlag&&q._DirtyCallbackArray.push(q._FresnelDirtyCallBack),e&q.AttributesDirtyFlag&&q._DirtyCallbackArray.push(q._AttributeDirtyCallBack),e&q.MiscDirtyFlag&&q._DirtyCallbackArray.push(q._MiscDirtyCallBack),e&q.PrePassDirtyFlag&&q._DirtyCallbackArray.push(q._PrePassDirtyCallBack),q._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(q._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const i of t.subMeshes)i.getMaterial()===this&&i.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 s of i.subMeshes)if(s.getMaterial(!1)===this)for(const n of s._drawWrappers)!n||!n.defines||!n.defines.markAllAsDirty||this._materialContext===n.materialContext&&e(n.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(q._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(q._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(q._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(q._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(q._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(q._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(q._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(q._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(q._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(q._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==0){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){const s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(2,this._eventInfo),this._parentContainer){const n=this._parentContainer.materials.indexOf(this);n>-1&&this._parentContainer.materials.splice(n,1),this._parentContainer=null}if(i!==!0)if(this.meshMap)for(const n in this.meshMap){const r=this.meshMap[n];r&&(r.material=null,this.releaseVertexArrayObject(r,e))}else{const n=s.meshes;for(const r of n)r.material===this&&!r.sourceMesh&&(r.material=null,this.releaseVertexArrayObject(r,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=Ae.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(const t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(!e.customType)e.customType="BABYLON.StandardMaterial";else if(e.customType==="BABYLON.PBRMaterial"&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return U.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;const n=ee.Instantiate(e.customType).Parse(e,t,i);return n._loadedUniqueId=e.uniqueId,n}static _ParsePlugins(e,t,i,s){var n;if(e.plugins)for(const r in e.plugins){const o=e.plugins[r];let l=(n=t.pluginManager)==null?void 0:n.getPlugin(o.name);if(!l){const h=ee.Instantiate("BABYLON."+r);h&&(l=new h(t))}l==null||l.parse(o,i,s)}}}q.TriangleFillMode=0;q.WireFrameFillMode=1;q.PointFillMode=2;q.PointListDrawMode=3;q.LineListDrawMode=4;q.LineLoopDrawMode=5;q.LineStripDrawMode=6;q.TriangleStripDrawMode=7;q.TriangleFanDrawMode=8;q.ClockWiseSideOrientation=0;q.CounterClockWiseSideOrientation=1;q.TextureDirtyFlag=1;q.LightDirtyFlag=2;q.FresnelDirtyFlag=4;q.AttributesDirtyFlag=8;q.MiscDirtyFlag=16;q.PrePassDirtyFlag=32;q.AllDirtyFlag=63;q.MATERIAL_OPAQUE=0;q.MATERIAL_ALPHATEST=1;q.MATERIAL_ALPHABLEND=2;q.MATERIAL_ALPHATESTANDBLEND=3;q.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0;q.MATERIAL_NORMALBLENDMETHOD_RNM=1;q.OnEventObservable=new Q;q._AllDirtyCallBack=a=>a.markAllAsDirty();q._ImageProcessingDirtyCallBack=a=>a.markAsImageProcessingDirty();q._TextureDirtyCallBack=a=>a.markAsTexturesDirty();q._FresnelDirtyCallBack=a=>a.markAsFresnelDirty();q._MiscDirtyCallBack=a=>a.markAsMiscDirty();q._PrePassDirtyCallBack=a=>a.markAsPrePassDirty();q._LightsDirtyCallBack=a=>a.markAsLightDirty();q._AttributeDirtyCallBack=a=>a.markAsAttributesDirty();q._FresnelAndMiscDirtyCallBack=a=>{q._FresnelDirtyCallBack(a),q._MiscDirtyCallBack(a)};q._TextureAndMiscDirtyCallBack=a=>{q._TextureDirtyCallBack(a),q._MiscDirtyCallBack(a)};q._DirtyCallbackArray=[];q._RunDirtyCallBacks=a=>{for(const e of q._DirtyCallbackArray)e(a)};D([B()],q.prototype,"id",void 0);D([B()],q.prototype,"uniqueId",void 0);D([B()],q.prototype,"name",void 0);D([B()],q.prototype,"metadata",void 0);D([B()],q.prototype,"checkReadyOnEveryCall",void 0);D([B()],q.prototype,"checkReadyOnlyOnce",void 0);D([B()],q.prototype,"state",void 0);D([B("alpha")],q.prototype,"_alpha",void 0);D([B("backFaceCulling")],q.prototype,"_backFaceCulling",void 0);D([B("cullBackFaces")],q.prototype,"_cullBackFaces",void 0);D([B()],q.prototype,"sideOrientation",void 0);D([B("alphaMode")],q.prototype,"_alphaMode",void 0);D([B()],q.prototype,"_needDepthPrePass",void 0);D([B()],q.prototype,"disableDepthWrite",void 0);D([B()],q.prototype,"disableColorWrite",void 0);D([B()],q.prototype,"forceDepthWrite",void 0);D([B()],q.prototype,"depthFunction",void 0);D([B()],q.prototype,"separateCullingPass",void 0);D([B("fogEnabled")],q.prototype,"_fogEnabled",void 0);D([B()],q.prototype,"pointSize",void 0);D([B()],q.prototype,"zOffset",void 0);D([B()],q.prototype,"zOffsetUnits",void 0);D([B()],q.prototype,"pointsCloud",null);D([B()],q.prototype,"fillMode",null);D([B()],q.prototype,"useLogarithmicDepth",null);D([B()],q.prototype,"transparencyMode",null);class tn extends q{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...s)=>{const n=t.apply(e,s);return this._markAllSubMeshesAsTexturesDirty(),n};const i=e.splice;e.splice=(s,n)=>{const r=i.apply(e,[s,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&&s.multiMaterials.splice(n,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new tn(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,ze&&ze.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(s=>i.subMaterials.push(t.getLastMaterialById(s))),i}}ft("BABYLON.MultiMaterial",tn);class vg{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class sc{}class xg{constructor(){this.visibleInstances={},this.batchCache=new _l,this.batchCacheReplacementModeInFrozenMode=new _l,this.instancesBufferSize=32*16*4}}class _l{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class bg{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=32*16,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class yg{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}class F extends et{static _GetDefaultSideOrientation(e){return e||F.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(E.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(E.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 Q),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new Q),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new Q),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new Q),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new Q),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get sideOrientation(){return this._internalMeshDataInfo._sideOrientation}set sideOrientation(e){this._internalMeshDataInfo._sideOrientation=e,this._internalAbstractMeshDataInfo._sideOrientationHint=this._scene.useRightHandedSystem&&e===1||!this._scene.useRightHandedSystem&&e===0}get overrideMaterialSideOrientation(){return this.sideOrientation}set overrideMaterialSideOrientation(e){this.sideOrientation=e,this.material&&(this.material.sideOrientation=null)}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){e&&(this.material&&this.material.sideOrientation===null||this._internalAbstractMeshDataInfo._sideOrientationHint)&&(e.sideOrientation=null),this._setMaterial(e)}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}constructor(e,t=null,i=null,s=null,n,r=!0){if(super(e,t),this._internalMeshDataInfo=new yg,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new xg,this._thinInstanceDataStorage=new bg,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=F.DEFAULTSIDE,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._scene.useRightHandedSystem?this.sideOrientation=0:this.sideOrientation=1,this._onBeforeDraw=(o,l,h)=>{o&&h&&(this._uniformBuffer?this.transferToEffect(l):h.bindOnlyWorldMatrix(l))},s){if(s._geometry&&s._geometry.applyToMesh(this),Ya.DeepCopy(s,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=s,t.useClonedMeshMap&&(s._internalMeshDataInfo.meshMap||(s._internalMeshDataInfo.meshMap={}),s._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=s._originalBuilderSideOrientation,this._creationDataStorage=s._creationDataStorage,s._ranges){const o=s._ranges;for(const l in o)Object.prototype.hasOwnProperty.call(o,l)&&o[l]&&this.createAnimationRange(l,o[l].from,o[l].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,ze&&ze.HasTags(s)&&ze.AddTagsTo(this,ze.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=e+"."+s.id,this.material=s.material,!n){const o=s.getDescendants(!0);for(let l=0;l{o.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 Q(this._internalMeshDataInfo._onMeshReadyObserverAdded),s&&s.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const s=this.getTotalVertices()===0||t&&t.doNotInstantiate&&(t.doNotInstantiate===!0||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));s.parent=e||this.parent,s.position=this.position.clone(),s.scaling=this.scaling.clone(),this.rotationQuaternion?s.rotationQuaternion=this.rotationQuaternion.clone():s.rotation=this.rotation.clone(),i&&i(this,s);for(const n of this.getChildTransformNodes(!0))n.getClassName()==="InstancedMesh"&&s.getClassName()==="Mesh"&&n.sourceMesh===this?n.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):n.instantiateHierarchy(s,t,i);return s}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;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 U.Warn("You cannot use a mesh as LOD level twice"),this;const i=new vg(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;io*r)return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,this),this;for(let l=0;l0||this.hasThinInstances);this.computeWorldMatrix();const r=this.material||s.defaultMaterial;if(r){if(r._storeEffectOnSubMeshes)for(const g of this.subMeshes){const _=g.getMaterial();if(_){if(_._storeEffectOnSubMeshes){if(!_.isReadyForSubMesh(this,g,n))return!1}else if(!_.isReady(this,n))return!1}}else if(!r.isReady(this,n))return!1}const o=i.currentRenderPassId;for(const g of this.lightSources){const _=g.getShadowGenerators();if(!_)continue;const m=_.values();for(let x=m.next();x.done!==!0;x=m.next()){const I=x.value;if(I&&(!((l=I.getShadowMap())!=null&&l.renderList)||(h=I.getShadowMap())!=null&&h.renderList&&((u=(c=I.getShadowMap())==null?void 0:c.renderList)==null?void 0:u.indexOf(this))!==-1)){const y=(f=I.getShadowMap().renderPassIds)!=null?f:[i.currentRenderPassId];for(let b=0;b0){const i=this.getIndices();if(!i)return null;const s=i.length;let n=!1;if(e)n=!0;else for(const r of this.subMeshes){if(r.indexStart+r.indexCount>s){n=!0;break}if(r.verticesStart+r.verticesCount>t){n=!0;break}}if(!n)return this.subMeshes[0]}return this.releaseSubMeshes(),new vi(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,s=0;for(;i%3!==0;)i++;this.releaseSubMeshes();for(let n=0;n=t);n++)vi.CreateFromIndices(0,s,n===e-1?t-s:i,this,void 0,!1),s+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const n=new j;n.set(t,e);const r=this.getScene();new kt(kt.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=kt.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,s){return this._geometry?(s?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(E.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(E.PositionKind,i,!1,!1),t){const s=this.getIndices(),n=this.getVerticesData(E.NormalKind);if(!n)return this;j.ComputeNormals(i,s,n),this.updateVerticesData(E.NormalKind,n,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(this._geometry.meshes.length===1)return this;const e=this._geometry,t=this._geometry.copy(kt.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new kt(kt.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const s=new j;s.indices=e;const n=this.getScene();new kt(kt.RandomId(),n,s,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,s=!0){if(!this._geometry)return this;const n=this.getScene().getEngine();let r;if(this._unIndexed)r=null;else switch(this._getRenderingFillMode(i)){case q.PointFillMode:r=null;break;case q.WireFrameFillMode:r=e._getLinesIndexBuffer(this.getIndices(),n);break;default:case q.TriangleFillMode:r=this._geometry.getIndexBuffer();break}return this._bindDirect(t,r,s)}_bindDirect(e,t,i=!0){return this._geometry?(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(e),!i||!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(e,t):this._geometry._bind(e,t,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),this):this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const n=this.getScene().getEngine();return this._unIndexed||t==q.PointFillMode?n.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==q.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(),s=i._isInIntermediateRendering(),n=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,r=this._instanceDataStorage.batchCache;if(r.mustReturn=!1,r.renderSelf[e]=t||!n&&this.isEnabled()&&this.isVisible,r.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const o=this._instanceDataStorage.visibleInstances,l=i.getRenderId(),h=s?o.intermediateDefaultRenderId:o.defaultRenderId;r.visibleInstances[e]=o[l],!r.visibleInstances[e]&&h&&(r.visibleInstances[e]=o[h])}return r.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&r.visibleInstances[e]!==null&&r.visibleInstances[e]!==void 0,this._instanceDataStorage.previousBatch=r,r}_renderWithInstances(e,t,i,s,n){var x;const r=i.visibleInstances[e._id],o=r?r.length:0,l=this._instanceDataStorage,h=l.instancesBufferSize;let c=l.instancesBuffer,u=l.instancesPreviousBuffer;const d=(o+1)*16*4;for(;l.instancesBufferSizey._distanceToCamera>b._distanceToCamera?-1:y._distanceToCamera1&&s.activeCamera===s.activeCameras[0]||n<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const o=this._getInstancesRenderList(e._id,!!i);if(o.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const l=s.getEngine();let h=0,c=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(h=s.activeCamera.maxZ,c=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const u=e.getRenderingMesh(),f=o.hardwareInstancedRendering[e._id]||u.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,d=this._instanceDataStorage,p=e.getMaterial();if(!p)return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this;if(!d.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==p){if(p._storeEffectOnSubMeshes){if(!p.isReadyForSubMesh(this,e,f))return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this}else if(!p.isReady(this,f))return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=p}else if(p._storeEffectOnSubMeshes&&!((M=e._drawWrapper)!=null&&M._wasPreviouslyReady)||!p._storeEffectOnSubMeshes&&!p._getDrawWrapper()._wasPreviouslyReady)return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this;t&&l.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);let g;this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?g=e._drawWrapper:g=this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const _=(C=g==null?void 0:g.effect)!=null?C:null;for(const w of s._beforeRenderingMeshStage)w.action(this,e,o,_);if(!g||!_)return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this;const m=i||this;let x;if(!d.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||this._internalMeshDataInfo._effectiveMaterial.sideOrientation!==null||this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)){const w=m._getWorldMatrixDeterminant();x=this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this),w<0&&(x=x===q.ClockWiseSideOrientation?q.CounterClockWiseSideOrientation:q.ClockWiseSideOrientation),d.sideOrientation=x}else x=d.sideOrientation;const I=this._internalMeshDataInfo._effectiveMaterial._preBind(g,x);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&l.setDepthWrite(!0);const T=this._internalMeshDataInfo._effectiveMaterial,y=T.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),f||this._bind(e,_,y,!1);const b=m.getWorldMatrix();T._storeEffectOnSubMeshes?T.bindForSubMesh(b,this,e):T.bind(b,this),!T.backFaceCulling&&T.separateCullingPass&&(l.setState(!0,T.zOffset,!1,!I,T.cullBackFaces,T.stencil,T.zOffsetUnits),this._processRendering(this,e,_,y,o,f,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),l.setState(!0,T.zOffset,!1,I,T.cullBackFaces,T.stencil,T.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,_,y,o,f,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const w of s._afterRenderingMeshStage)w.action(this,e,o,_);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),c&&(c.maxZ=h,s.updateTransformMatrix(!0)),s.performancePriority===2&&!d.isFrozen&&this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(E.MatricesWeightsKind)&&(this.isVerticesDataPresent(E.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(E.MatricesWeightsKind),t=e.length;for(let i=0;im&&s++,y!==0&&I++,x+=y,m=y}if(h[I]++,I>r&&(r=I),x===0)n++;else{const T=1/x;let y=0;for(let b=0;bc&&o++}}const u=this.skeleton.bones.length,f=this.getVerticesData(E.MatricesIndicesKind),d=this.getVerticesData(E.MatricesIndicesExtraKind);let p=0;for(let _=0;_=u||x<0)&&p++}const g="Number of Weights = "+i/4+"\nMaximum influences = "+r+"\nMissing Weights = "+n+"\nNot Sorted = "+s+"\nNot Normalized = "+o+"\nWeightCounts = ["+h+"]\nNumber of bones = "+u+"\nBad Bone Indices = "+p;return{skinned:!0,valid:n===0&&o===0&&p===0,report:g}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===4&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=this.delayLoadingFile.indexOf(".babylonbinarymeshdata")!==-1;return ee.LoadFile(this.delayLoadingFile,i=>{i instanceof ArrayBuffer?this._delayLoadingFunction(i,this):this._delayLoadingFunction(JSON.parse(i),this),this.instances.forEach(s=>{s.refreshBoundingInfo(),s._syncSubMeshes()}),this.delayLoadState=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return this.delayLoadState===2||!super.isInFrustum(e)?!1:(this._checkDelayState(),!0)}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const s=this.getScene().multiMaterials;for(i=s.length-1;i>-1;i--)if(s[i].id===e)return this.material=s[i],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(E.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(E.PositionKind);const s=v.Zero();let n;for(n=0;n{const f=u.width,d=u.height,g=this.getEngine().createCanvas(f,d).getContext("2d");g.drawImage(u,0,0);const _=g.getImageData(0,0,f,d).data;this.applyDisplacementMapFromBuffer(_,f,d,t,i,n,r,o),s&&s(this)};return ee.LoadImage(e,c,l||(()=>{}),h.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,n,r,o,l=!1){if(!this.isVerticesDataPresent(E.PositionKind)||!this.isVerticesDataPresent(E.NormalKind)||!this.isVerticesDataPresent(E.UVKind))return U.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const h=this.getVerticesData(E.PositionKind,!0,!0),c=this.getVerticesData(E.NormalKind),u=this.getVerticesData(E.UVKind);let f=v.Zero();const d=v.Zero(),p=fe.Zero();r=r||fe.Zero(),o=o||new fe(1,1);for(let g=0;g{const c=new Float32Array(i.length*h);let u=0;for(let f=0;f{const o=s.length-1-r,l=s[o];for(let h=0;h{for(let o=0;o-1&&(s.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),e.skeletonId!==void 0&&e.skeletonId!==null&&(s.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(s.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let n=0;n4,h=l?this.getVerticesData(E.MatricesIndicesExtraKind):null,c=l?this.getVerticesData(E.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),f=v.Zero(),d=new O,p=new O;let g=0,_;for(let m=0;m0&&(O.FromFloat32ArrayToRefScaled(u,Math.floor(r[g+_]*16),x,p),d.addToSelf(p));if(l)for(_=0;_<4;_++)x=c[g+_],x>0&&(O.FromFloat32ArrayToRefScaled(u,Math.floor(h[g+_]*16),x,p),d.addToSelf(p));v.TransformCoordinatesFromFloatsToRef(i._sourcePositions[m],i._sourcePositions[m+1],i._sourcePositions[m+2],d,f),f.toArray(s,m),t&&(v.TransformNormalFromFloatsToRef(i._sourceNormals[m],i._sourceNormals[m+1],i._sourceNormals[m+2],d,f),f.toArray(n,m)),d.reset()}return this.updateVerticesData(E.PositionKind,s),t&&this.updateVerticesData(E.NormalKind,n),this}static MinMax(e){let t=null,i=null;return e.forEach(function(s){const r=s.getBoundingInfo().boundingBox;!t||!i?(t=r.minimumWorld,i=r.maximumWorld):(t.minimizeInPlace(r.minimumWorld),i.maximizeInPlace(r.maximumWorld))}),!t||!i?{min:v.Zero(),max:v.Zero()}:{min:t,max:i}}static Center(e){const t=e instanceof Array?F.MinMax(e):e;return v.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,n,r){return co(F._MergeMeshesCoroutine(e,t,i,s,n,r,!1))}static MergeMeshesAsync(e,t=!0,i,s,n,r){return X_(F._MergeMeshesCoroutine(e,t,i,s,n,r,!0),W_())}static*_MergeMeshesCoroutine(e,t=!0,i,s,n,r,o){if(e=e.filter(Boolean),e.length===0)return null;let l;if(!i){let S=0;for(l=0;l=65536)return U.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}r&&(n=!1);const h=new Array,c=new Array,u=new Array,f=e[0].sideOrientation;for(l=0;l{const A=S.computeWorldMatrix(!0);return{vertexData:j.ExtractFromMesh(S,!1,!1),transform:A}},{vertexData:g,transform:_}=p(d);o&&(yield);const m=new Array(e.length-1);for(let S=1;S{throw Te("GroundMesh")};F._GoldbergMeshParser=(a,e)=>{throw Te("GoldbergMesh")};F._LinesMeshParser=(a,e)=>{throw Te("LinesMesh")};F._GreasedLineMeshParser=(a,e)=>{throw Te("GreasedLineMesh")};F._GreasedLineRibbonMeshParser=(a,e)=>{throw Te("GreasedLineRibbonMesh")};F._TrailMeshParser=(a,e)=>{throw Te("TrailMesh")};ft("BABYLON.Mesh",F);class Tg{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(i=>{if(i.type===Re.POINTERDOWN){this._isPointerDown=!0;return}i.type===Re.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;const i=xi.Now;let s=0;this._lastFrameTime!=null&&(s=i-this._lastFrameTime),this._lastFrameTime=i,this._applyUserInteraction();const n=i-this._lastInteractionTime-this._idleRotationWaitTime,r=Math.max(Math.min(n/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*r,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(s/1e3))})}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=e!=null?e:xi.Now}_reachTargetAlpha(){return this._attachedCamera&&this.targetAlpha?Math.abs(this._attachedCamera.alpha-this.targetAlpha)=.5?(1-this.easeInCore((1-e)*2))*.5+.5:this.easeInCore(e*2)*.5}}Di.EASINGMODE_EASEIN=0;Di.EASINGMODE_EASEOUT=1;Di.EASINGMODE_EASEINOUT=2;class Sg extends Di{constructor(e=1){super(),this.amplitude=e}easeInCore(e){const t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}}class Eg extends Di{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}}class Fr{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new Fr(this.name,this.from,this.to)}}const Ig=Object.freeze(new le(0,0,0,0)),Ag=Object.freeze(v.Zero()),Cg=Object.freeze(fe.Zero()),Mg=Object.freeze(oi.Zero()),Rg=Object.freeze(pe.Black()),Pg=Object.freeze(new X(0,0,0,0)),Ii={key:0,repeatCount:0,loopMode:2};class se{static _PrepareAnimation(e,t,i,s,n,r,o,l){let h;if(!isNaN(parseFloat(n))&&isFinite(n)?h=se.ANIMATIONTYPE_FLOAT:n instanceof le?h=se.ANIMATIONTYPE_QUATERNION:n instanceof v?h=se.ANIMATIONTYPE_VECTOR3:n instanceof fe?h=se.ANIMATIONTYPE_VECTOR2:n instanceof pe?h=se.ANIMATIONTYPE_COLOR3:n instanceof X?h=se.ANIMATIONTYPE_COLOR4:n instanceof oi&&(h=se.ANIMATIONTYPE_SIZE),h==null)return null;const c=new se(e,t,i,h,o),u=[{frame:0,value:n},{frame:s,value:r}];return c.setKeys(u),l!==void 0&&c.setEasingFunction(l),c}static CreateAnimation(e,t,i,s){const n=new se(e+"Animation",e,i,t,se.ANIMATIONLOOPMODE_CONSTANT);return n.setEasingFunction(s),n}static CreateAndStartAnimation(e,t,i,s,n,r,o,l,h,c,u){const f=se._PrepareAnimation(e,i,s,n,r,o,l,h);return!f||(t.getScene&&(u=t.getScene()),!u)?null:u.beginDirectAnimation(t,[f],0,n,f.loopMode===1,1,c)}static CreateAndStartHierarchyAnimation(e,t,i,s,n,r,o,l,h,c,u){const f=se._PrepareAnimation(e,s,n,r,o,l,h,c);return f?t.getScene().beginDirectHierarchyAnimation(t,i,[f],0,r,f.loopMode===1,1,u):null}static CreateMergeAndStartAnimation(e,t,i,s,n,r,o,l,h,c){const u=se._PrepareAnimation(e,i,s,n,r,o,l,h);return u?(t.animations.push(u),t.getScene().beginAnimation(t,0,n,u.loopMode===1,1,c)):null}static MakeAnimationAdditive(e,t,i,s=!1,n){var x,I;let r;typeof t=="object"?r=t:r={referenceFrame:t!=null?t:0,range:i,cloneOriginalAnimation:s,clonedAnimationName:n};let o=e;if(r.cloneOriginalAnimation&&(o=e.clone(),o.name=r.clonedAnimationName||o.name),!o._keys.length)return o;const l=r.referenceFrame&&r.referenceFrame>=0?r.referenceFrame:0;let h=0;const c=o._keys[0];let u=o._keys.length-1;const f=o._keys[u],d={referenceValue:c.value,referencePosition:N.Vector3[0],referenceQuaternion:N.Quaternion[0],referenceScaling:N.Vector3[1],keyPosition:N.Vector3[2],keyQuaternion:N.Quaternion[1],keyScaling:N.Vector3[3]};let p=c.frame,g=f.frame;if(r.range){const T=o.getRange(r.range);T&&(p=T.from,g=T.to)}else p=(x=r.fromFrame)!=null?x:p,g=(I=r.toFrame)!=null?I:g;if(p!==c.frame&&(h=o.createKeyForFrame(p)),g!==f.frame&&(u=o.createKeyForFrame(g)),o._keys.length===1){const T=o._getKeyValue(o._keys[0]);d.referenceValue=T.clone?T.clone():T}else if(l<=c.frame){const T=o._getKeyValue(c.value);d.referenceValue=T.clone?T.clone():T}else if(l>=f.frame){const T=o._getKeyValue(f.value);d.referenceValue=T.clone?T.clone():T}else{Ii.key=0;const T=o._interpolate(l,Ii);d.referenceValue=T.clone?T.clone():T}o.dataType===se.ANIMATIONTYPE_QUATERNION?d.referenceValue.normalize().conjugateInPlace():o.dataType===se.ANIMATIONTYPE_MATRIX&&(d.referenceValue.decompose(d.referenceScaling,d.referenceQuaternion,d.referencePosition),d.referenceQuaternion.normalize().conjugateInPlace());let _=Number.MAX_VALUE;const m=r.clipKeys?[]:null;for(let T=h;T<=u;T++){let y=o._keys[T];if((m||r.cloneOriginalAnimation)&&(y={frame:y.frame,value:y.value.clone?y.value.clone():y.value,inTangent:y.inTangent,outTangent:y.outTangent,interpolation:y.interpolation,lockedTangent:y.lockedTangent},m&&(_===Number.MAX_VALUE&&(_=y.frame),y.frame-=_,m.push(y))),!(T&&o.dataType!==se.ANIMATIONTYPE_FLOAT&&y.value===c.value))switch(o.dataType){case se.ANIMATIONTYPE_MATRIX:y.value.decompose(d.keyScaling,d.keyQuaternion,d.keyPosition),d.keyPosition.subtractInPlace(d.referencePosition),d.keyScaling.divideInPlace(d.referenceScaling),d.referenceQuaternion.multiplyToRef(d.keyQuaternion,d.keyQuaternion),O.ComposeToRef(d.keyScaling,d.keyQuaternion,d.keyPosition,y.value);break;case se.ANIMATIONTYPE_QUATERNION:d.referenceValue.multiplyToRef(y.value,y.value);break;case se.ANIMATIONTYPE_VECTOR2:case se.ANIMATIONTYPE_VECTOR3:case se.ANIMATIONTYPE_COLOR3:case se.ANIMATIONTYPE_COLOR4:y.value.subtractToRef(d.referenceValue,y.value);break;case se.ANIMATIONTYPE_SIZE:y.value.width-=d.referenceValue.width,y.value.height-=d.referenceValue.height;break;default:y.value-=d.referenceValue}}return m&&o.setKeys(m,!0),o}static TransitionTo(e,t,i,s,n,r,o,l=null){if(o<=0)return i[e]=t,l&&l(),null;const h=n*(o/1e3);r.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:h,value:t}]),i.animations||(i.animations=[]),i.animations.push(r);const c=s.beginAnimation(i,0,h,!1);return c.onAnimationEnd=l,c}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,s,n,r){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=s,this.loopMode=n,this.enableBlending=r,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=s,this.loopMode=n===void 0?se.ANIMATIONLOOPMODE_CYCLE:n,this.uniqueId=se._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let i=!0;for(const s in this._ranges)i&&(t+=", ",i=!1),t+=s;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort((t,i)=>t.frame-i.frame)}removeEvents(e){for(let t=0;t=0;r--)this._keys[r].frame>=s&&this._keys[r].frame<=n&&this._keys.splice(r,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 s=this._keys,n=s.length;let r=t.key;for(;r>=0&&e=s[r+1].frame;)++r;if(t.key=r,r<0)return i?void 0:this._getKeyValue(s[0].value);if(r+1>n-1)return i?void 0:this._getKeyValue(s[n-1].value);const o=s[r],l=s[r+1];if(i&&(e===o.frame||e===l.frame))return;const h=this._getKeyValue(o.value),c=this._getKeyValue(l.value);if(o.interpolation===1)return l.frame>e?h:c;const u=o.outTangent!==void 0&&l.inTangent!==void 0,f=l.frame-o.frame;let d=(e-o.frame)/f;const p=o.easingFunction||this.getEasingFunction();switch(p!==null&&(d=p.ease(d)),this.dataType){case se.ANIMATIONTYPE_FLOAT:{const _=u?this.floatInterpolateFunctionWithTangents(h,o.outTangent*f,c,l.inTangent*f,d):this.floatInterpolateFunction(h,c,d);switch(t.loopMode){case se.ANIMATIONLOOPMODE_CYCLE:case se.ANIMATIONLOOPMODE_CONSTANT:case se.ANIMATIONLOOPMODE_YOYO:return _;case se.ANIMATIONLOOPMODE_RELATIVE:case se.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return((g=t.offsetValue)!=null?g:0)*t.repeatCount+_}break}case se.ANIMATIONTYPE_QUATERNION:{const _=u?this.quaternionInterpolateFunctionWithTangents(h,o.outTangent.scale(f),c,l.inTangent.scale(f),d):this.quaternionInterpolateFunction(h,c,d);switch(t.loopMode){case se.ANIMATIONLOOPMODE_CYCLE:case se.ANIMATIONLOOPMODE_CONSTANT:case se.ANIMATIONLOOPMODE_YOYO:return _;case se.ANIMATIONLOOPMODE_RELATIVE:case se.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.addInPlace((t.offsetValue||Ig).scale(t.repeatCount))}return _}case se.ANIMATIONTYPE_VECTOR3:{const _=u?this.vector3InterpolateFunctionWithTangents(h,o.outTangent.scale(f),c,l.inTangent.scale(f),d):this.vector3InterpolateFunction(h,c,d);switch(t.loopMode){case se.ANIMATIONLOOPMODE_CYCLE:case se.ANIMATIONLOOPMODE_CONSTANT:case se.ANIMATIONLOOPMODE_YOYO:return _;case se.ANIMATIONLOOPMODE_RELATIVE:case se.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.add((t.offsetValue||Ag).scale(t.repeatCount))}break}case se.ANIMATIONTYPE_VECTOR2:{const _=u?this.vector2InterpolateFunctionWithTangents(h,o.outTangent.scale(f),c,l.inTangent.scale(f),d):this.vector2InterpolateFunction(h,c,d);switch(t.loopMode){case se.ANIMATIONLOOPMODE_CYCLE:case se.ANIMATIONLOOPMODE_CONSTANT:case se.ANIMATIONLOOPMODE_YOYO:return _;case se.ANIMATIONLOOPMODE_RELATIVE:case se.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.add((t.offsetValue||Cg).scale(t.repeatCount))}break}case se.ANIMATIONTYPE_SIZE:{switch(t.loopMode){case se.ANIMATIONLOOPMODE_CYCLE:case se.ANIMATIONLOOPMODE_CONSTANT:case se.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(h,c,d);case se.ANIMATIONLOOPMODE_RELATIVE:case se.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(h,c,d).add((t.offsetValue||Mg).scale(t.repeatCount))}break}case se.ANIMATIONTYPE_COLOR3:{const _=u?this.color3InterpolateFunctionWithTangents(h,o.outTangent.scale(f),c,l.inTangent.scale(f),d):this.color3InterpolateFunction(h,c,d);switch(t.loopMode){case se.ANIMATIONLOOPMODE_CYCLE:case se.ANIMATIONLOOPMODE_CONSTANT:case se.ANIMATIONLOOPMODE_YOYO:return _;case se.ANIMATIONLOOPMODE_RELATIVE:case se.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.add((t.offsetValue||Rg).scale(t.repeatCount))}break}case se.ANIMATIONTYPE_COLOR4:{const _=u?this.color4InterpolateFunctionWithTangents(h,o.outTangent.scale(f),c,l.inTangent.scale(f),d):this.color4InterpolateFunction(h,c,d);switch(t.loopMode){case se.ANIMATIONLOOPMODE_CYCLE:case se.ANIMATIONLOOPMODE_CONSTANT:case se.ANIMATIONLOOPMODE_YOYO:return _;case se.ANIMATIONLOOPMODE_RELATIVE:case se.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.add((t.offsetValue||Pg).scale(t.repeatCount))}break}case se.ANIMATIONTYPE_MATRIX:{switch(t.loopMode){case se.ANIMATIONLOOPMODE_CYCLE:case se.ANIMATIONLOOPMODE_CONSTANT:case se.ANIMATIONLOOPMODE_YOYO:return se.AllowMatricesInterpolation?this.matrixInterpolateFunction(h,c,d,t.workValue):h;case se.ANIMATIONLOOPMODE_RELATIVE:case se.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return h}break}}return 0}matrixInterpolateFunction(e,t,i,s){return se.AllowMatrixDecomposeForInterpolation?s?(O.DecomposeLerpToRef(e,t,i,s),s):O.DecomposeLerp(e,t,i):s?(O.LerpToRef(e,t,i,s),s):O.Lerp(e,t,i)}clone(){const e=new se(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(const t in this._ranges){const i=this._ranges[t];i&&(e._ranges[t]=i.clone())}}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){Ii.key=0;const t=this._interpolate(e,Ii,!0);if(!t)return this._keys[Ii.key].frame===e?Ii.key:Ii.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(Ii.key+1,0,i),Ii.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let s=0;s=2&&(l=o.values[1]),o.values.length>=3&&(h=o.values[2]),o.values.length>=4&&(c=o.values[3]);break;case se.ANIMATIONTYPE_QUATERNION:if(n=le.FromArray(o.values),o.values.length>=8){const f=le.FromArray(o.values.slice(4,8));f.equals(le.Zero())||(l=f)}if(o.values.length>=12){const f=le.FromArray(o.values.slice(8,12));f.equals(le.Zero())||(h=f)}o.values.length>=13&&(c=o.values[12]);break;case se.ANIMATIONTYPE_MATRIX:n=O.FromArray(o.values),o.values.length>=17&&(c=o.values[16]);break;case se.ANIMATIONTYPE_COLOR3:n=pe.FromArray(o.values),o.values[3]&&(l=pe.FromArray(o.values[3])),o.values[4]&&(h=pe.FromArray(o.values[4])),o.values[5]&&(c=o.values[5]);break;case se.ANIMATIONTYPE_COLOR4:n=X.FromArray(o.values),o.values[4]&&(l=X.FromArray(o.values[4])),o.values[5]&&(h=X.FromArray(o.values[5])),o.values[6]&&(c=X.FromArray(o.values[6]));break;case se.ANIMATIONTYPE_VECTOR3:default:n=v.FromArray(o.values),o.values[3]&&(l=v.FromArray(o.values[3])),o.values[4]&&(h=v.FromArray(o.values[4])),o.values[5]&&(c=o.values[5]);break}const u={};u.frame=o.frame,u.value=n,l!=null&&(u.inTangent=l),h!=null&&(u.outTangent=h),c!=null&&(u.interpolation=c),s.push(u)}if(t.setKeys(s),e.ranges)for(r=0;r{const n=new Ft;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){let r=JSON.parse(n.responseText);if(r.animations&&(r=r.animations),r.length){const o=[];for(const l of r)o.push(this.Parse(l));i(o)}else{const o=this.Parse(r);e&&(o.name=e),i(o)}}else s("Unable to load the animation")}),n.open("GET",t),n.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{const s=new Ft;s.addEventListener("readystatechange",()=>{if(s.readyState==4)if(s.status==200){const n=JSON.parse(JSON.parse(s.responseText).jsonPayload);if(n.animations){const r=JSON.parse(n.animations),o=[];for(const l of r.animations){const h=this.Parse(l);h.snippetId=e,o.push(h)}t(o)}else{const r=JSON.parse(n.animation),o=this.Parse(r);o.snippetId=e,t(o)}}else i("Unable to load the snippet "+e)}),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()})}}se._UniqueIdGenerator=0;se.AllowMatricesInterpolation=!1;se.AllowMatrixDecomposeForInterpolation=!0;se.SnippetUrl="https://snippet.babylonjs.com";se.ANIMATIONTYPE_FLOAT=0;se.ANIMATIONTYPE_VECTOR3=1;se.ANIMATIONTYPE_QUATERNION=2;se.ANIMATIONTYPE_MATRIX=3;se.ANIMATIONTYPE_COLOR3=4;se.ANIMATIONTYPE_COLOR4=7;se.ANIMATIONTYPE_VECTOR2=5;se.ANIMATIONTYPE_SIZE=6;se.ANIMATIONLOOPMODE_RELATIVE=0;se.ANIMATIONLOOPMODE_CYCLE=1;se.ANIMATIONLOOPMODE_CONSTANT=2;se.ANIMATIONLOOPMODE_YOYO=4;se.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5;se.CreateFromSnippetAsync=se.ParseFromSnippetAsync;ft("BABYLON.Animation",se);mt._AnimationRangeFactory=(a,e,t)=>new Fr(a,e,t);class Ds{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(i=>{if(i&&(i.computeWorldMatrix(!0),i.getBoundingInfo)){const s=i.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=s*.05,this.upperRadiusTransitionRange=s*.05}}):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:!1}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(Ds.EasingFunction.setEasingMode(Ds.EasingMode),this._radiusBounceTransition=se.CreateAnimation("radius",se.ANIMATIONTYPE_FLOAT,60,Ds.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=se.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()}}Ds.EasingFunction=new Sg(.3);Ds.EasingMode=Di.EASINGMODE_EASEOUT;class jt{constructor(){this.onTargetFramingAnimationEndObservable=new Q,this._mode=jt.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();jt.EasingFunction.setEasingMode(jt.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===Re.POINTERDOWN){this._isPointerDown=!0;return}i.type===Re.POINTERUP&&(this._isPointerDown=!1)}),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add(i=>{i&&i.getBoundingInfo&&this.zoomOnMesh(i,void 0,()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()})}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()})}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(s.minimumWorld,s.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(s.min,s.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const s=new v(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new v(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let r=0;r{this.stopAllAnimations(),s&&s(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}),c&&this._animatables.push(c),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let s=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===jt.IgnoreBoundsSizeMode&&(s=si.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=xi.Now-this._lastInteractionTime,t=Math.PI*.5-this._defaultElevation,i=Math.PI*.5;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=se.CreateAnimation("beta",se.ANIMATIONTYPE_FLOAT,60,jt.EasingFunction));const s=se.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});s&&this._animatables.push(s)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=xi.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?this._attachedCamera.inertialAlphaOffset!==0||this._attachedCamera.inertialBetaOffset!==0||this._attachedCamera.inertialRadiusOffset!==0||this._attachedCamera.inertialPanningX!==0||this._attachedCamera.inertialPanningY!==0||this._isPointerDown:!1}}jt.EasingFunction=new Eg;jt.EasingMode=Di.EASINGMODE_EASEINOUT;jt.IgnoreBoundsSizeMode=0;jt.FitFrustumSidesMode=1;mt.AddNodeConstructor("TargetCamera",(a,e)=>()=>new Mt(a,v.Zero(),e));class Mt extends ve{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=v.Zero(),this._tmpTargetVector=v.Zero(),this.cameraDirection=new v(0,0,0),this.cameraRotation=new fe(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new le,this.rotation=new v(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=v.Zero(),this._initialFocalDistance=1,this._viewMatrix=O.Zero(),this._camMatrix=O.Zero(),this._cameraTransformMatrix=O.Zero(),this._cameraRotationMatrix=O.Zero(),this._referencePoint=new v(0,0,1),this._transformedReferencePoint=v.Zero(),this._deferredPositionUpdate=new v,this._deferredRotationQuaternionUpdate=new le,this._deferredRotationUpdate=new v,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=v.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();const t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){const e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return super._restoreStateValues()?(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0):!1}_initCache(){super._initCache(),this._cache.lockedTarget=new v(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new v(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new le(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()/(e.getFps()*100))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=Ne),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),O.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&&le.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){this.parent.getWorldMatrix().invertToRef(N.Matrix[0]),v.TransformNormalToRef(this.cameraDirection,N.Matrix[0],N.Vector3[0]),this._deferredPositionUpdate.addInPlace(N.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,this.noRotationConstraint||(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(le.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))),t&&(Math.abs(this.cameraDirection.x){}}add(e){const t=e.getSimpleName();if(this.attached[t]){U.Warn("camera input of type "+t+" already exists on camera");return}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){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}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=ve.ForceAttachControlToAlwaysPreventDefault?!1: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 i in this.attached){const s=this.attached[i],n=Ae.Serialize(s);t[s.getClassName()]=n}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const i in t){const s=Mn[i];if(s){const n=t[i],r=Ae.Parse(()=>new s,n,null);this.add(r)}}}else for(const i in this.attached){const s=Mn[this.attached[i].getClassName()];if(s){const n=Ae.Parse(()=>new s,e,null);this.remove(this.attached[i]),this.add(n)}}}}class nc{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=ee.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let s=0,n=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=o=>{var u,f;const l=o.event,h=l.pointerType==="touch";if(o.type!==Re.POINTERMOVE&&this.buttons.indexOf(l.button)===-1)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 d=l.movementX,p=l.movementY;this.onTouch(null,d,p),this._pointA=null,this._pointB=null}else{if(o.type!==Re.POINTERDOWN&&o.type!==Re.POINTERDOUBLETAP&&h&&((u=this._pointA)==null?void 0:u.pointerId)!==l.pointerId&&((f=this._pointB)==null?void 0:f.pointerId)!==l.pointerId)return;if(o.type===Re.POINTERDOWN&&(this._currentActiveButton===-1||h)){try{c==null||c.setPointerCapture(l.pointerId)}catch{}if(this._pointA===null)this._pointA={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType};else if(this._pointB===null)this._pointB={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType};else return;this._currentActiveButton===-1&&!h&&(this._currentActiveButton=l.button),this.onButtonDown(l),e||(l.preventDefault(),i&&i.focus())}else if(o.type===Re.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(o.type===Re.POINTERUP&&(this._currentActiveButton===l.button||h)){try{c==null||c.releasePointerCapture(l.pointerId)}catch{}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,(s!==0||n)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,n,null),s=0,n=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else if(o.type===Re.POINTERMOVE){if(e||l.preventDefault(),this._pointA&&this._pointB===null){const d=l.clientX-this._pointA.x,p=l.clientY-this._pointA.y;this.onTouch(this._pointA,d,p),this._pointA.x=l.clientX,this._pointA.y=l.clientY}else if(this._pointA&&this._pointB){const d=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;d.x=l.clientX,d.y=l.clientY;const p=this._pointA.x-this._pointB.x,g=this._pointA.y-this._pointB.y,_=p*p+g*g,m={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:o.type};this.onMultiTouch(this._pointA,this._pointB,s,_,n,m),n=m,s=_}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Re.POINTERDOWN|Re.POINTERUP|Re.POINTERMOVE|Re.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,n=null,this.onLostFocus()},this._contextMenuBind=o=>this.onContextMenu(o),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const r=this.camera.getScene().getEngine().getHostWindow();r&&ee.RegisterTopRootEvents(r,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&ee.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,s,n,r){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}D([B()],nc.prototype,"buttons",void 0);class Jt extends nc{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(this.panningSensibility!==0&&e&&t){const i=t.x-e.x,s=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=s/this.panningSensibility}}_computePinchZoom(e,t){const i=this.camera.radius||Jt.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=(t-e)*.001*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){this.panningSensibility!==0&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,s,n,r){i===0&&n===null||s===0&&r===null||(this.multiTouchPanAndZoom?(this._computePinchZoom(i,s),this._computeMultiTouchPanning(n,r)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(s)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,s),this._isPinching=!0):this._computeMultiTouchPanning(n,r)):this.multiTouchPanning?this._computeMultiTouchPanning(n,r):this.pinchZoom&&this._computePinchZoom(i,s))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}Jt.MinimumRadiusForPinch=.001;D([B()],Jt.prototype,"buttons",void 0);D([B()],Jt.prototype,"angularSensibilityX",void 0);D([B()],Jt.prototype,"angularSensibilityY",void 0);D([B()],Jt.prototype,"pinchPrecision",void 0);D([B()],Jt.prototype,"pinchDeltaPercentage",void 0);D([B()],Jt.prototype,"useNaturalPinchZoom",void 0);D([B()],Jt.prototype,"pinchZoom",void 0);D([B()],Jt.prototype,"panningSensibility",void 0);D([B()],Jt.prototype,"multiTouchPanning",void 0);D([B()],Jt.prototype,"multiTouchPanAndZoom",void 0);Mn.ArcRotateCameraPointersInput=Jt;class Oi{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=ee.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===Cn.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(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)===-1&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(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){const s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,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?i=s/(1+this.wheelDeltaPercentage):i=s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=ee.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Re.POINTERWHEEL)return;const i=t.event;let s=0;const n=i.deltaMode===Nn.DOM_DELTA_LINE?Dg:1,r=-(i.deltaY*n);if(this.customComputeDeltaFromMouseWheel)s=this.customComputeDeltaFromMouseWheel(r,this,i);else if(this.wheelDeltaPercentage){if(s=this._computeDeltaFromMouseWheelLegacyEvent(r,this.camera.radius),s>0){let o=this.camera.radius,l=this.camera.inertialRadiusOffset+s;for(let h=0;h<20&&Math.abs(l)>.001;h++)o-=l,l*=this.camera.inertia;o=Ye.Clamp(o,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(r,o)}}else s=r/(this.wheelPrecision*40);s&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(s)):this.camera.inertialRadiusOffset+=s),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Re.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=Yt.FromPositionAndNormal(e.target,t)}_getPosition(){var n;const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,O.Identity(),e,!1);(e.targetScreenOffset.x!==0||e.targetScreenOffset.y!==0)&&(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=v.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=(n=i.intersectsPlane(this._hitPlane))!=null?n:0),i.origin.addInPlace(i.direction.scaleInPlace(s))}_zoomToMouse(e){var l,h;const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const c=(l=t.lowerRadiusLimit)!=null?l:0;t.radius-(t.inertialRadiusOffset+e)/ic&&(e=(t.radius-c)*i-t.inertialRadiusOffset)}const n=e/i/t.radius,r=this._getPosition(),o=N.Vector3[6];r.subtractToRef(t.target,o),o.scaleInPlace(n),o.scaleInPlace(i),this._inertialPanning.addInPlace(o),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)()=>new st(a,0,0,1,v.Zero(),e));class st extends Mt{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 O,this._upToYMatrix=new O,this._upVector=v.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){O.RotationAlignToRef(v.UpReadOnly,this._upVector,this._yToUpMatrix),O.RotationAlignToRef(this._upVector,v.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:!1}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:!1}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 this._bouncingBehavior!=null}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Ds,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return this._framingBehavior!=null}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new jt,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return this._autoRotationBehavior!=null}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new Tg,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,n,r,o=!0){super(e,v.Zero(),r,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=v.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=fe.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new O,this.panningAxis=new v(1,1,0),this._transformedDirection=new v,this.mapPanning=!1,this.onMeshTargetChangedObservable=new Q,this.checkCollisions=!1,this.collisionRadius=new v(.5,.5,.5),this._previousPosition=v.Zero(),this._collisionVelocity=v.Zero(),this._newPosition=v.Zero(),this._computationVector=v.Zero(),this._onCollisionPositionChange=(l,h,c=null)=>{c?(this.setPosition(h),this.onCollide&&this.onCollide(c)):this._previousPosition.copyFrom(this._position);const u=Math.cos(this.alpha),f=Math.sin(this.alpha),d=Math.cos(this.beta);let p=Math.sin(this.beta);p===0&&(p=1e-4);const g=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*u*p,this.radius*d,this.radius*f*p),g.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let _=this.upVector;this.allowUpsideDown&&this.beta<0&&(_=_.clone(),_=_.negate()),this._computeViewMatrix(this._position,g,_),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=v.Zero(),n&&this.setTarget(n),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new Fg(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new v(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=fe.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 t=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?t.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(t)}const e=this._getLockedTargetPosition();return e||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return 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):!1}_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):!1}attachControl(e,t,i=!0,s=2){const n=arguments;t=ee.BackCompatCameraNoPreventDefault(n),this._useCtrlForPanning=i,this._panningMouseButton=s,typeof n[0]=="boolean"&&(n.length>1&&(this._useCtrlForPanning=n[1]),n.length>2&&(this._panningMouseButton=n[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),this.inertialAlphaOffset!==0||this.inertialBetaOffset!==0||this.inertialRadiusOffset!==0){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),this.lowerAlphaLimit!==null&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),this.lowerRadiusLimit!==null&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&v.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),this.radius===0&&(this.radius=1e-4);const e=this.alpha;this._computationVector.x===0&&this._computationVector.z===0?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+=t*2*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,s=!1){var n;if(s=(n=this.overrideCloneAlphaBetaRadius)!=null?n:s,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const r=e,o=this._getTargetPosition();if(o&&!i&&o.equals(r))return;this._targetHost=null,this._target=r,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}s||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let s=Math.sin(this.beta);s===0&&(s=1e-4),this.radius===0&&(this.radius=1e-4);const n=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*s,this.radius*i,this.radius*t*s),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&v.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),n.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const r=this.getScene().collisionCoordinator;this._collider||(this._collider=r.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,r.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let r=this.upVector;this.allowUpsideDown&&s<0&&(r=r.negate()),this._computeViewMatrix(this._position,n,r),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=n,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=F.MinMax(e);let s=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);s=Math.max(Math.min(s,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=s*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:s},t)}focusOn(e,t=!1){let i,s;if(e.min===void 0){const n=e||this.getScene().meshes;i=F.MinMax(n),s=v.Distance(i.min,i.max)}else{const n=e;i=n,s=n.distance}this._target=F.Center(i),t||(this.maxZ=s*2)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ve.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ve.RIG_MODE_STEREOSCOPIC_INTERLACED:case ve.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(t===0?1:-1);break;case ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(t===0?-1:1);break}const s=new st(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return s._cameraRigParams={},s.isRigCamera=!0,s.rigParent=this,s.upVector=this.upVector,s.mode=this.mode,s.orthoLeft=this.orthoLeft,s.orthoRight=this.orthoRight,s.orthoBottom=this.orthoBottom,s.orthoTop=this.orthoTop,s}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ve.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ve.RIG_MODE_STEREOSCOPIC_INTERLACED:case ve.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle;break}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const s=v.Distance(e,t),r=this.getScene().getEngine().getAspectRatio(this),o=Math.tan(this.fov/2),l=o*r,c=s*.5*i,u=c*Math.sqrt(1+1/(l*l)),f=c*Math.sqrt(1+1/(o*o));return Math.max(u,f)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}D([B()],st.prototype,"alpha",void 0);D([B()],st.prototype,"beta",void 0);D([B()],st.prototype,"radius",void 0);D([B()],st.prototype,"overrideCloneAlphaBetaRadius",void 0);D([bi("target")],st.prototype,"_target",void 0);D([Lh("targetHost")],st.prototype,"_targetHost",void 0);D([B()],st.prototype,"inertialAlphaOffset",void 0);D([B()],st.prototype,"inertialBetaOffset",void 0);D([B()],st.prototype,"inertialRadiusOffset",void 0);D([B()],st.prototype,"lowerAlphaLimit",void 0);D([B()],st.prototype,"upperAlphaLimit",void 0);D([B()],st.prototype,"lowerBetaLimit",void 0);D([B()],st.prototype,"upperBetaLimit",void 0);D([B()],st.prototype,"lowerRadiusLimit",void 0);D([B()],st.prototype,"upperRadiusLimit",void 0);D([B()],st.prototype,"inertialPanningX",void 0);D([B()],st.prototype,"inertialPanningY",void 0);D([B()],st.prototype,"pinchToPanMaxDistance",void 0);D([B()],st.prototype,"panningDistanceLimit",void 0);D([bi()],st.prototype,"panningOriginTarget",void 0);D([B()],st.prototype,"panningInertia",void 0);D([B()],st.prototype,"zoomToMouseLocation",null);D([B()],st.prototype,"zoomOnFactor",void 0);D([Oh()],st.prototype,"targetScreenOffset",void 0);D([B()],st.prototype,"allowUpsideDown",void 0);D([B()],st.prototype,"useInputToRestoreState",void 0);ft("BABYLON.ArcRotateCamera",st);class De extends mt{get range(){return this._range}set range(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)}get intensityMode(){return this._intensityMode}set intensityMode(e){this._intensityMode=e,this._computePhotometricScale()}get radius(){return this._radius}set radius(e){this._radius=e,this._computePhotometricScale()}get shadowEnabled(){return this._shadowEnabled}set shadowEnabled(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())}get includedOnlyMeshes(){return this._includedOnlyMeshes}set includedOnlyMeshes(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)}get excludedMeshes(){return this._excludedMeshes}set excludedMeshes(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)}get excludeWithLayerMask(){return this._excludeWithLayerMask}set excludeWithLayerMask(e){this._excludeWithLayerMask=e,this._resyncMeshes()}get includeOnlyWithLayerMask(){return this._includeOnlyWithLayerMask}set includeOnlyWithLayerMask(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()}get lightmapMode(){return this._lightmapMode}set lightmapMode(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())}getViewMatrix(e){return null}getProjectionMatrix(e,t){return null}constructor(e,t){super(e,t,!1),this.diffuse=new pe(1,1,1),this.specular=new pe(1,1,1),this.falloffType=De.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=De.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 de(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=[],this.excludedMeshes=[],this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,s,n=!0){var l;const r=e.toString();let o=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+r),this._renderId!==t.getRenderId()||this._lastUseSpecular!==s||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=s;const h=this.getScaledIntensity();this.transferToEffect(i,r),this.diffuse.scaleToRef(h,Hs.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",Hs.Color3[0],this.range,r),s&&(this.specular.scaleToRef(h,Hs.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",Hs.Color3[1],this.radius,r)),o=!0}if(this.transferTexturesToEffect(i,r),t.shadowsEnabled&&this.shadowEnabled&&n){const h=(l=this.getShadowGenerator(t.activeCamera))!=null?l:this.getShadowGenerator();h&&(h.bindShadowLight(r,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&&this.includedOnlyMeshes.indexOf(e)===-1||this.excludedMeshes&&this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1||this.includeOnlyWithLayerMask!==0&&!(this.includeOnlyWithLayerMask&e.layerMask)||this.excludeWithLayerMask!==0&&this.excludeWithLayerMask&e.layerMask):!0}dispose(e,t=!1){if(this._shadowGenerators){const i=this._shadowGenerators.values();for(let s=i.next();s.done!==!0;s=i.next())s.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const i=this._parentContainer.lights.indexOf(this);i>-1&&this._parentContainer.lights.splice(i,1),this._parentContainer=null}for(const i of this.getScene().meshes)i._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=De.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=Ae.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=Ae.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)})),Ae.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const s=mt.Construct("Light_Type_"+e,t,i);return s||null}static Parse(e,t){const i=De.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=Ae.Parse(i,e,t);if(e.excludedMeshesIds&&(s._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(s._includedOnlyMeshesIds=e.includedOnlyMeshesIds),e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.falloffType!==void 0&&(s.falloffType=e.falloffType),e.lightmapMode!==void 0&&(s.lightmapMode=e.lightmapMode),e.animations){for(let n=0;n{const n=t.apply(e,s);for(const r of s)r._resyncLightSource(this);return n};const i=e.splice;e.splice=(s,n)=>{const r=i.apply(e,[s,n]);for(const o of r)o._resyncLightSource(this);return r};for(const s of e)s._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...s)=>{const n=t.apply(e,s);return this._resyncMeshes(),n};const i=e.splice;e.splice=(s,n)=>{const r=i.apply(e,[s,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)e.lightSources.indexOf(this)!==-1&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===De.INTENSITYMODE_AUTOMATIC&&(t===De.LIGHTTYPEID_DIRECTIONALLIGHT?i=De.INTENSITYMODE_ILLUMINANCE:i=De.INTENSITYMODE_LUMINOUSINTENSITY),t){case De.LIGHTTYPEID_POINTLIGHT:case De.LIGHTTYPEID_SPOTLIGHT:switch(i){case De.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case De.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case De.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case De.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case De.INTENSITYMODE_ILLUMINANCE:e=1;break;case De.INTENSITYMODE_LUMINANCE:{let s=this.radius;s=Math.max(s,.001),e=2*Math.PI*(1-Math.cos(s));break}}break;case De.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){const e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}De.FALLOFF_DEFAULT=Xe.FALLOFF_DEFAULT;De.FALLOFF_PHYSICAL=Xe.FALLOFF_PHYSICAL;De.FALLOFF_GLTF=Xe.FALLOFF_GLTF;De.FALLOFF_STANDARD=Xe.FALLOFF_STANDARD;De.LIGHTMAP_DEFAULT=Xe.LIGHTMAP_DEFAULT;De.LIGHTMAP_SPECULAR=Xe.LIGHTMAP_SPECULAR;De.LIGHTMAP_SHADOWSONLY=Xe.LIGHTMAP_SHADOWSONLY;De.INTENSITYMODE_AUTOMATIC=Xe.INTENSITYMODE_AUTOMATIC;De.INTENSITYMODE_LUMINOUSPOWER=Xe.INTENSITYMODE_LUMINOUSPOWER;De.INTENSITYMODE_LUMINOUSINTENSITY=Xe.INTENSITYMODE_LUMINOUSINTENSITY;De.INTENSITYMODE_ILLUMINANCE=Xe.INTENSITYMODE_ILLUMINANCE;De.INTENSITYMODE_LUMINANCE=Xe.INTENSITYMODE_LUMINANCE;De.LIGHTTYPEID_POINTLIGHT=Xe.LIGHTTYPEID_POINTLIGHT;De.LIGHTTYPEID_DIRECTIONALLIGHT=Xe.LIGHTTYPEID_DIRECTIONALLIGHT;De.LIGHTTYPEID_SPOTLIGHT=Xe.LIGHTTYPEID_SPOTLIGHT;De.LIGHTTYPEID_HEMISPHERICLIGHT=Xe.LIGHTTYPEID_HEMISPHERICLIGHT;D([ls()],De.prototype,"diffuse",void 0);D([ls()],De.prototype,"specular",void 0);D([B()],De.prototype,"falloffType",void 0);D([B()],De.prototype,"intensity",void 0);D([B()],De.prototype,"range",null);D([B()],De.prototype,"intensityMode",null);D([B()],De.prototype,"radius",null);D([B()],De.prototype,"_renderPriority",void 0);D([qe("_reorderLightsInScene")],De.prototype,"renderPriority",void 0);D([B("shadowEnabled")],De.prototype,"_shadowEnabled",void 0);D([B("excludeWithLayerMask")],De.prototype,"_excludeWithLayerMask",void 0);D([B("includeOnlyWithLayerMask")],De.prototype,"_includeOnlyWithLayerMask",void 0);D([B("lightmapMode")],De.prototype,"_lightmapMode",void 0);class kn extends De{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=O.Identity(),this._projectionMatrix=O.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return this.parent&&this.parent.getWorldMatrix?(this.transformedPosition||(this.transformedPosition=v.Zero()),v.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=v.Zero()),v.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0):!1}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=v.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=v.Cross(this.direction,Wt.Y),t=v.Cross(e,this.direction);return v.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=v.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=O.Identity()),O.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return this.shadowMinZ!==void 0?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return this.shadowMaxZ!==void 0?this.shadowMaxZ:e.maxZ}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=N.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),v.NormalizeToRef(this.getShadowDirection(e),t),Math.abs(v.Dot(t,v.Up()))===1&&(t.z=1e-13);const s=N.Vector3[1];return i.addToRef(t,s),O.LookAtLHToRef(i,s,v.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e!=null?e:this._viewMatrix,t!=null?t:[]),this._projectionMatrix}}D([bi()],kn.prototype,"position",null);D([bi()],kn.prototype,"direction",null);D([B()],kn.prototype,"shadowMinZ",null);D([B()],kn.prototype,"shadowMaxZ",null);mt.AddNodeConstructor("Light_Type_0",(a,e)=>()=>new Or(a,v.Zero(),e));class Or extends kn{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){const t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){const i=this._shadowGenerators.values();for(let s=i.next();s.done!==!0;s=i.next())s.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return De.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new v(1,0,0);case 1:return new v(-1,0,0);case 2:return new v(0,-1,0);case 3:return new v(0,1,0);case 4:return new v(0,0,1);case 5:return new v(0,0,-1)}return v.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;const n=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,r=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;O.PerspectiveFovLHToRef(this.shadowAngle,1,o?r:n,o?n:r,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}D([B()],Or.prototype,"shadowAngle",null);ft("BABYLON.PointLight",Or);class gl{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,s,n){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&t.prePassRenderer.getIndex(2)!==-1){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=s.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]=s.clone()}}}class vo{constructor(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!1,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))e[0]!=="_"&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)this._keys.indexOf(e)===-1&&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 s,n,r,o,l;const t=(r=(n=(s=this._externalProperties)==null?void 0:s[e])==null?void 0:n.type)!=null?r:typeof this[e],i=(l=(o=this._externalProperties)==null?void 0:o[e])==null?void 0:l.default;switch(t){case"number":this[e]=i!=null?i:0;break;case"string":this[e]=i!=null?i:"";break;default:this[e]=i!=null?i:!1;break}}toString(){let e="";for(let t=0;tthis._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 s=0;s0&&(n.computeBonesUsingShaders=!1);continue}if(!(!n.computeBonesUsingShaders||n.numBoneInfluencers===0)){if(n.material.getEffect()===t)n.computeBonesUsingShaders=!1;else if(n.subMeshes){for(const r of n.subMeshes)if(r.effect===t){n.computeBonesUsingShaders=!1;break}}}}}else{const i=this._defines[this._currentRank];if(i)for(let s=0;sthis._handlePluginEvent(s,n),this._plugins.push(e),this._plugins.sort((s,n)=>s.priority-n.priority),this._codeInjectionPoints={};const i={};i[gs._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const s of this._plugins)s.collectDefines(i),this._collectPointNames("vertex",s.getCustomCode("vertex")),this._collectPointNames("fragment",s.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){this._activePlugins.indexOf(e)===-1&&(this._activePlugins.push(e),this._activePlugins.sort((t,i)=>t.priority-i.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((t,i)=>t.priority-i.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&&s.uniforms.push(...this._uniformList),this._samplerList.length>0&&s.samplers.push(...this._samplerList),this._uboList.length>0&&s.uniformBuffersNames.push(...this._uboList),s.customCode=this._injectCustomCode(s,s.customCode);break}case 8:{const s=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const n of this._plugins){const r=n.getUniforms();if(r){if(r.ubo)for(const o of r.ubo){if(o.size&&o.type){const l=(i=o.arraySize)!=null?i:0;s.ubo.addUniform(o.name,o.size,l),this._uboDeclaration+="".concat(o.type," ").concat(o.name).concat(l>0?"[".concat(l,"]"):"",";\n")}this._uniformList.push(o.name)}r.vertex&&(this._vertexDeclaration+=r.vertex+"\n"),r.fragment&&(this._fragmentDeclaration+=r.fragment+"\n")}n.getSamplers(this._samplerList),n.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,s)=>{var o,l;t&&(s=t(i,s)),this._uboDeclaration&&(s=s.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(s=s.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(s=s.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const n=(o=this._codeInjectionPoints)==null?void 0:o[i];if(!n)return s;let r=null;for(let h in n){let c="";for(const u of this._activePlugins){let f=(l=u.getCustomCode(i))==null?void 0:l[h];f&&(u.resolveIncludes&&(r===null&&(r={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:K.GetShadersRepository(0),includesShadersStore:K.GetIncludesShadersStore(0),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}),r.isFragment=i==="fragment",En(f,r,d=>f=d)),c+=f+"\n")}if(c.length>0)if(h.charAt(0)==="!"){h=h.substring(1);let u="g";if(h.charAt(0)==="!")u="",h=h.substring(1);else{const g=Q1.exec(h);g&&g.length>=2&&(u=g[1],h=h.substring(u.length+1))}u.indexOf("g")<0&&(u+="g");const f=s,d=new RegExp(h,u);let p=d.exec(f);for(;p!==null;){let g=c;for(let _=0;_{ev()});const J1=[];let ml=null;function ev(){J1.length=0,q.OnEventObservable.remove(ml),ml=null}class hn{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,s,n=!0,r=!1,o=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=o,e.pluginManager||(e.pluginManager=new gs(e),e.onDisposeObservable.add(()=>{e.pluginManager=void 0})),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,n&&this._pluginManager._addPlugin(this),r&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,s){return!0}hardBindForSubMesh(e,t,i,s){}bindForSubMesh(e,t,i,s){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if(t[0]==="_")continue;const i=typeof this._pluginDefineNames[t];e[t]={type:i==="number"?"number":i==="string"?"string":i==="boolean"?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){Ae.Clone(()=>e,this)}serialize(){return Ae.Serialize(this)}parse(e,t,i){Ae.Parse(()=>this,e,t,i)}}D([B()],hn.prototype,"name",void 0);D([B()],hn.prototype,"priority",void 0);D([B()],hn.prototype,"resolveIncludes",void 0);D([B()],hn.prototype,"registerForExtraEvents",void 0);ft("BABYLON.MaterialPluginBase",hn);class tv extends vo{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class Bs extends hn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new tv,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=q.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&we.DetailTextureEnabled&&!this._texture.isReady()):!0}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&we.DetailTextureEnabled&&this._isEnabled?(ds(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&&we.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),ps(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&we.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&&((t=this._texture)==null||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"}]}}}D([pi("detailTexture"),qe("_markAllSubMeshesAsTexturesDirty")],Bs.prototype,"texture",void 0);D([B()],Bs.prototype,"diffuseBlendLevel",void 0);D([B()],Bs.prototype,"roughnessBlendLevel",void 0);D([B()],Bs.prototype,"bumpLevel",void 0);D([B(),qe("_markAllSubMeshesAsTexturesDirty")],Bs.prototype,"normalBlendMethod",void 0);D([B(),qe("_markAllSubMeshesAsTexturesDirty")],Bs.prototype,"isEnabled",void 0);const ra={effect:null,subMesh:null};class iv extends vo{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.PARALLAX_RHS=!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_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.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.DECAL_AFTER_DETAIL=!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 te extends xo{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),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new pe(0,0,0),this.diffuseColor=new pe(1,1,1),this.specularColor=new pe(1,1,1),this.emissiveColor=new pe(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._applyDecalMapAfterDetailMap=!1,this._renderTargets=new Vt(16),this._worldViewProjectionMatrix=O.Zero(),this._globalAmbientColor=new pe(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new Bs(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new gl,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),te.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),te.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return te.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||te.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled}needAlphaTesting(){return this._forceAlphaTest?!0:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===q.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==q.MATERIAL_OPAQUE}_hasAlphaChannel(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new iv(this._eventInfo.defineNames));const n=this.getScene(),r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();r._needNormals=og(n,e,r,!0,this._maxSimultaneousLights,this._disableLighting),fg(n,r);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(pg(n,r,this.canRenderToMRT&&!l),dg(n,r,l),r._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,r._needUVs=!1;for(let c=1;c<=6;++c)r["MAINUV"+c]=!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&&te.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())ds(this._diffuseTexture,r,"DIFFUSE");else return!1;else r.DIFFUSE=!1;if(this._ambientTexture&&te.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())ds(this._ambientTexture,r,"AMBIENT");else return!1;else r.AMBIENT=!1;if(this._opacityTexture&&te.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())ds(this._opacityTexture,r,"OPACITY"),r.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else r.OPACITY=!1;if(this._reflectionTexture&&te.ReflectionTextureEnabled)if(this._reflectionTexture.isReadyOrNotBlocking()){switch(r._needNormals=!0,r.REFLECTION=!0,r.ROUGHNESS=this._roughness>0,r.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,r.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===ne.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 ne.EXPLICIT_MODE:r.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case ne.PLANAR_MODE:r.setReflectionMode("REFLECTIONMAP_PLANAR");break;case ne.PROJECTION_MODE:r.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case ne.SKYBOX_MODE:r.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case ne.SPHERICAL_MODE:r.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case ne.EQUIRECTANGULAR_MODE:r.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case ne.FIXED_EQUIRECTANGULAR_MODE:r.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case ne.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:r.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case ne.CUBIC_MODE:case ne.INVCUBIC_MODE:default:r.setReflectionMode("REFLECTIONMAP_CUBIC");break}r.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else return!1;else r.REFLECTION=!1,r.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&te.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())ds(this._emissiveTexture,r,"EMISSIVE");else return!1;else r.EMISSIVE=!1;if(this._lightmapTexture&&te.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())ds(this._lightmapTexture,r,"LIGHTMAP"),r.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,r.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else r.LIGHTMAP=!1;if(this._specularTexture&&te.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())ds(this._specularTexture,r,"SPECULAR"),r.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else r.SPECULAR=!1;if(n.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&te.BumpTextureEnabled){if(this._bumpTexture.isReady())ds(this._bumpTexture,r,"BUMP"),r.PARALLAX=this._useParallax,r.PARALLAX_RHS=n.useRightHandedSystem,r.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;r.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else r.BUMP=!1,r.PARALLAX=!1,r.PARALLAX_RHS=!1,r.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&te.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())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 return!1;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=this.alphaMode===7||this.alphaMode===8,r.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,r.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,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=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,r.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}r._areFresnelDirty&&(te.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),ec(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,r,this._applyDecalMapAfterDetailMap),tc(n,o,this,r,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=r,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),ic(e,r,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let h=!1;if(r.isDirty){const c=r._areLightsDisposed;r.markAsProcessed();const u=new bo;r.REFLECTION&&u.addFallback(0,"REFLECTION"),r.SPECULAR&&u.addFallback(0,"SPECULAR"),r.BUMP&&u.addFallback(0,"BUMP"),r.PARALLAX&&u.addFallback(1,"PARALLAX"),r.PARALLAX_RHS&&u.addFallback(1,"PARALLAX_RHS"),r.PARALLAXOCCLUSION&&u.addFallback(0,"PARALLAXOCCLUSION"),r.SPECULAROVERALPHA&&u.addFallback(0,"SPECULAROVERALPHA"),r.FOG&&u.addFallback(1,"FOG"),r.POINTSIZE&&u.addFallback(0,"POINTSIZE"),r.LOGARITHMICDEPTH&&u.addFallback(0,"LOGARITHMICDEPTH"),rg(r,u,this._maxSimultaneousLights),r.SPECULARTERM&&u.addFallback(0,"SPECULARTERM"),r.DIFFUSEFRESNEL&&u.addFallback(1,"DIFFUSEFRESNEL"),r.OPACITYFRESNEL&&u.addFallback(2,"OPACITYFRESNEL"),r.REFLECTIONFRESNEL&&u.addFallback(3,"REFLECTIONFRESNEL"),r.EMISSIVEFRESNEL&&u.addFallback(4,"EMISSIVEFRESNEL"),r.FRESNEL&&u.addFallback(4,"FRESNEL"),r.MULTIVIEW&&u.addFallback(0,"MULTIVIEW");const f=[E.PositionKind];r.NORMAL&&f.push(E.NormalKind),r.TANGENT&&f.push(E.TangentKind);for(let b=1;b<=6;++b)r["UV"+b]&&f.push("uv".concat(b===1?"":b));r.VERTEXCOLOR&&f.push(E.ColorKind),ng(f,e,r,u),Jh(f,r),$h(f,e,r),Zh(f,e,r);let d="default";const p=["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"],g=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],_=["Material","Scene","Mesh"],m={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:r.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=u,this._eventInfo.fallbackRank=0,this._eventInfo.defines=r,this._eventInfo.uniforms=p,this._eventInfo.attributes=f,this._eventInfo.samplers=g,this._eventInfo.uniformBuffersNames=_,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=m,this._callbackPluginEventGeneric(128,this._eventInfo),gl.AddUniforms(p),Ue&&(Ue.PrepareUniforms(p,r),Ue.PrepareSamplers(g,r)),mg({uniformsNames:p,uniformBuffersNames:_,samplers:g,defines:r,maxSimultaneousLights:this._maxSimultaneousLights}),uo(p);const x={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,p,_,g,r,f,x));const I=r.toString(),T=t.effect;let y=n.getEngine().createEffect(d,{attributes:f,uniformsNames:p,uniformBuffersNames:_,samplers:g,defines:I,fallbacks:u,onCompiled:this.onCompiled,onError:this.onError,indexParameters:m,processFinalCode:x.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:r.PREPASS},o);if(this._eventInfo.customCode=void 0,y)if(this._onEffectCreatedObservable&&(ra.effect=y,ra.subMesh=t,this._onEffectCreatedObservable.notifyObservers(ra)),this.allowShaderHotSwapping&&T&&!y.isReady()){if(y=T,r.markAsUnprocessed(),h=this.isFrozen,c)return r._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(y,r,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!h,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var h;const s=this.getScene(),n=i.materialDefines;if(!n)return;const r=i.effect;if(!r)return;this._activeEffect=r,t.getMeshUniformBuffer().bindToEffect(r,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(r,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),n.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(s,r,i,t.visibility);Qh(t,r);const l=this._uniformBuffer;if(o){if(this.bindViewProjection(r),!l.useUbo||!this.isFrozen||!l.isSync||i._drawWrapper._forceRebindOnNextCall){if(te.FresnelEnabled&&n.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 pe(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(l.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),l.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(l.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),l.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(l.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),l.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&te.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),ps(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&te.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),ps(this._ambientTexture,l,"ambient")),this._opacityTexture&&te.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),ps(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&te.ReflectionTextureEnabled&&(l.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),l.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const c=this._reflectionTexture;l.updateVector3("vReflectionPosition",c.boundingBoxPosition),l.updateVector3("vReflectionSize",c.boundingBoxSize)}if(this._emissiveTexture&&te.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),ps(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&te.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),ps(this._lightmapTexture,l,"lightmap")),this._specularTexture&&te.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),ps(this._specularTexture,l,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&te.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),ps(this._bumpTexture,l,"bump"),s._mirroredCameraPosition?l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&te.RefractionTextureEnabled){let c=1;if(this._refractionTexture.isCube||(l.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(c=this._refractionTexture.depth)),l.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,c,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const u=this._refractionTexture;l.updateVector3("vRefractionPosition",u.boundingBoxPosition),l.updateVector3("vRefractionSize",u.boundingBoxSize)}}}this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),n.SPECULARTERM&&l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",te.EmissiveTextureEnabled?this.emissiveColor:pe.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&te.DiffuseTextureEnabled&&r.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&te.AmbientTextureEnabled&&r.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&te.OpacityTextureEnabled&&r.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&te.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?r.setTexture("reflectionCubeSampler",this._reflectionTexture):r.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&te.EmissiveTextureEnabled&&r.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&te.LightmapTextureEnabled&&r.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&te.SpecularTextureEnabled&&r.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&te.BumpTextureEnabled&&r.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&te.RefractionTextureEnabled&&(this._refractionTexture.isCube?r.setTexture("refractionCubeSampler",this._refractionTexture):r.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(r),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),fo(r,this,s),this.bindEyePosition(r)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(s.lightsEnabled&&!this._disableLighting&&sg(s,t,r,n,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==Qe.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||n.PREPASS)&&this.bindView(r),_o(s,t,r),n.NUM_MORPH_INFLUENCERS&&mo(t,r),n.BAKED_VERTEX_ANIMATION_TEXTURE&&((h=t.bakedVertexAnimationManager)==null||h.bind(r,n.INSTANCES)),this.useLogarithmicDepth&&po(n,r,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),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,s,n,r,o,l,h,c,u;t&&((i=this._diffuseTexture)==null||i.dispose(),(s=this._ambientTexture)==null||s.dispose(),(n=this._opacityTexture)==null||n.dispose(),(r=this._reflectionTexture)==null||r.dispose(),(o=this._emissiveTexture)==null||o.dispose(),(l=this._specularTexture)==null||l.dispose(),(h=this._bumpTexture)==null||h.dispose(),(c=this._lightmapTexture)==null||c.dispose(),(u=this._refractionTexture)==null||u.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=Ae.Clone(()=>new te(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return s.name=e,s.id=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}static Parse(e,t,i){const s=Ae.Parse(()=>new te(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),q._ParsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return we.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){we.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return we.DetailTextureEnabled}static set DetailTextureEnabled(e){we.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return we.AmbientTextureEnabled}static set AmbientTextureEnabled(e){we.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return we.OpacityTextureEnabled}static set OpacityTextureEnabled(e){we.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return we.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){we.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return we.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){we.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return we.SpecularTextureEnabled}static set SpecularTextureEnabled(e){we.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return we.BumpTextureEnabled}static set BumpTextureEnabled(e){we.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return we.LightmapTextureEnabled}static set LightmapTextureEnabled(e){we.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return we.RefractionTextureEnabled}static set RefractionTextureEnabled(e){we.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return we.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){we.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return we.FresnelEnabled}static set FresnelEnabled(e){we.FresnelEnabled=e}}D([pi("diffuseTexture")],te.prototype,"_diffuseTexture",void 0);D([qe("_markAllSubMeshesAsTexturesAndMiscDirty")],te.prototype,"diffuseTexture",void 0);D([pi("ambientTexture")],te.prototype,"_ambientTexture",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"ambientTexture",void 0);D([pi("opacityTexture")],te.prototype,"_opacityTexture",void 0);D([qe("_markAllSubMeshesAsTexturesAndMiscDirty")],te.prototype,"opacityTexture",void 0);D([pi("reflectionTexture")],te.prototype,"_reflectionTexture",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"reflectionTexture",void 0);D([pi("emissiveTexture")],te.prototype,"_emissiveTexture",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"emissiveTexture",void 0);D([pi("specularTexture")],te.prototype,"_specularTexture",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"specularTexture",void 0);D([pi("bumpTexture")],te.prototype,"_bumpTexture",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"bumpTexture",void 0);D([pi("lightmapTexture")],te.prototype,"_lightmapTexture",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"lightmapTexture",void 0);D([pi("refractionTexture")],te.prototype,"_refractionTexture",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"refractionTexture",void 0);D([ls("ambient")],te.prototype,"ambientColor",void 0);D([ls("diffuse")],te.prototype,"diffuseColor",void 0);D([ls("specular")],te.prototype,"specularColor",void 0);D([ls("emissive")],te.prototype,"emissiveColor",void 0);D([B()],te.prototype,"specularPower",void 0);D([B("useAlphaFromDiffuseTexture")],te.prototype,"_useAlphaFromDiffuseTexture",void 0);D([qe("_markAllSubMeshesAsTexturesAndMiscDirty")],te.prototype,"useAlphaFromDiffuseTexture",void 0);D([B("useEmissiveAsIllumination")],te.prototype,"_useEmissiveAsIllumination",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useEmissiveAsIllumination",void 0);D([B("linkEmissiveWithDiffuse")],te.prototype,"_linkEmissiveWithDiffuse",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"linkEmissiveWithDiffuse",void 0);D([B("useSpecularOverAlpha")],te.prototype,"_useSpecularOverAlpha",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useSpecularOverAlpha",void 0);D([B("useReflectionOverAlpha")],te.prototype,"_useReflectionOverAlpha",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useReflectionOverAlpha",void 0);D([B("disableLighting")],te.prototype,"_disableLighting",void 0);D([qe("_markAllSubMeshesAsLightsDirty")],te.prototype,"disableLighting",void 0);D([B("useObjectSpaceNormalMap")],te.prototype,"_useObjectSpaceNormalMap",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useObjectSpaceNormalMap",void 0);D([B("useParallax")],te.prototype,"_useParallax",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useParallax",void 0);D([B("useParallaxOcclusion")],te.prototype,"_useParallaxOcclusion",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useParallaxOcclusion",void 0);D([B()],te.prototype,"parallaxScaleBias",void 0);D([B("roughness")],te.prototype,"_roughness",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"roughness",void 0);D([B()],te.prototype,"indexOfRefraction",void 0);D([B()],te.prototype,"invertRefractionY",void 0);D([B()],te.prototype,"alphaCutOff",void 0);D([B("useLightmapAsShadowmap")],te.prototype,"_useLightmapAsShadowmap",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useLightmapAsShadowmap",void 0);D([Ln("diffuseFresnelParameters")],te.prototype,"_diffuseFresnelParameters",void 0);D([qe("_markAllSubMeshesAsFresnelDirty")],te.prototype,"diffuseFresnelParameters",void 0);D([Ln("opacityFresnelParameters")],te.prototype,"_opacityFresnelParameters",void 0);D([qe("_markAllSubMeshesAsFresnelAndMiscDirty")],te.prototype,"opacityFresnelParameters",void 0);D([Ln("reflectionFresnelParameters")],te.prototype,"_reflectionFresnelParameters",void 0);D([qe("_markAllSubMeshesAsFresnelDirty")],te.prototype,"reflectionFresnelParameters",void 0);D([Ln("refractionFresnelParameters")],te.prototype,"_refractionFresnelParameters",void 0);D([qe("_markAllSubMeshesAsFresnelDirty")],te.prototype,"refractionFresnelParameters",void 0);D([Ln("emissiveFresnelParameters")],te.prototype,"_emissiveFresnelParameters",void 0);D([qe("_markAllSubMeshesAsFresnelDirty")],te.prototype,"emissiveFresnelParameters",void 0);D([B("useReflectionFresnelFromSpecular")],te.prototype,"_useReflectionFresnelFromSpecular",void 0);D([qe("_markAllSubMeshesAsFresnelDirty")],te.prototype,"useReflectionFresnelFromSpecular",void 0);D([B("useGlossinessFromSpecularMapAlpha")],te.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"useGlossinessFromSpecularMapAlpha",void 0);D([B("maxSimultaneousLights")],te.prototype,"_maxSimultaneousLights",void 0);D([qe("_markAllSubMeshesAsLightsDirty")],te.prototype,"maxSimultaneousLights",void 0);D([B("invertNormalMapX")],te.prototype,"_invertNormalMapX",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"invertNormalMapX",void 0);D([B("invertNormalMapY")],te.prototype,"_invertNormalMapY",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"invertNormalMapY",void 0);D([B("twoSidedLighting")],te.prototype,"_twoSidedLighting",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],te.prototype,"twoSidedLighting",void 0);D([B("applyDecalMapAfterDetailMap")],te.prototype,"_applyDecalMapAfterDetailMap",void 0);D([qe("_markAllSubMeshesAsMiscDirty")],te.prototype,"applyDecalMapAfterDetailMap",void 0);ft("BABYLON.StandardMaterial",te);Qe.DefaultMaterialFactory=a=>new te("default material",a);var vl;(function(a){a[a.Clean=0]="Clean",a[a.Stop=1]="Stop",a[a.Sync=2]="Sync",a[a.NoSync=3]="NoSync"})(vl||(vl={}));class Be{static get ForceFullSceneLoadingForIncremental(){return Tt.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Tt.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Tt.ShowLoadingScreen}static set ShowLoadingScreen(e){Tt.ShowLoadingScreen=e}static get loggingLevel(){return Tt.loggingLevel}static set loggingLevel(e){Tt.loggingLevel=e}static get CleanBoneMatrixWeights(){return Tt.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Tt.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return Be._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){const t=Be._RegisteredPlugins[e];return t||(U.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"),Be.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in Be._RegisteredPlugins){const i=Be._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Be._RegisteredPlugins[t]}return Be.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");t!==-1&&(e=e.substring(0,t));const i=e.lastIndexOf("."),s=e.substring(i,e.length).toLowerCase();return Be._GetPluginForExtension(s)}static _GetDirectLoad(e){return e.substr(0,5)==="data:"?e.substr(5):null}static _FormatErrorMessage(e,t,i){let n="Unable to load from "+(e.rawData?"binary data":e.url);return t?n+=": ".concat(t):i&&(n+=": ".concat(i)),n}static _LoadData(e,t,i,s,n,r,o,l){var I,T,y,b;const h=Be._GetDirectLoad(e.url);if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const c=o?Be._GetPluginForExtension(o):h?Be._GetPluginForDirectLoad(e.url):Be._GetPluginForFilename(e.url);if(e.rawData&&!c.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";const u=(y=(T=(I=c.plugin).createPlugin)==null?void 0:T.call(I))!=null?y:c.plugin;if(!u)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(Be.OnPluginActivatedObservable.notifyObservers(u),h&&(u.canDirectLoad&&u.canDirectLoad(e.url)||!Qa(e.url))){if(u.directLoad){const S=u.directLoad(t,h);S instanceof Promise?S.then(A=>{i(u,A)}).catch(A=>{n("Error in directLoad of _loadData: "+A,A)}):i(u,S)}else i(u,h);return u}const f=c.isBinary,d=(S,A)=>{if(t.isDisposed){n("Scene has been disposed");return}i(u,S,A)};let p=null,g=!1;(b=u.onDisposeObservable)==null||b.add(()=>{g=!0,p&&(p.abort(),p=null),r()});const _=()=>{if(g)return;const S=(A,M)=>{n(A==null?void 0:A.statusText,M)};if(!u.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";p=u.loadFile?u.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,d,s,f,S,l):t._loadFile(e.file||e.url,d,s,!0,f,S)},m=t.getEngine();let x=m.enableOfflineSupport;if(x){let S=!1;for(const A of t.disableOfflineSupportExceptionRules)if(A.test(e.url)){S=!0;break}x=!S}return x&&ie.OfflineProviderFactory?t.offlineProvider=ie.OfflineProviderFactory(e.url,_,m.disableManifestCheck):_(),u}static _GetFileInfo(e,t){let i,s,n=null,r=null;if(!t)i=e,s=ee.GetFilename(e),e=ee.GetFolderPath(e);else if(t.name){const o=t;i="file:".concat(o.name),s=o.name,n=o}else if(ArrayBuffer.isView(t))i="",s=eo(),r=t;else if(typeof t=="string"&&t.startsWith("data:"))i=t,s="";else{const o=t;if(o.substr(0,1)==="/")return ee.Error("Wrong sceneFilename parameter"),null;i=e+o,s=o}return{url:i,rootUrl:e,name:s,file:n,rawData:r}}static GetPluginForExtension(e){return Be._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!Be._RegisteredPlugins[e]}static RegisterPlugin(e){if(typeof e.extensions=="string"){const t=e.extensions;Be._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach(i=>{Be._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",s=Ce.LastCreatedScene,n=null,r=null,o=null,l=null,h=""){if(!s)return U.Error("No scene available to import mesh to"),null;const c=Be._GetFileInfo(t,i);if(!c)return null;const u={};s.addPendingData(u);const f=()=>{s.removePendingData(u)},d=(_,m)=>{const x=Be._FormatErrorMessage(c,_,m);o?o(s,x,new is(x,Ps.SceneLoaderError,m)):U.Error(x),f()},p=r?_=>{try{r(_)}catch(m){d("Error in onProgress callback: "+m,m)}}:void 0,g=(_,m,x,I,T,y,b,S)=>{if(s.importedMeshesFiles.push(c.url),n)try{n(_,m,x,I,T,y,b,S)}catch(A){d("Error in onSuccess callback: "+A,A)}s.removePendingData(u)};return Be._LoadData(c,s,(_,m,x)=>{if(_.rewriteRootURL&&(c.rootUrl=_.rewriteRootURL(c.rootUrl,x)),_.importMesh){const I=_,T=[],y=[],b=[];if(!I.importMesh(e,s,m,c.rootUrl,T,y,b,d))return;s.loadingPluginName=_.name,g(T,y,b,[],[],[],[],[])}else _.importMeshAsync(e,s,m,c.rootUrl,p,c.name).then(T=>{s.loadingPluginName=_.name,g(T.meshes,T.particleSystems,T.skeletons,T.animationGroups,T.transformNodes,T.geometries,T.lights,T.spriteManagers)}).catch(T=>{d(T.message,T)})},p,d,f,l,h)}static ImportMeshAsync(e,t,i="",s=Ce.LastCreatedScene,n=null,r=null,o=""){return new Promise((l,h)=>{Be.ImportMesh(e,t,i,s,(c,u,f,d,p,g,_,m)=>{l({meshes:c,particleSystems:u,skeletons:f,animationGroups:d,transformNodes:p,geometries:g,lights:_,spriteManagers:m})},n,(c,u,f)=>{h(f||new Error(u))},r,o)})}static Load(e,t="",i=Ce.LastCreatedEngine,s=null,n=null,r=null,o=null,l=""){return i?Be.Append(e,t,new Qe(i),s,n,r,o,l):(ee.Error("No engine available"),null)}static LoadAsync(e,t="",i=Ce.LastCreatedEngine,s=null,n=null,r=""){return new Promise((o,l)=>{Be.Load(e,t,i,h=>{o(h)},s,(h,c,u)=>{l(u||new Error(c))},n,r)})}static Append(e,t="",i=Ce.LastCreatedScene,s=null,n=null,r=null,o=null,l=""){if(!i)return U.Error("No scene available to append to"),null;const h=Be._GetFileInfo(e,t);if(!h)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)};Be.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));const f=(g,_)=>{const m=Be._FormatErrorMessage(h,g,_);r?r(i,m,new is(m,Ps.SceneLoaderError,_)):U.Error(m),u()},d=n?g=>{try{n(g)}catch(_){f("Error in onProgress callback",_)}}:void 0,p=()=>{if(s)try{s(i)}catch(g){f("Error in onSuccess callback",g)}i.removePendingData(c)};return Be._LoadData(h,i,(g,_)=>{if(g.load){if(!g.load(i,_,h.rootUrl,f))return;i.loadingPluginName=g.name,p()}else g.loadAsync(i,_,h.rootUrl,d,h.name).then(()=>{i.loadingPluginName=g.name,p()}).catch(x=>{f(x.message,x)})},d,f,u,o,l)}static AppendAsync(e,t="",i=Ce.LastCreatedScene,s=null,n=null,r=""){return new Promise((o,l)=>{Be.Append(e,t,i,h=>{o(h)},s,(h,c,u)=>{l(u||new Error(c))},n,r)})}static LoadAssetContainer(e,t="",i=Ce.LastCreatedScene,s=null,n=null,r=null,o=null,l=""){if(!i)return U.Error("No scene available to load asset container to"),null;const h=Be._GetFileInfo(e,t);if(!h)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)},f=(g,_)=>{const m=Be._FormatErrorMessage(h,g,_);r?r(i,m,new is(m,Ps.SceneLoaderError,_)):U.Error(m),u()},d=n?g=>{try{n(g)}catch(_){f("Error in onProgress callback",_)}}:void 0,p=g=>{if(s)try{s(g)}catch(_){f("Error in onSuccess callback",_)}i.removePendingData(c)};return Be._LoadData(h,i,(g,_)=>{if(g.loadAssetContainer){const x=g.loadAssetContainer(i,_,h.rootUrl,f);if(!x)return;x.populateRootNodes(),i.loadingPluginName=g.name,p(x)}else g.loadAssetContainerAsync?g.loadAssetContainerAsync(i,_,h.rootUrl,d,h.name).then(x=>{x.populateRootNodes(),i.loadingPluginName=g.name,p(x)}).catch(x=>{f(x.message,x)}):f("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},d,f,u,o,l)}static LoadAssetContainerAsync(e,t="",i=Ce.LastCreatedScene,s=null,n=null){return new Promise((r,o)=>{Be.LoadAssetContainer(e,t,i,l=>{r(l)},s,(l,h,c)=>{o(c||new Error(h))},n)})}static ImportAnimations(e,t="",i=Ce.LastCreatedScene,s=!0,n=0,r=null,o=null,l=null,h=null,c=null){if(!i){U.Error("No scene available to load animations to");return}if(s){for(const p of i.animatables)p.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(p=>{p.dispose()}),i.getNodes().forEach(p=>{p.animations&&(p.animations=[])})}else switch(n){case 0:i.animationGroups.slice().forEach(d=>{d.dispose()});break;case 1:i.animationGroups.forEach(d=>{d.stop()});break;case 2:i.animationGroups.forEach(d=>{d.reset(),d.restart()});break;case 3:break;default:U.Error("Unknown animation group loading mode value '"+n+"'");return}const u=i.animatables.length,f=d=>{d.mergeAnimationsTo(i,i.animatables.slice(u),r),d.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)};this.LoadAssetContainer(e,t,i,f,l,h,c)}static ImportAnimationsAsync(e,t="",i=Ce.LastCreatedScene,s=!0,n=0,r=null,o=null,l=null,h=null,c=null){return new Promise((u,f)=>{Be.ImportAnimations(e,t,i,s,n,r,d=>{u(d)},l,(d,p,g)=>{f(g||new Error(p))},c)})}}Be.NO_LOGGING=0;Be.MINIMAL_LOGGING=1;Be.SUMMARY_LOGGING=2;Be.DETAILED_LOGGING=3;Be.OnPluginActivatedObservable=new Q;Be._RegisteredPlugins={};Be._ShowingLoadingScreen=!1;const sv="fxaaPixelShader",nv="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)\n{lumaN=lumaW;}\nif (!horzSpan) \n{lumaS=lumaE;}\nif (horzSpan) \n{lengthSign=texelSize.y;}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN)\n{lengthSign=-lengthSign;}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) \n{posB.x+=lengthSign*0.5;}\nif (horzSpan)\n{posB.y+=lengthSign*0.5;}\nvec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) \n{lumaNN=lumaSS;}\nfloat gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) \n{posN.x-=offNP.x*3.0;}\nif (!doneN) \n{posN.y-=offNP.y*3.0;}\nbool doneNP=(!doneN) || (!doneP);if (!doneP) \n{posP.x+=offNP.x*3.0;}\nif (!doneP)\n{posP.y+=offNP.y*3.0;}\nif (doneNP)\n{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;}\nfloat dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)\n{dstN=posM.y-posN.y;}\nif (!horzSpan) \n{dstP=posP.y-posM.y;}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{const c=this.texelSize;h.setFloat2("texelSize",c.x,c.y)})}_getDefines(){const e=this.getEngine();return e&&e.extractDriverInfo().toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,s){return Ae.Parse(()=>new Lr(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}ft("BABYLON.FxaaPostProcess",Lr);let us=null;function Br(a,e,t,i,s="image/png",n=!1,r){const{height:o,width:l}=oc(a,e,t);if(!(o&&l)){U.Error("Invalid 'size' parameter !");return}us||(us=document.createElement("canvas")),us.width=l,us.height=o;const h=us.getContext("2d"),c=a.getRenderWidth()/a.getRenderHeight();let u=l,f=u/c;f>o&&(f=o,u=f*c);const d=Math.max(0,l-u)/2,p=Math.max(0,o-f)/2;e.getScene().activeCamera!==e?Nr(a,e,t,_=>{if(n){const m=new Blob([_]);ee.DownloadBlob(m),i&&i("")}else i&&i(_)},s,1,a.getCreationOptions().antialias,void 0,void 0,void 0,void 0,r):a.onEndFrameObservable.addOnce(()=>{const _=a.getRenderingCanvas();h&&_&&h.drawImage(_,d,p,u,f),us&&(n?(ee.EncodeScreenshotCanvasData(us,void 0,s,void 0,r),i&&i("")):ee.EncodeScreenshotCanvasData(us,i,s,void 0,r))})}function rc(a,e,t,i="image/png",s){return new Promise((n,r)=>{Br(a,e,t,o=>{typeof o<"u"?n(o):r(new Error("Data is undefined"))},i,void 0,s)})}function ov(a,e,t,i,s="image/png",n){return new Promise(r=>{Br(a,e,{width:t,height:i},()=>{r()},s,!0,n)})}function Nr(a,e,t,i,s="image/png",n=1,r=!1,o,l=!1,h=!1,c=!0,u,f){const{height:d,width:p,finalWidth:g,finalHeight:_}=oc(a,e,t),m={width:p,height:d};if(!(d&&p)){U.Error("Invalid 'size' parameter !");return}const x={width:a.getRenderWidth(),height:a.getRenderHeight()};a.setSize(p,d);const I=e.getScene(),T=new wi("screenShot",m,I,!1,!1,0,!1,ne.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,n);T.renderList=I.meshes.slice(),T.samples=n,T.renderSprites=l,T.activeCamera=e,T.forceLayerMaskCheck=c,f==null||f(T);const y=()=>{T.isReadyForRendering()&&e.isReady(!0)?(a.onEndFrameObservable.addOnce(()=>{g===p&&_===d?T.readPixels(void 0,void 0,void 0,!1).then(S=>{Ot.DumpData(p,d,S,i,s,o,!0,void 0,u),T.dispose()}):h_("pass",T.getInternalTexture(),I,void 0,void 0,void 0,g,_).then(S=>{a._readTexturePixels(S,g,_,-1,0,null,!0,!1,0,0).then(A=>{Ot.DumpData(g,_,A,i,s,o,!0,void 0,u),S.dispose()})})}),T.render(!0),I.incrementRenderId(),I.resetCachedMaterial(),a.setSize(x.width,x.height),e.getProjectionMatrix(!0),I.render()):setTimeout(y,16)},b=()=>{I.incrementRenderId(),I.resetCachedMaterial(),y()};if(r){const S=new Lr("antialiasing",1,I.activeCamera);T.addPostProcess(S),S.getEffect().isReady()?b():S.getEffect().onCompiled=()=>{b()}}else b()}function ac(a,e,t,i="image/png",s=1,n=!1,r,o=!1,l=!1,h=!0,c){return new Promise((u,f)=>{Nr(a,e,t,d=>{typeof d<"u"?u(d):f(new Error("Data is undefined"))},i,s,n,r,o,l,h,c)})}function oc(a,e,t){let i=0,s=0,n=0,r=0;if(typeof t=="object"){const o=t.precision?Math.abs(t.precision):1;t.width&&t.height?(i=t.height*o,s=t.width*o):t.width&&!t.height?(s=t.width*o,i=Math.round(s/a.getAspectRatio(e))):t.height&&!t.width?(i=t.height*o,s=Math.round(i*a.getAspectRatio(e))):(s=Math.round(a.getRenderWidth()*o),i=Math.round(s/a.getAspectRatio(e))),t.finalWidth&&t.finalHeight?(r=t.finalHeight,n=t.finalWidth):t.finalWidth&&!t.finalHeight?(n=t.finalWidth,r=Math.round(n/a.getAspectRatio(e))):t.finalHeight&&!t.finalWidth?(r=t.finalHeight,n=Math.round(r*a.getAspectRatio(e))):(n=s,r=i)}else isNaN(t)||(i=t,s=t,n=t,r=t);return s&&(s=Math.floor(s)),i&&(i=Math.floor(i)),n&&(n=Math.floor(n)),r&&(r=Math.floor(r)),{height:i|0,width:s|0,finalWidth:n|0,finalHeight:r|0}}const lv={CreateScreenshot:Br,CreateScreenshotAsync:rc,CreateScreenshotWithResizeAsync:ov,CreateScreenshotUsingRenderTarget:Nr,CreateScreenshotUsingRenderTargetAsync:ac},hv=()=>{ee.CreateScreenshot=Br,ee.CreateScreenshotAsync=rc,ee.CreateScreenshotUsingRenderTarget=Nr,ee.CreateScreenshotUsingRenderTargetAsync=ac};hv();F._instancedMeshFactory=(a,e)=>{const t=new Ur(a,e);if(e.instancedBuffers){t.instancedBuffers={};for(const i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};class Ur extends et{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 i of t.getAnimationRanges())i!=null&&this.createAnimationRange(i.name,i.from,i.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){var t;((t=this._sourceMesh)==null?void 0:t.receiveShadows)!==e&&ee.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;((t=this._sourceMesh)==null?void 0:t.material)!==e&&ee.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;((t=this._sourceMesh)==null?void 0:t.visibility)!==e&&ee.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;((t=this._sourceMesh)==null?void 0:t.skeleton)!==e&&ee.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){!this._sourceMesh||e===this._sourceMesh.renderingGroupId||U.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}copyVerticesData(e,t){this._sourceMesh.copyVerticesData(e,t)}setVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,s),this.sourceMesh}updateVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,s),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i;typeof e=="object"?i=e:i={applySkeleton:e,applyMorph:t};const s=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getData(i,null,E.PositionKind),s),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||U.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!==Ie.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new O);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,N.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(N.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||t.length===0)this._currentLOD=this.sourceMesh;else{const i=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,i.boundingSphere)}return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e(s.toArray(i,i.length),i),[]),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((i,s)=>(s.toArray(i,i.length),i),[]),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((i,s)=>(s.toArray(i,i.length),i),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(t.length*16);for(let s=0;sn===e||n.startsWith(i));return s>=0&&this.options.defines.splice(s,1),(typeof t!="boolean"||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var y,b,S;const s=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const A=s?i._drawWrapper:this._drawWrapper;if(A.effect&&A._wasPreviouslyReady&&A._wasPreviouslyUsingInstances===t)return!0}const n=this.getScene(),r=n.getEngine(),o=[],l=[],h=new bo;let c=this._shaderPath,u=this._options.uniforms,f=this._options.uniformBuffers,d=this._options.samplers;r.getCaps().multiview&&n.activeCamera&&n.activeCamera.outputRenderTarget&&n.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),u.indexOf("viewProjection")!==-1&&u.indexOf("viewProjectionR")===-1&&u.push("viewProjectionR"));for(let A=0;A4&&(l.push(E.MatricesIndicesExtraKind),l.push(E.MatricesWeightsExtraKind));const A=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),h.addCPUSkinningFallback(0,e),A.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),u.indexOf("boneTextureWidth")===-1&&u.push("boneTextureWidth"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(A.bones.length+1)),u.indexOf("mBones")===-1&&u.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let p=0;const g=e?e.morphTargetManager:null;if(g){const A=g.supportsUVs&&o.indexOf("#define UV1")!==-1,M=g.supportsTangents&&o.indexOf("#define TANGENT")!==-1,C=g.supportsNormals&&o.indexOf("#define NORMAL")!==-1;p=g.numMaxInfluencers||g.numInfluencers,A&&o.push("#define MORPHTARGETS_UV"),M&&o.push("#define MORPHTARGETS_TANGENT"),C&&o.push("#define MORPHTARGETS_NORMAL"),p>0&&o.push("#define MORPHTARGETS"),g.isUsingTextureForTargets&&(o.push("#define MORPHTARGETS_TEXTURE"),u.indexOf("morphTargetTextureIndices")===-1&&u.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),o.push("#define NUM_MORPH_INFLUENCERS "+p);for(let w=0;w0&&(u=u.slice(),u.push("morphTargetInfluences"),u.push("morphTargetCount"),u.push("morphTargetTextureInfo"),u.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const A=e.bakedVertexAnimationManager;A&&A.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),u.indexOf("bakedVertexAnimationSettings")===-1&&u.push("bakedVertexAnimationSettings"),u.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&u.push("bakedVertexAnimationTextureSizeInverted"),u.indexOf("bakedVertexAnimationTime")===-1&&u.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture")),Zh(l,e,o)}for(const A in this._textures)if(!this._textures[A].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(uo(u),qh(this,n,o)),n.fogEnabled&&(e!=null&&e.applyFog)&&n.fogMode!==Qe.FOGMODE_NONE&&(o.push("#define FOG"),u.indexOf("view")===-1&&u.push("view"),u.indexOf("vFogInfos")===-1&&u.push("vFogInfos"),u.indexOf("vFogColor")===-1&&u.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),u.indexOf("logarithmicDepthConstant")===-1&&u.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(u=u.slice(),f=f.slice(),d=d.slice(),c=this.customShaderNameResolve(this.name,u,f,d,o,l));const _=s?i._getDrawWrapper(void 0,!0):this._drawWrapper,m=(y=_==null?void 0:_.effect)!=null?y:null,x=(b=_==null?void 0:_.defines)!=null?b:null,I=o.join("\n");let T=m;return x!==I&&(T=r.createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:f,samplers:d,defines:I,fallbacks:h,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:p},shaderLanguage:this._options.shaderLanguage},r),s?i.setEffect(T,I,this._materialContext):_&&_.setEffect(T,I),this._onEffectCreatedObservable&&(aa.effect=T,aa.subMesh=(S=i!=null?i:e==null?void 0:e.subMeshes[0])!=null?S:null,this._onEffectCreatedObservable.notifyObservers(aa))),_._wasPreviouslyUsingInstances=!!t,T!=null&&T.isReady()?(m!==T&&n.resetCachedMaterial(),_._wasPreviouslyReady=!0,!0):!1}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=t!=null?t:this.getEffect();s&&(this._options.uniforms.indexOf("world")!==-1&&s.setMatrix("world",e),this._options.uniforms.indexOf("worldView")!==-1&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),s.setMatrix("worldView",this._cachedWorldViewMatrix)),this._options.uniforms.indexOf("worldViewProjection")!==-1&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),s.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),this._options.uniforms.indexOf("view")!==-1&&s.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){var s;this.bind(e,t,(s=i._drawWrapperOverride)==null?void 0:s.effect,i)}bind(e,t,i,s){var u;const n=s&&this._storeEffectOnSubMeshes,r=i!=null?i:n?s.effect:this.getEffect();if(!r)return;const o=this.getScene();this._activeEffect=r,this.bindOnlyWorldMatrix(e,i);const l=this._options.uniformBuffers;let h=!1;if(r&&l&&l.length>0&&o.getEngine().supportsUniformBuffers)for(let f=0;f0&&mo(t,r);const d=t.bakedVertexAnimationManager;if(d&&d.isEnabled){const p=n?s._drawWrapper:this._drawWrapper;(u=t.bakedVertexAnimationManager)==null||u.bind(r,!!p._wasPreviouslyUsingInstances)}}this._afterBind(t,r,s)}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 s=0;snew rs(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);t.name=e,t.id=e,typeof t._shaderPath=="object"&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach(i=>{const s=this._options[i];Array.isArray(s)&&(this._options[i]=s.slice(0))}),this.stencil.copyTo(t.stencil);for(const i in this._textures)t.setTexture(i,this._textures[i]);for(const i in this._textureArrays)t.setTextureArray(i,this._textureArrays[i]);for(const i in this._externalTextures)t.setExternalTexture(i,this._externalTextures[i]);for(const i in this._ints)t.setInt(i,this._ints[i]);for(const i in this._uints)t.setUInt(i,this._uints[i]);for(const i in this._floats)t.setFloat(i,this._floats[i]);for(const i in this._floatsArrays)t.setFloats(i,this._floatsArrays[i]);for(const i in this._colors3)t.setColor3(i,this._colors3[i]);for(const i in this._colors3Arrays)t._colors3Arrays[i]=this._colors3Arrays[i];for(const i in this._colors4)t.setColor4(i,this._colors4[i]);for(const i in this._colors4Arrays)t._colors4Arrays[i]=this._colors4Arrays[i];for(const i in this._vectors2)t.setVector2(i,this._vectors2[i]);for(const i in this._vectors3)t.setVector3(i,this._vectors3[i]);for(const i in this._vectors4)t.setVector4(i,this._vectors4[i]);for(const i in this._quaternions)t.setQuaternion(i,this._quaternions[i]);for(const i in this._quaternionsArrays)t._quaternionsArrays[i]=this._quaternionsArrays[i];for(const i in this._matrices)t.setMatrix(i,this._matrices[i]);for(const i in this._matrixArrays)t._matrixArrays[i]=this._matrixArrays[i].slice();for(const i in this._matrices3x3)t.setMatrix3x3(i,this._matrices3x3[i]);for(const i in this._matrices2x2)t.setMatrix2x2(i,this._matrices2x2[i]);for(const i in this._vectors2Arrays)t.setArray2(i,this._vectors2Arrays[i]);for(const i in this._vectors3Arrays)t.setArray3(i,this._vectors3Arrays[i]);for(const i in this._vectors4Arrays)t.setArray4(i,this._vectors4Arrays[i]);for(const i in this._uniformBuffers)t.setUniformBuffer(i,this._uniformBuffers[i]);for(const i in this._textureSamplers)t.setTextureSampler(i,this._textureSamplers[i]);for(const i in this._storageBuffers)t.setStorageBuffer(i,this._storageBuffers[i]);return t}dispose(e,t,i){if(t){let s;for(s in this._textures)this._textures[s].dispose();for(s in this._textureArrays){const n=this._textureArrays[s];for(let r=0;rnew rs(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);let n;e.stencil&&s.stencil.parse(e.stencil,t,i);for(n in e.textures)s.setTexture(n,ne.Parse(e.textures[n],t,i));for(n in e.textureArrays){const r=e.textureArrays[n],o=[];for(let l=0;l(h%3===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>pe.FromArray(o));s.setColor3Array(n,r)}for(n in e.colors4)s.setColor4(n,X.FromArray(e.colors4[n]));for(n in e.colors4Arrays){const r=e.colors4Arrays[n].reduce((o,l,h)=>(h%4===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>X.FromArray(o));s.setColor4Array(n,r)}for(n in e.vectors2)s.setVector2(n,fe.FromArray(e.vectors2[n]));for(n in e.vectors3)s.setVector3(n,v.FromArray(e.vectors3[n]));for(n in e.vectors4)s.setVector4(n,Pe.FromArray(e.vectors4[n]));for(n in e.quaternions)s.setQuaternion(n,le.FromArray(e.quaternions[n]));for(n in e.matrices)s.setMatrix(n,O.FromArray(e.matrices[n]));for(n in e.matrixArray)s._matrixArrays[n]=new Float32Array(e.matrixArray[n]);for(n in e.matrices3x3)s.setMatrix3x3(n,e.matrices3x3[n]);for(n in e.matrices2x2)s.setMatrix2x2(n,e.matrices2x2[n]);for(n in e.vectors2Arrays)s.setArray2(n,e.vectors2Arrays[n]);for(n in e.vectors3Arrays)s.setArray3(n,e.vectors3Arrays[n]);for(n in e.vectors4Arrays)s.setArray4(n,e.vectors4Arrays[n]);for(n in e.quaternionsArrays)s.setArray4(n,e.quaternionsArrays[n]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise((n,r)=>{const o=new Ft;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const l=JSON.parse(o.responseText),h=this.Parse(l,i||Ce.LastCreatedScene,s);e&&(h.name=e),n(h)}else r("Unable to load the ShaderMaterial")}),o.open("GET",t),o.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((s,n)=>{const r=new Ft;r.addEventListener("readystatechange",()=>{if(r.readyState==4)if(r.status==200){const o=JSON.parse(JSON.parse(r.responseText).jsonPayload),l=JSON.parse(o.shaderMaterial),h=this.Parse(l,t||Ce.LastCreatedScene,i);h.snippetId=e,s(h)}else n("Unable to load the snippet "+e)}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}}rs.SnippetUrl="https://snippet.babylonjs.com";rs.CreateFromSnippetAsync=rs.ParseFromSnippetAsync;ft("BABYLON.ShaderMaterial",rs);const cv="colorPixelShader",uv="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include\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#include(color,gl_FragColor)\n#define CUSTOM_FRAGMENT_MAIN_END\n}";K.ShadersStore[cv]=uv;const fv="colorVertexShader",dv="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\n#ifdef FOG\nuniform mat4 view;\n#endif\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) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";K.ShadersStore[fv]=dv;F._LinesMeshParser=(a,e)=>xs.Parse(a,e);class xs extends F{_isShaderMaterial(e){return e.getClassName()==="ShaderMaterial"}constructor(e,t=null,i=null,s=null,n,r,o,l){super(e,t,i,s,n),this.useVertexColor=r,this.useVertexAlpha=o,this.color=new pe(1,1,1),this.alpha=1,s&&(this.color=s.color.clone(),this.alpha=s.alpha,this.useVertexColor=s.useVertexColor,this.useVertexAlpha=s.useVertexAlpha),this.intersectionThreshold=.1;const h=[],c={attributes:[E.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:h,useClipPlane:null};o===!1?c.needAlphaBlending=!1:c.defines.push("#define VERTEXALPHA"),r?(c.defines.push("#define VERTEXCOLOR"),c.attributes.push(E.ColorKind)):(c.uniforms.push("color"),this._color4=new X),l?this.material=l:(this.material=new rs("colorShader",this.getScene(),"color",c,!1),this.material.doNotSerialize=!0)}isReady(){return this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)?super.isReady():!1}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=q.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.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r:s,g:n,b:r}=this.color;this._color4.set(s,n,r,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 s=this.getScene().getEngine();return this._unIndexed?s.drawArraysType(q.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(q.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 xs(e,this.getScene(),t,this,i)}createInstance(e){const t=new lc(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const i in this.instancedBuffers)t.instancedBuffers[i]=this.instancedBuffers[i]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new xs(e.name,t);return i.color=pe.FromArray(e.color),i.alpha=e.alpha,i}}class lc extends Ur{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}const pv="linePixelShader",_v="#include\nuniform vec4 color;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";K.ShadersStore[pv]=_v;const gv="lineVertexDeclaration",mv="uniform mat4 viewProjection;\n#define ADDITIONAL_VERTEX_DECLARATION\n";K.IncludesShadersStore[gv]=mv;const vv="lineUboDeclaration",xv="layout(std140,column_major) uniform;\n#include\n#include\n";K.IncludesShadersStore[vv]=xv;const bv="lineVertexShader",yv="#include<__decl__lineVertex>\n#include\n#include\nattribute vec3 position;attribute vec4 normal;uniform float width;uniform float aspectRatio;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nmat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";K.ShadersStore[bv]=yv;et.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this};et.prototype.enableEdgesRendering=function(a=.95,e=!1,t){return this.disableEdgesRendering(),this._edgesRenderer=new kr(this,a,e,!0,t),this};Object.defineProperty(et.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0});xs.prototype.enableEdgesRendering=function(a=.95,e=!1){return this.disableEdgesRendering(),this._edgesRenderer=new Sv(this,a,e),this};lc.prototype.enableEdgesRendering=function(a=.95,e=!1){return xs.prototype.enableEdgesRendering.apply(this,arguments),this};class Tv{constructor(){this.edges=[],this.edgesConnectedCount=0}}class kr{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){const t=new rs("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"],uniformBuffers:["Scene","Mesh"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,s=!0,n){var r;this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new Vt(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=n!=null?n:null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new ln(e.getEngine())),this._prepareRessources(),s&&((r=n==null?void 0:n.useAlternateEdgeFinder)==null||r?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add(()=>{this._rebuild()}),this._meshDisposeObserver=this._source.onDisposeObservable.add(()=>{this.dispose()})}_prepareRessources(){this._lineShader||(this._lineShader=kr._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[E.PositionKind];e&&e._rebuild(),e=this._buffers[E.NormalKind],e&&e._rebuild();const i=this._source.getScene().getEngine();this._ib=i.createIndexBuffer(this._linesIndices)}dispose(){var t;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let e=this._buffers[E.PositionKind];e&&(e.dispose(),this._buffers[E.PositionKind]=null),e=this._buffers[E.NormalKind],e&&(e.dispose(),this._buffers[E.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),(t=this._drawWrapper)==null||t.dispose()}_processEdgeForAdjacencies(e,t,i,s,n){return e===i&&t===s||e===s&&t===i?0:e===s&&t===n||e===n&&t===s?1:e===n&&t===i||e===i&&t===n?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,s,n){return e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(s,1e-10)||e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(i,1e-10)?0:e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(n,1e-10)||e.equalsWithEpsilon(n,1e-10)&&t.equalsWithEpsilon(s,1e-10)?1:e.equalsWithEpsilon(n,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(n,1e-10)?2:-1}_checkEdge(e,t,i,s,n){let r;t===void 0?r=!0:r=v.Dot(i[e],i[t]){C>=0&&M.push(C);for(let w=0;w=e[0].length&&e[1].length>=e[2].length?r=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(r=2);for(let A=0;A<3;++A)A===r?e[A].sort((M,C)=>M[1]C[1]?1:0):e[A].sort((M,C)=>M[1]>C[1]?-1:M[1]=r+1;--A)n(e[A%3],l,A!==r+2?s[i[t+(A+1)%3]]:-1);const c=l.length,u=0,f=0;i.push(s[i[t+r]],o[0],l[0]),i.push(s[i[t+(r+1)%3]],l[c-1],o[h-1]);const d=h<=c,p=d?h:c,g=d?c:h,_=d?h-1:c-1,m=d?0:1;let x=h+c-2,I=d?u:f,T=d?f:u;const y=d?o:l,b=d?l:o;let S=0;for(;x-- >0;){m?i.push(y[I],b[T]):i.push(b[T],y[I]),S+=p;let A;S>=g&&I<_?(A=y[++I],S-=g):A=b[++T],i.push(A)}i[t+0]=i[i.length-3],i[t+1]=i[i.length-2],i[t+2]=i[i.length-1],i.length=i.length-3}_generateEdgesLinesAlternate(){var h,c,u,f,d,p,g,_,m,x;const e=this._source.getVerticesData(E.PositionKind);let t=this._source.getIndices();if(!t||!e)return;Array.isArray(t)||(t=Array.from(t));const i=(c=(h=this._options)==null?void 0:h.useFastVertexMerger)!=null?c:!0,s=i?Math.round(-Math.log((f=(u=this._options)==null?void 0:u.epsilonVertexMerge)!=null?f:1e-6)/Math.log(10)):(p=(d=this._options)==null?void 0:d.epsilonVertexMerge)!=null?p:1e-6,n=[],r=[];if(i){const I={};for(let T=0;TS){const w=b;b=S,S=w}const M=b+"_"+S,C=o[M];C?C.done||(v.Dot(T,C.normal)0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera){this._lineShader._setDrawWrapper(t);return}const i=this._source.hasInstances&&this.customInstances.length>0,s=i||this._source.hasThinInstances;let n=0;if(s)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){const o=this._source._instanceDataStorage;if(n=this.customInstances.length,!o.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!o.isFrozen){let l=0;for(let h=0;h=0?c.substring(0,u):c;f=f.toLowerCase();const d=u>=0?c.substring(u+1).trim():"";if(f==="newmtl")l&&this.materials.push(l),e._blockEntityCollection=!!s,l=new te(d,e),l._parentContainer=s,e._blockEntityCollection=!1;else if(f==="kd"&&l)o=d.split(r,3).map(parseFloat),l.diffuseColor=pe.FromArray(o);else if(f==="ka"&&l)o=d.split(r,3).map(parseFloat),l.ambientColor=pe.FromArray(o);else if(f==="ks"&&l)o=d.split(r,3).map(parseFloat),l.specularColor=pe.FromArray(o);else if(f==="ke"&&l)o=d.split(r,3).map(parseFloat),l.emissiveColor=pe.FromArray(o);else if(f==="ns"&&l)l.specularPower=parseFloat(d);else if(f==="d"&&l)l.alpha=parseFloat(d);else if(f==="map_ka"&&l)l.ambientTexture=Ri._GetTexture(i,d,e);else if(f==="map_kd"&&l)l.diffuseTexture=Ri._GetTexture(i,d,e);else if(f==="map_ks"&&l)l.specularTexture=Ri._GetTexture(i,d,e);else if(f!=="map_ns")if(f==="map_bump"&&l){const p=d.split(r),g=p.indexOf("-bm");let _=null;g>=0&&(_=p[g+1],p.splice(g,2)),l.bumpTexture=Ri._GetTexture(i,p.join(" "),e),l.bumpTexture&&_!==null&&(l.bumpTexture.level=parseFloat(_))}else f==="map_d"&&l&&(l.opacityTexture=Ri._GetTexture(i,d,e))}l&&this.materials.push(l)}static _GetTexture(e,t,i){if(!t)return null;let s=e;if(e==="file:"){let n=t.lastIndexOf("\\");n===-1&&(n=t.lastIndexOf("/")),n>-1?s+=t.substr(n+1):s+=t}else s+=t;return new ne(s,i,!1,Ri.INVERT_TEXTURE_Y)}}Ri.INVERT_TEXTURE_Y=!0;class Ze{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj="",this._objMeshName="",this._increment=1,this._isFirstMaterial=!0,this._grayColor=new X(.5,.5,.5,1),this._hasLineData=!1,this._materialToUse=e,this._babylonMeshesArray=t,this._loadingOptions=i}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});const i=e[t[0]].normals.indexOf(t[1]);return i===-1?-1:e[t[0]].idx[i]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});const i=e[t[0]].normals.indexOf(t[1]);return i!=1&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e,t,i,s,n,r,o){let l;this._loadingOptions.optimizeWithUV?l=this._isInArrayUV(this._tuplePosNorm,[e,i,t]):l=this._isInArray(this._tuplePosNorm,[e,i]),l===-1?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(s),this._wrappedUvsForBabylon.push(n),this._wrappedNormalsForBabylon.push(r),o!==void 0&&this._wrappedColorsForBabylon.push(o),this._tuplePosNorm[e].normals.push(i),this._tuplePosNorm[e].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e].uv.push(t)):this._indicesForBabylon.push(l)}_unwrapData(){for(let e=0;e0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice(),this._handledMesh.uvs=this._unwrappedUVForBabylon.slice(),this._handledMesh.hasLines=this._hasLineData,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0,this._hasLineData=!1)}_optimizeNormals(e){const t=e.getVerticesData(E.PositionKind),i=e.getVerticesData(E.NormalKind),s={};if(!t||!i)return;for(let r=0;rthis._triangles.push(h[0],h[c],h[c+1]),this._handednessSign=1):i.useRightHandedSystem?(this._pushTriangle=(h,c)=>this._triangles.push(h[0],h[c+1],h[c]),this._handednessSign=1):(this._pushTriangle=(h,c)=>this._triangles.push(h[0],h[c],h[c+1]),this._handednessSign=-1);const r=t.split("\n");for(let h=0;h=7){const f=parseFloat(u[4]),d=parseFloat(u[5]),p=parseFloat(u[6]);this._colors.push(new X(f>1?f/255:f,d>1?d/255:d,p>1?p/255:p,u.length===7||u[7]===void 0?1:parseFloat(u[7])))}else this._colors.push(this._grayColor)}else if((u=Ze.NormalPattern.exec(c))!==null)this._normals.push(new v(parseFloat(u[1]),parseFloat(u[2]),parseFloat(u[3])));else if((u=Ze.UVPattern.exec(c))!==null)this._uvs.push(new fe(parseFloat(u[1])*this._loadingOptions.UVScaling.x,parseFloat(u[2])*this._loadingOptions.UVScaling.y));else if((u=Ze.FacePattern3.exec(c))!==null)this._setDataForCurrentFaceWithPattern3(u[1].trim().split(" "),1);else if((u=Ze.FacePattern4.exec(c))!==null)this._setDataForCurrentFaceWithPattern4(u[1].trim().split(" "),1);else if((u=Ze.FacePattern5.exec(c))!==null)this._setDataForCurrentFaceWithPattern5(u[1].trim().split(" "),1);else if((u=Ze.FacePattern2.exec(c))!==null)this._setDataForCurrentFaceWithPattern2(u[1].trim().split(" "),1);else if((u=Ze.FacePattern1.exec(c))!==null)this._setDataForCurrentFaceWithPattern1(u[1].trim().split(" "),1);else if((u=Ze.LinePattern1.exec(c))!==null)this._setDataForCurrentFaceWithPattern1(u[1].trim().split(" "),0),this._hasLineData=!0;else if((u=Ze.LinePattern2.exec(c))!==null)this._setDataForCurrentFaceWithPattern2(u[1].trim().split(" "),0),this._hasLineData=!0;else if((u=Ze.LinePattern3.exec(c))!==null)this._setDataForCurrentFaceWithPattern3(u[1].trim().split(" "),0),this._hasLineData=!0;else if(Ze.GroupDescriptor.test(c)||Ze.ObjectDescriptor.test(c)){const f={name:c.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:Ze.ObjectDescriptor.test(c)};this._addPreviousObjMesh(),this._meshesFromObj.push(f),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(Ze.UseMtlDescriptor.test(c)){if(this._materialNameFromObj=c.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const f={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:!1};this._increment++,this._meshesFromObj.push(f),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else Ze.MtlLibGroupDescriptor.test(c)?n(c.substring(7).trim()):Ze.SmoothDescriptor.test(c)||U.Log("Unhandled expression at line : "+c)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._handledMesh.normals=this._unwrappedNormalsForBabylon,this._handledMesh.uvs=this._unwrappedUVForBabylon,this._handledMesh.hasLines=this._hasLineData,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon)),!this._hasMeshes){let h=null;if(this._indicesForBabylon.length)this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData();else{for(const c of this._positions)this._unwrappedPositionsForBabylon.push(c.x,c.y,c.z);if(this._normals.length)for(const c of this._normals)this._unwrappedNormalsForBabylon.push(c.x,c.y,c.z);if(this._uvs.length)for(const c of this._uvs)this._unwrappedUVForBabylon.push(c.x,c.y);if(this._colors.length)for(const c of this._colors)this._unwrappedColorsForBabylon.push(c.r,c.g,c.b,c.a);this._materialNameFromObj||(h=new te(kt.RandomId(),i),h.pointsCloud=!0,this._materialNameFromObj=h.name,this._normals.length||(h.disableLighting=!0,h.emissiveColor=pe.White()))}this._meshesFromObj.push({name:kt.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:h,isObject:!0})}for(let h=0;h=0;--f)if(this._meshesFromObj[f].isObject&&this._meshesFromObj[f]._babylonMesh){c.parent=this._meshesFromObj[f]._babylonMesh;break}}if(this._materialToUse.push(this._meshesFromObj[h].materialName),this._handledMesh.hasLines&&((o=c._internalMetadata)!=null||(c._internalMetadata={}),c._internalMetadata._isLine=!0),((l=this._handledMesh.positions)==null?void 0:l.length)===0){this._babylonMeshesArray.push(c);continue}const u=new j;if(u.uvs=this._handledMesh.uvs,u.indices=this._handledMesh.indices,u.positions=this._handledMesh.positions,this._loadingOptions.computeNormals){const f=new Array;j.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,f),u.normals=f}else u.normals=this._handledMesh.normals;this._loadingOptions.importVertexColors&&(u.colors=this._handledMesh.colors),u.applyToMesh(c),this._loadingOptions.invertY&&(c.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(c),this._babylonMeshesArray.push(c),this._handledMesh.directMaterial&&(c.material=this._handledMesh.directMaterial)}}}Ze.ObjectDescriptor=/^o/;Ze.GroupDescriptor=/^g/;Ze.MtlLibGroupDescriptor=/^mtllib /;Ze.UseMtlDescriptor=/^usemtl /;Ze.SmoothDescriptor=/^s /;Ze.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/;Ze.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;Ze.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;Ze.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/;Ze.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;Ze.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;Ze.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;Ze.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;Ze.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/;Ze.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;Ze.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;class Ev extends Xi{}class Iv{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){this.rootNodes.slice(0).forEach(e=>{e.dispose()}),this.rootNodes.length=0,this.skeletons.slice(0).forEach(e=>{e.dispose()}),this.skeletons.length=0,this.animationGroups.slice(0).forEach(e=>{e.dispose()}),this.animationGroups.length=0}}class Av extends Xi{constructor(e){super(),this._wasAddedToScene=!1,e=e||Ce.LastCreatedScene,e&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add(()=>{this._wasAddedToScene||this.dispose()}),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{for(const t of this.geometries)t._rebuild();for(const t of this.meshes)t._rebuild();for(const t of this.particleSystems)t.rebuild();for(const t of this.textures)t._rebuild()}))}_topologicalSort(e){const t=new Map;for(const o of e)t.set(o.uniqueId,o);const i={dependsOn:new Map,dependedBy:new Map};for(const o of e){const l=o.uniqueId;i.dependsOn.set(l,new Set),i.dependedBy.set(l,new Set)}for(const o of e){const l=o.uniqueId,h=i.dependsOn.get(l);if(o instanceof Ur){const u=o.sourceMesh;t.has(u.uniqueId)&&(h.add(u.uniqueId),i.dependedBy.get(u.uniqueId).add(l))}const c=i.dependedBy.get(l);for(const u of o.getDescendants()){const f=u.uniqueId;t.has(f)&&(c.add(f),i.dependsOn.get(f).add(l))}}const s=[],n=[];for(const o of e){const l=o.uniqueId;i.dependsOn.get(l).size===0&&(n.push(o),t.delete(l))}const r=n;for(;r.length>0;){const o=r.shift();s.push(o);const l=i.dependedBy.get(o.uniqueId);for(const h of Array.from(l.values())){const c=i.dependsOn.get(h);c.delete(o.uniqueId),c.size===0&&t.get(h)&&(r.push(t.get(h)),t.delete(h))}}return t.size>0&&(U.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(o=>U.Error(o.name))),s}_addNodeAndDescendantsToList(e,t,i,s){if(!(!i||s&&!s(i)||t.has(i.uniqueId))){e.push(i),t.add(i.uniqueId);for(const n of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,n,s)}}_isNodeInContainer(e){return e instanceof et&&this.meshes.indexOf(e)!==-1||e instanceof Ie&&this.transformNodes.indexOf(e)!==-1||e instanceof De&&this.lights.indexOf(e)!==-1||e instanceof ve&&this.cameras.indexOf(e)!==-1}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return U.Warn("Node ".concat(e.name," has a parent that is not in the container.")),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return U.Warn("Node ".concat(e.name," has a parent that is not in the container.")),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return U.Warn("Node ".concat(e.name," has a parent that is not in the container.")),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return U.Warn("Node ".concat(e.name," has a parent that is not in the container.")),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||ee.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},n={},r=new Iv,o=[],l=[],h={doNotInstantiate:!0,...i},c=(g,_)=>{if(s[g.uniqueId]=_.uniqueId,n[_.uniqueId]=_,e&&(_.name=e(g.name)),_ instanceof F){const m=_;if(m.morphTargetManager){const x=g.morphTargetManager;m.morphTargetManager=x.clone();for(let I=0;I{if(c(g,_),g.parent){const m=s[g.parent.uniqueId],x=n[m];x?_.parent=x:_.parent=g.parent}if(_.position&&g.position&&_.position.copyFrom(g.position),_.rotationQuaternion&&g.rotationQuaternion&&_.rotationQuaternion.copyFrom(g.rotationQuaternion),_.rotation&&g.rotation&&_.rotation.copyFrom(g.rotation),_.scaling&&g.scaling&&_.scaling.copyFrom(g.scaling),_.material){const m=_;if(m.material)if(t){const x=g.material;if(l.indexOf(x)===-1){let I=x.clone(e?e(x.name):"Clone of "+x.name);if(l.push(x),s[x.uniqueId]=I.uniqueId,n[I.uniqueId]=I,x.getClassName()==="MultiMaterial"){const T=x;for(const y of T.subMaterials)y&&(I=y.clone(e?e(y.name):"Clone of "+y.name),l.push(y),s[y.uniqueId]=I.uniqueId,n[I.uniqueId]=I);T.subMaterials=T.subMaterials.map(y=>y&&n[s[y.uniqueId]])}}m.getClassName()!=="InstancedMesh"&&(m.material=n[s[x.uniqueId]])}else m.material.getClassName()==="MultiMaterial"?this.scene.multiMaterials.indexOf(m.material)===-1&&this.scene.addMultiMaterial(m.material):this.scene.materials.indexOf(m.material)===-1&&this.scene.addMaterial(m.material)}_.parent===null&&r.rootNodes.push(_)};return d.forEach(g=>{if(g.getClassName()==="InstancedMesh"){const _=g,m=_.sourceMesh,x=s[m.uniqueId],T=(typeof x=="number"?n[x]:m).createInstance(_.name);p(_,T)}else{let _=!0;g.getClassName()==="TransformNode"||g.getClassName()==="Node"||g.skeleton||!g.getTotalVertices||g.getTotalVertices()===0?_=!1:h.doNotInstantiate&&(typeof h.doNotInstantiate=="function"?_=!h.doNotInstantiate(g):_=!h.doNotInstantiate);const m=_?g.createInstance("instance of ".concat(g.name)):g.clone("Clone of ".concat(g.name),null,!0);if(!m)throw new Error("Could not clone or instantiate node on Asset Container ".concat(g.name));p(g,m)}}),this.skeletons.forEach(g=>{if(h.predicate&&!h.predicate(g))return;const _=g.clone(e?e(g.name):"Clone of "+g.name);for(const m of this.meshes)if(m.skeleton===g&&!m.isAnInstance){const x=n[s[m.uniqueId]];if(!x||x.isAnInstance||(x.skeleton=_,o.indexOf(_)!==-1))continue;o.push(_);for(const I of _.bones)I._linkedTransformNode&&(I._linkedTransformNode=n[s[I._linkedTransformNode.uniqueId]])}r.skeletons.push(_)}),this.animationGroups.forEach(g=>{if(h.predicate&&!h.predicate(g))return;const _=g.clone(e?e(g.name):"Clone of "+g.name,m=>n[s[m.uniqueId]]||m);r.animationGroups.push(_)}),r}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||ee.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(const e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){const t=[];this.cameras.forEach(i=>{e&&!e(i)||(this.scene.addCamera(i),t.push(i))}),this.lights.forEach(i=>{e&&!e(i)||(this.scene.addLight(i),t.push(i))}),this.meshes.forEach(i=>{e&&!e(i)||(this.scene.addMesh(i),t.push(i))}),this.skeletons.forEach(i=>{e&&!e(i)||this.scene.addSkeleton(i)}),this.animations.forEach(i=>{e&&!e(i)||this.scene.addAnimation(i)}),this.animationGroups.forEach(i=>{e&&!e(i)||this.scene.addAnimationGroup(i)}),this.multiMaterials.forEach(i=>{e&&!e(i)||this.scene.addMultiMaterial(i)}),this.materials.forEach(i=>{e&&!e(i)||this.scene.addMaterial(i)}),this.morphTargetManagers.forEach(i=>{e&&!e(i)||this.scene.addMorphTargetManager(i)}),this.geometries.forEach(i=>{e&&!e(i)||this.scene.addGeometry(i)}),this.transformNodes.forEach(i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))}),this.actionManagers.forEach(i=>{e&&!e(i)||this.scene.addActionManager(i)}),this.textures.forEach(i=>{e&&!e(i)||this.scene.addTexture(i)}),this.reflectionProbes.forEach(i=>{e&&!e(i)||this.scene.addReflectionProbe(i)});for(const i of t)i.parent&&this.scene.getNodes().indexOf(i.parent)===-1&&(i.setParent?i.setParent(null):i.parent=null)}removeAllFromScene(){this._isValidHierarchy()||ee.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach(t=>{e&&!e(t)||this.scene.removeCamera(t)}),this.lights.forEach(t=>{e&&!e(t)||this.scene.removeLight(t)}),this.meshes.forEach(t=>{e&&!e(t)||this.scene.removeMesh(t,!0)}),this.skeletons.forEach(t=>{e&&!e(t)||this.scene.removeSkeleton(t)}),this.animations.forEach(t=>{e&&!e(t)||this.scene.removeAnimation(t)}),this.animationGroups.forEach(t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)}),this.multiMaterials.forEach(t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)}),this.materials.forEach(t=>{e&&!e(t)||this.scene.removeMaterial(t)}),this.morphTargetManagers.forEach(t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)}),this.geometries.forEach(t=>{e&&!e(t)||this.scene.removeGeometry(t)}),this.transformNodes.forEach(t=>{e&&!e(t)||this.scene.removeTransformNode(t)}),this.actionManagers.forEach(t=>{e&&!e(t)||this.scene.removeActionManager(t)}),this.textures.forEach(t=>{e&&!e(t)||this.scene.removeTexture(t)}),this.reflectionProbes.forEach(t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)})}dispose(){this.cameras.slice(0).forEach(e=>{e.dispose()}),this.cameras.length=0,this.lights.slice(0).forEach(e=>{e.dispose()}),this.lights.length=0,this.meshes.slice(0).forEach(e=>{e.dispose()}),this.meshes.length=0,this.skeletons.slice(0).forEach(e=>{e.dispose()}),this.skeletons.length=0,this.animationGroups.slice(0).forEach(e=>{e.dispose()}),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach(e=>{e.dispose()}),this.multiMaterials.length=0,this.materials.slice(0).forEach(e=>{e.dispose()}),this.materials.length=0,this.geometries.slice(0).forEach(e=>{e.dispose()}),this.geometries.length=0,this.transformNodes.slice(0).forEach(e=>{e.dispose()}),this.transformNodes.length=0,this.actionManagers.slice(0).forEach(e=>{e.dispose()}),this.actionManagers.length=0,this.textures.slice(0).forEach(e=>{e.dispose()}),this.textures.length=0,this.reflectionProbes.slice(0).forEach(e=>{e.dispose()}),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach(e=>{e.dispose()}),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(!(!e||!t))for(const s of e){let n=!0;if(i){for(const r of i)if(s===r){n=!1;break}}n&&(t.push(s),s._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,e===void 0&&(e=new Ev);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||(t==="_environmentTexture"?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new F("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=Ce.LastCreatedScene,t,i=null){if(!e)return U.Error("No scene available to merge animations to"),[];const s=i||(o=>{let l=null;const h=o.animations.length?o.animations[0].targetProperty:"",c=o.name.split(".").join("").split("_primitive")[0];switch(h){case"position":case"rotationQuaternion":l=e.getTransformNodeByName(o.name)||e.getTransformNodeByName(c);break;case"influence":l=e.getMorphTargetByName(o.name)||e.getMorphTargetByName(c);break;default:l=e.getNodeByName(o.name)||e.getNodeByName(c)}return l});this.getNodes().forEach(o=>{const l=s(o);if(l!==null){for(const h of o.animations){const c=l.animations.filter(u=>u.targetProperty===h.targetProperty);for(const u of c){const f=l.animations.indexOf(u,0);f>-1&&l.animations.splice(f,1)}}l.animations=l.animations.concat(o.animations)}});const r=[];return this.animationGroups.slice().forEach(o=>{r.push(o.clone(o.name,s)),o.animatables.forEach(l=>{l.stop()})}),t.forEach(o=>{const l=s(o.target);l&&(e.beginAnimation(l,o.fromFrame,o.toFrame,o.loopAnimation,o.speedRatio,o.onAnimationEnd?o.onAnimationEnd:void 0,void 0,!0,void 0,o.onAnimationLoop?o.onAnimationLoop:void 0),e.stopAnimation(o.target))}),r}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.transformNodes.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.lights.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}),this.cameras.forEach(e=>{!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)})}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const s=t.pop();if(s instanceof F?(s.geometry&&this.geometries.indexOf(s.geometry)===-1&&this.geometries.push(s.geometry),this.meshes.push(s)):s instanceof Ie?this.transformNodes.push(s):s instanceof De?this.lights.push(s):s instanceof ve&&this.cameras.push(s),s instanceof et){if(s.material&&this.materials.indexOf(s.material)===-1){this.materials.push(s.material);for(const n of s.material.getActiveTextures())this.textures.indexOf(n)===-1&&this.textures.push(n)}s.skeleton&&this.skeletons.indexOf(s.skeleton)===-1&&this.skeletons.push(s.skeleton),s.morphTargetManager&&this.morphTargetManagers.indexOf(s.morphTargetManager)===-1&&this.morphTargetManagers.push(s.morphTargetManager)}for(const n of s.getChildren())i.has(n)||t.push(n);i.add(s)}this.populateRootNodes()}}class vt{static get INVERT_TEXTURE_Y(){return Ri.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){Ri.INVERT_TEXTURE_Y=e}constructor(e){this.name="obj",this.extensions=".obj",this._assetContainer=null,this._loadingOptions=e||vt._DefaultLoadingOptions}static get _DefaultLoadingOptions(){return{computeNormals:vt.COMPUTE_NORMALS,optimizeNormals:vt.OPTIMIZE_NORMALS,importVertexColors:vt.IMPORT_VERTEX_COLORS,invertY:vt.INVERT_Y,invertTextureY:vt.INVERT_TEXTURE_Y,UVScaling:vt.UV_SCALING,materialLoadingFailsSilently:vt.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:vt.OPTIMIZE_WITH_UV,skipMaterials:vt.SKIP_MATERIALS,useLegacyBehavior:vt.USE_LEGACY_BEHAVIOR}}_loadMTL(e,t,i,s){const n=t+e;ee.LoadFile(n,i,void 0,void 0,!1,(r,o)=>{s(n,o)})}createPlugin(){return new vt(vt._DefaultLoadingOptions)}canDirectLoad(){return!1}importMeshAsync(e,t,i,s){return this._parseSolid(e,t,i,s).then(n=>({meshes:n,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then(()=>{})}loadAssetContainerAsync(e,t,i){const s=new Av(e);return this._assetContainer=s,this.importMeshAsync(null,e,t,i).then(n=>(n.meshes.forEach(r=>s.meshes.push(r)),n.meshes.forEach(r=>{const o=r.material;o&&s.materials.indexOf(o)==-1&&(s.materials.push(o),o.getActiveTextures().forEach(h=>{s.textures.indexOf(h)==-1&&s.textures.push(h)}))}),this._assetContainer=null,s)).catch(n=>{throw this._assetContainer=null,n})}_parseSolid(e,t,i,s){let n="";const r=new Ri,o=[],l=[];new Ze(o,l,this._loadingOptions).parse(e,i,t,this._assetContainer,u=>{n=u});const c=[];return n!==""&&!this._loadingOptions.skipMaterials&&c.push(new Promise((u,f)=>{this._loadMTL(n,s,d=>{try{r.parseMTL(t,d,s,this._assetContainer);for(let p=0;p-1;)_.push(m),g=m+1;if(m===-1&&_.length===0)r.materials[p].dispose();else for(let x=0;x<_.length;x++){const I=l[_[x]],T=r.materials[p];I.material=T,I.getTotalIndices()||(T.pointsCloud=!0)}}u()}catch(p){ee.Warn("Error processing MTL file: '".concat(n,"'")),this._loadingOptions.materialLoadingFailsSilently?u():f(p)}},(d,p)=>{ee.Warn("Error downloading MTL file: '".concat(n,"'")),this._loadingOptions.materialLoadingFailsSilently?u():f(p)})})),Promise.all(c).then(()=>{const u=f=>{var d,p;return!!((p=(d=f._internalMetadata)==null?void 0:d._isLine)!=null&&p)};return l.forEach(f=>{var d,p;if(u(f)){let g=(d=f.material)!=null?d:new te(f.name+"_line",t);g.getBindedMeshes().filter(m=>!u(m)).length>0&&(g=(p=g.clone(g.name+"_line"))!=null?p:g),g.wireframe=!0,f.material=g,f._internalMetadata&&(f._internalMetadata._isLine=void 0)}}),l})}}vt.OPTIMIZE_WITH_UV=!0;vt.INVERT_Y=!1;vt.IMPORT_VERTEX_COLORS=!1;vt.COMPUTE_NORMALS=!1;vt.OPTIMIZE_NORMALS=!1;vt.UV_SCALING=new fe(1,1);vt.SKIP_MATERIALS=!1;vt.MATERIAL_LOADING_FAILS_SILENTLY=!0;vt.USE_LEGACY_BEHAVIOR=!1;Be&&Be.RegisterPlugin(new vt);class Ge{constructor(e,t,i=Number.MAX_VALUE,s=Ne){this.origin=e,this.direction=t,this.length=i,this.epsilon=s}clone(){return new Ge(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const s=Ge._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),n=Ge._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let r=0,o=Number.MAX_VALUE,l,h,c,u;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xn.x)return!1}else if(l=1/this.direction.x,h=(s.x-this.origin.x)*l,c=(n.x-this.origin.x)*l,c===-1/0&&(c=1/0),h>c&&(u=h,h=c,c=u),r=Math.max(h,r),o=Math.min(c,o),r>o)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yn.y)return!1}else if(l=1/this.direction.y,h=(s.y-this.origin.y)*l,c=(n.y-this.origin.y)*l,c===-1/0&&(c=1/0),h>c&&(u=h,h=c,c=u),r=Math.max(h,r),o=Math.min(c,o),r>o)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zn.z)return!1}else if(l=1/this.direction.z,h=(s.z-this.origin.z)*l,c=(n.z-this.origin.z)*l,c===-1/0&&(c=1/0),h>c&&(u=h,h=c,c=u),r=Math.max(h,r),o=Math.min(c,o),r>o)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,s=e.center.y-this.origin.y,n=e.center.z-this.origin.z,r=i*i+s*s+n*n,o=e.radius+t,l=o*o;if(r<=l)return!0;const h=i*this.direction.x+s*this.direction.y+n*this.direction.z;return h<0?!1:r-h*h<=l}intersectsTriangle(e,t,i){const s=Ge._TmpVector3[0],n=Ge._TmpVector3[1],r=Ge._TmpVector3[2],o=Ge._TmpVector3[3],l=Ge._TmpVector3[4];t.subtractToRef(e,s),i.subtractToRef(e,n),v.CrossToRef(this.direction,n,r);const h=v.Dot(s,r);if(h===0)return null;const c=1/h;this.origin.subtractToRef(e,o);const u=v.Dot(o,r)*c;if(u<-this.epsilon||u>1+this.epsilon)return null;v.CrossToRef(o,s,l);const f=v.Dot(this.direction,l)*c;if(f<-this.epsilon||u+f>1+this.epsilon)return null;const d=v.Dot(n,l)*c;return d>this.length?null:new Ea(1-u-f,u,d)}intersectsPlane(e){let t;const i=v.Dot(e.normal,this.direction);if(Math.abs(i)<999999997475243e-21)return null;{const s=v.Dot(e.normal,this.origin);return t=(-e.d-s)/i,t<0?t<-999999997475243e-21?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const i=(this.origin.y-t)/this.direction.y;return i>0?null:new v(this.origin.x+this.direction.x*-i,t,this.origin.z+this.direction.z*-i)}case"x":{const i=(this.origin.x-t)/this.direction.x;return i>0?null:new v(t,this.origin.y+this.direction.y*-i,this.origin.z+this.direction.z*-i)}case"z":{const i=(this.origin.z-t)/this.direction.z;return i>0?null:new v(this.origin.x+this.direction.x*-i,this.origin.y+this.direction.y*-i,t)}default:return null}}intersectsMesh(e,t,i,s=!1,n,r=!1){const o=N.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?Ge.TransformToRef(this,o,this._tmpRay):this._tmpRay=Ge.Transform(this,o),e.intersects(this._tmpRay,t,i,s,n,r)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let s=0;st.distance?1:0}intersectionSegment(e,t,i){const s=this.origin,n=N.Vector3[0],r=N.Vector3[1],o=N.Vector3[2],l=N.Vector3[3];t.subtractToRef(e,n),this.direction.scaleToRef(Ge._Rayl,o),s.addToRef(o,r),e.subtractToRef(s,l);const h=v.Dot(n,n),c=v.Dot(n,o),u=v.Dot(o,o),f=v.Dot(n,l),d=v.Dot(o,l),p=h*u-c*c;let g,_=p,m,x=p;p_&&(g=_,m=d+c,x=u)),m<0?(m=0,-f<0?g=0:-f>h?g=_:(g=-f,_=h)):m>x&&(m=x,-f+c<0?g=0:-f+c>h?g=_:(g=-f+c,_=h));const I=Math.abs(g)0&&T<=this.length&&S.lengthSquared()=a.distance?null:h};Qe.prototype._internalPick=function(a,e,t,i,s){let n=null;const r=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),n=this.cameraToUseForPointers||this.activeCamera;for(let r=0;r(this._tempPickingRay||(this._tempPickingRay=Ge.Zero()),this.createPickingRayToRef(a,e,r,this._tempPickingRay,s||null),this._tempPickingRay),t,i,!0);return n&&(n.ray=this.createPickingRay(a,e,O.Identity(),s||null)),n};Object.defineProperty(Qe.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1});Qe.prototype.pick=function(a,e,t,i,s,n,r=!1){const o=this._internalPick((l,h)=>(this._tempPickingRay||(this._tempPickingRay=Ge.Zero()),this.createPickingRayToRef(a,e,l,this._tempPickingRay,s||null,!1,h),this._tempPickingRay),t,i,!1,n);return o&&(o.ray=this.createPickingRay(a,e,O.Identity(),s||null)),o};Qe.prototype.pickWithRay=function(a,e,t,i){const s=this._internalPick(n=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=O.Identity()),n.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Ge.Zero()),Ge.TransformToRef(a,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t,!1,i);return s&&(s.ray=a),s};Qe.prototype.multiPick=function(a,e,t,i,s){return this._internalMultiPick(n=>this.createPickingRay(a,e,n,i||null),t,s)};Qe.prototype.multiPickWithRay=function(a,e,t){return this._internalMultiPick(i=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=O.Identity()),i.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Ge.Zero()),Ge.TransformToRef(a,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t)};ve.prototype.getForwardRay=function(a=100,e,t){return this.getForwardRayToRef(new Ge(v.Zero(),v.Zero(),a),a,e,t)};ve.prototype.getForwardRayToRef=function(a,e=100,t,i){t||(t=this.getWorldMatrix()),a.length=e,i?a.origin.copyFrom(i):a.origin.copyFrom(this.position);const s=N.Vector3[2];s.set(0,0,this._scene.useRightHandedSystem?-1:1);const n=N.Vector3[3];return v.TransformNormalToRef(s,t,n),v.NormalizeToRef(n,a.direction),a};Se.prototype.setAlphaMode=function(a,e=!1){if(this._alphaMode===a&&(a===0&&!this._alphaState.alphaBlend||a!==0&&this._alphaState.alphaBlend)){if(!e){const t=a===0;this.depthCullingState.depthMask!==t&&(this.setDepthWrite(t),this._cacheRenderPipeline.setDepthWriteEnabled(t))}return}switch(a){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,1),this._alphaState.alphaBlend=!0;break;case 8:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,1),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(1,1,0,1),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(770,1,0,1),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(0,769,1,1),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(774,0,1,1),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(770,769,1,1),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(32769,32770,32771,32772),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(1,769,1,771),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,1),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(772,1,0,0),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(775,769,773,771),this._alphaState.alphaBlend=!0;break;case 14:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,0),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(775,769,0,1),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,771),this._alphaState.alphaBlend=!0;break}e||(this.setDepthWrite(a===0),this._cacheRenderPipeline.setDepthWriteEnabled(a===0)),this._alphaMode=a,this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};Se.prototype.setAlphaEquation=function(a){me.prototype.setAlphaEquation.call(this,a),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};class sn{constructor(e,t,i,s=""){var l,h;this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new Q,this.onErrorObservable=new Q,this.onBindObservable=new Q,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=1,this.name=e,this._key=s,this._engine=i,this.uniqueId=sn._UniqueIdSeed++,this.defines=(l=t.defines)!=null?l:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=(h=t.entryPoint)!=null?h:"main",this._shaderStore=K.GetShadersStore(this._shaderLanguage),this._shaderRepository=K.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=K.GetIncludesShadersStore(this._shaderLanguage);let n;const r=St()?this._engine.getHostDocument():null;typeof e=="string"?n=e:e.computeSource?n="source:"+e.computeSource:e.computeElement?n=(r==null?void 0:r.getElementById(e.computeElement))||e.computeElement:n=e.compute||e;const o={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(this._engine.version*100).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:(c,u,f)=>{if(!f)return u;for(const d of f){const g=d.replace("#define","").replace(";","").trim().split(" ");if(g.length===2){const _=g[0],m=g[1];(!isNaN(parseInt(m))||!isNaN(parseFloat(m)))&&(u="const ".concat(_," = ").concat(m,";\n")+u)}}return u}};this._loadShader(n,"Compute","",c=>{ah(o),Mf(c,o,u=>{this._rawComputeSourceCode=c,t.processFinalCode&&(u=t.processFinalCode(u));const f=oh(u,"",o);this._useFinalCode(f.vertexCode,e)},this._engine)})}_useFinalCode(e,t){if(t){const i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return this._isReady?!0:this._pipelineContext?this._pipelineContext.isReady:!1}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){if(this.isReady()){e(this);return}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){this._processCompilationErrors(t,e);return}setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,s){if(typeof HTMLElement<"u"&&e instanceof HTMLElement){const r=Ga(e);s(r);return}if(e.substr(0,7)==="source:"){s(e.substr(7));return}if(e.substr(0,7)==="base64:"){const r=window.atob(e.substr(7));s(r);return}if(this._shaderStore[e+t+"Shader"]){s(this._shaderStore[e+t+"Shader"]);return}if(i&&this._shaderStore[e+i+"Shader"]){s(this._shaderStore[e+i+"Shader"]);return}let n;e[0]==="."||e[0]==="/"||e.indexOf("http")>-1?n=e:n=this._shaderRepository+e,this._engine._loadFile(n+"."+t.toLowerCase()+".fx",s)}get computeSourceCode(){var e,t;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:(t=(e=this._pipelineContext)==null?void 0:e._getComputeShaderCode())!=null?t:this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){const e=this.defines,t=this._pipelineContext;this._isReady=!1;try{const i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,s=>{if(s&&s.numErrors>0){this._processCompilationErrors(s,t);return}this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t)}),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(i){this._processCompilationErrors(i,t)}}_processCompilationErrors(e,t=null){var i;if(this._compilationError="",U.Error("Unable to compile compute effect:"),this.defines&&U.Error("Defines:\n"+this.defines),sn.LogShaderCodeOnCompilationError){const s=(i=this._pipelineContext)==null?void 0:i._getComputeShaderCode();s&&(U.Error("Compute code:"),U.Error(s))}if(typeof e=="string")this._compilationError=e,U.Error("Error: "+this._compilationError);else for(const s of e.messages){let n="";s.line!==void 0&&(n+="Line "+s.line+", "),s.offset!==void 0&&(n+="Offset "+s.offset+", "),s.length!==void 0&&(n+="Length "+s.length+", "),n+=s.type+": "+s.text,this._compilationError&&(this._compilationError+="\n"),this._compilationError+=n,U.Error(n)}t&&(this._pipelineContext=t,this._isReady=!0),this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){K.GetShadersStore(1)["".concat(e,"ComputeShader")]=t}}sn._UniqueIdSeed=0;sn.LogShaderCodeOnCompilationError=!0;class Vr{getBindGroups(e,t,i){if(!i)throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");if(this._bindGroups.length===0){const s=this._bindGroupEntries.length>0;for(const n in e){const r=e[n],o=i[n],l=o.group,h=o.binding,c=r.type,u=r.object;let f=r.indexInGroupEntries,d=this._bindGroupEntries[l];switch(d||(d=this._bindGroupEntries[l]=[]),c){case 5:{const p=u;f!==void 0&&s?d[f].resource=this._cacheSampler.getSampler(p):(r.indexInGroupEntries=d.length,d.push({binding:h,resource:this._cacheSampler.getSampler(p)}));break}case 0:case 4:{const p=u,g=p._texture._hardwareTexture;f!==void 0&&s?(c===0&&(d[f++].resource=this._cacheSampler.getSampler(p._texture)),d[f].resource=g.view):(r.indexInGroupEntries=d.length,c===0&&d.push({binding:h-1,resource:this._cacheSampler.getSampler(p._texture)}),d.push({binding:h,resource:g.view}));break}case 1:{const p=u,g=p._texture._hardwareTexture;g.textureAdditionalUsages&8||U.Error("computeDispatch: The texture (name=".concat(p.name,", uniqueId=").concat(p.uniqueId,") is not a storage texture!"),50),f!==void 0&&s?d[f].resource=g.viewForWriting:(r.indexInGroupEntries=d.length,d.push({binding:h,resource:g.viewForWriting}));break}case 6:{const g=u.underlyingResource;f!==void 0&&s?d[f].resource=this._device.importExternalTexture({source:g}):(r.indexInGroupEntries=d.length,d.push({binding:h,resource:this._device.importExternalTexture({source:g})}));break}case 2:case 3:case 7:{const p=c===7?u:u.getBuffer(),g=p.underlyingResource;f!==void 0&&s?(d[f].resource.buffer=g,d[f].resource.size=p.capacity):(r.indexInGroupEntries=d.length,d.push({binding:h,resource:{buffer:g,offset:0,size:p.capacity}}));break}}}for(let n=0;n0&&f.dispatchWorkgroups(i,s,n),f.end(),h&&(this._timestampQuery.endPass(this._timestampIndex,h),this._timestampIndex+=2)};Se.prototype.releaseComputeEffects=function(){for(const a in this._compiledComputeEffects){const e=this._compiledComputeEffects[a].getPipelineContext();this._deleteComputePipelineContext(e)}this._compiledComputeEffects={}};Se.prototype._prepareComputePipelineContext=function(a,e,t,i,s){const n=a;this.dbgShowShaderCode&&(U.Log(i),U.Log(e)),n.sources={compute:e,rawCompute:t},n.stage=this._createComputePipelineStageDescriptor(e,i,s)};Se.prototype._releaseComputeEffect=function(a){this._compiledComputeEffects[a._key]&&(delete this._compiledComputeEffects[a._key],this._deleteComputePipelineContext(a.getPipelineContext()))};Se.prototype._rebuildComputeEffects=function(){for(const a in this._compiledComputeEffects){const e=this._compiledComputeEffects[a];e._pipelineContext=null,e._wasPreviouslyReady=!1,e._prepareEffect()}};Se.prototype._executeWhenComputeStateIsCompiled=function(a,e){a.stage.module.getCompilationInfo().then(t=>{const i={numErrors:0,messages:[]};for(const s of t.messages)s.type==="error"&&i.numErrors++,i.messages.push({type:s.type,text:s.message,line:s.lineNum,column:s.linePos,length:s.length,offset:s.offset});e(i)})};Se.prototype._deleteComputePipelineContext=function(a){a&&a.dispose()};Se.prototype._createComputePipelineStageDescriptor=function(a,e,t){return e?e="//"+e.split("\n").join("\n//")+"\n":e="",{module:this._device.createShaderModule({code:e+a}),entryPoint:t}};Se.prototype._createDepthStencilCubeTexture=function(a,e){const t=new Et(this,e.generateStencil?12:14);t.isCube=!0,t.label=e.label;const i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:e.generateStencil?13:14,...e};t.format=i.depthTextureFormat,this._setupDepthStencilTexture(t,a,i.generateStencil,i.bilinearFiltering,i.comparisonFunction,i.samples),this._textureHelper.createGPUTextureForInternalTexture(t);const s=t._hardwareTexture;return t.type=Ve.GetTextureTypeFromFormat(s.format),this._internalTexturesCache.push(t),t};Se.prototype.createCubeTexture=function(a,e,t,i,s=null,n=null,r,o=null,l=!1,h=0,c=0,u=null,f,d=!1,p=null){return this.createCubeTextureBase(a,e,t,!!i,s,n,r,o,l,h,c,u,null,(g,_)=>{const m=_,x=m[0].width,I=x;this._setCubeMapTextureParams(g,!i),g.format=r!=null?r:-1;const T=this._textureHelper.createGPUTextureForInternalTexture(g,x,I);this._textureHelper.updateCubeTextures(m,T.underlyingResource,x,I,T.format,!1,!1,0,0),i||this._generateMipmaps(g,this._uploadEncoder),g.isReady=!0,g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear(),s&&s()},!!d,p)};Se.prototype._setCubeMapTextureParams=function(a,e,t){a.samplingMode=e?3:2,a._cachedWrapU=0,a._cachedWrapV=0,t&&(a._maxLodLevel=t)};Se.prototype.generateMipMapsForCubemap=function(a){var e;a.generateMipMaps&&((e=a._hardwareTexture)!=null&&e.underlyingResource||this._textureHelper.createGPUTextureForInternalTexture(a),this._generateMipmaps(a))};Se.prototype._debugPushGroup=function(a,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.pushDebugGroup(a):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(a):this._pendingDebugCommands.push(["push",a]))};Se.prototype._debugPopGroup=function(a){this._options.enableGPUDebugMarkers&&(a===0||a===1?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))};Se.prototype._debugInsertMarker=function(a,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.insertDebugMarker(a):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(a):this._pendingDebugCommands.push(["insert",a]))};Se.prototype._debugFlushPendingCommands=function(){for(let a=0;a0)}else if(a.occlusionInternalRetryCounter++,a.occlusionRetryCount!==-1&&a.occlusionInternalRetryCounter>a.occlusionRetryCount)a.isOcclusionQueryInProgress=!1,a.occlusionInternalRetryCounter=0,a.isOccluded=a.occlusionType===et.OCCLUSION_TYPE_OPTIMISTIC?!1:a.isOccluded;else return a.occlusionType===et.OCCLUSION_TYPE_OPTIMISTIC?!1:a.isOccluded;const t=this.getScene();if(t.getBoundingBoxRenderer){const i=t.getBoundingBoxRenderer();this._occlusionQuery===null&&(this._occlusionQuery=e.createQuery()),this._occlusionQuery&&e.beginOcclusionQuery(a.occlusionQueryAlgorithmType,this._occlusionQuery)&&(i.renderOcclusionBoundingBox(this),e.endOcclusionQuery(a.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return a.isOccluded};Se.prototype.getGPUFrameTimeCounter=function(){return this._timestampQuery.gpuFrameTimeCounter};Se.prototype.captureGPUFrameTime=function(a){this._timestampQuery.enable=a&&!!this._caps.timerQuery};Se.prototype.createQuery=function(){return this._occlusionQuery.createQuery()};Se.prototype.deleteQuery=function(a){return this._occlusionQuery.deleteQuery(a),this};Se.prototype.isQueryResultAvailable=function(a){return this._occlusionQuery.isQueryResultAvailable(a)};Se.prototype.getQueryResult=function(a){return this._occlusionQuery.getQueryResult(a)};Se.prototype.beginOcclusionQuery=function(a,e){var t;if(this.compatibilityMode){if(this._occlusionQuery.canBeginQuery(e))return(t=this._currentRenderPass)==null||t.beginOcclusionQuery(e),!0}else return this._bundleList.addItem(new ao(e)),!0;return!1};Se.prototype.endOcclusionQuery=function(){var a;return this.compatibilityMode?(a=this._currentRenderPass)==null||a.endOcclusionQuery():this._bundleList.addItem(new oo),this};Se.prototype.createRawTexture=function(a,e,t,i,s,n,r,o=null,l=0,h=0,c=!1){const u=new Et(this,3);return u.baseWidth=e,u.baseHeight=t,u.width=e,u.height=t,u.format=i,u.generateMipMaps=s,u.samplingMode=r,u.invertY=n,u._compression=o,u.type=l,u._creationFlags=h,u._useSRGBBuffer=c,this._doNotHandleContextLost||(u._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(u,e,t,void 0,h),this.updateRawTexture(u,a,i,n,o,l,c),this._internalTexturesCache.push(u),u};Se.prototype.updateRawTexture=function(a,e,t,i,s=null,n=0,r=!1){if(a){if(this._doNotHandleContextLost||(a._bufferView=e,a.invertY=i,a._compression=s,a._useSRGBBuffer=r),e){const o=a._hardwareTexture;t===4&&(e=Vn(e,a.width,a.height,n));const h=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(h,a,a.width,a.height,a.depth,o.format,0,0,i,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0}};Se.prototype.createRawCubeTexture=function(a,e,t,i,s,n,r,o=null){const l=new Et(this,8);if(i===1&&!this._caps.textureFloatLinearFiltering?(s=!1,r=1,U.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):i===2&&!this._caps.textureHalfFloatLinearFiltering?(s=!1,r=1,U.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):i===1&&!this._caps.textureFloatRender?(s=!1,U.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):i===2&&!this._caps.colorBufferFloat&&(s=!1,U.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")),l.isCube=!0,l._originalFormat=t,l.format=t===4?5:t,l.type=i,l.generateMipMaps=s,l.width=e,l.height=e,l.samplingMode=r,this._doNotHandleContextLost||(l._bufferViewArray=a),l.invertY=n,l._compression=o,l._cachedWrapU=0,l._cachedWrapV=0,this._textureHelper.createGPUTextureForInternalTexture(l),t===4){const h=l._hardwareTexture;h._originalFormatIsRGB=!0}return a&&this.updateRawCubeTexture(l,a,t,i,n,o),l.isReady=!0,l};Se.prototype.updateRawCubeTexture=function(a,e,t,i,s,n=null){a._bufferViewArray=e,a.invertY=s,a._compression=n;const r=a._hardwareTexture,o=r._originalFormatIsRGB,l=[0,2,4,1,3,5],h=[];for(let c=0;c{e==null||e.removePendingData(f),h&&g&&h(g.status+" "+g.statusText,_)},p=g=>{const _=f.width,m=r(g);if(m){if(o){const x=i===4,I=o(m),T=f._hardwareTexture,y=[0,1,2,3,4,5];for(let b=0;b>b,A=[];for(let M=0;M<6;M++){let C=I[b][y[M]];x&&(C=Vn(C,S,S,s)),A.push(new Uint8Array(C.buffer,C.byteOffset,C.byteLength))}this._textureHelper.updateCubeTextures(A,T.underlyingResource,S,S,T.format,u,!1,0,0)}}else this.updateRawCubeTexture(f,m,i,s,u);f.isReady=!0,e==null||e.removePendingData(f),l&&l()}};return this._loadFile(a,g=>{p(g)},void 0,e==null?void 0:e.offlineProvider,!0,d),f};Se.prototype.createRawTexture3D=function(a,e,t,i,s,n,r,o,l=null,h=0,c=0){const f=new Et(this,10);return f.baseWidth=e,f.baseHeight=t,f.baseDepth=i,f.width=e,f.height=t,f.depth=i,f.format=s,f.type=h,f.generateMipMaps=n,f.samplingMode=o,f.is3D=!0,f._creationFlags=c,this._doNotHandleContextLost||(f._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(f,e,t,void 0,c),this.updateRawTexture3D(f,a,s,r,l,h),this._internalTexturesCache.push(f),f};Se.prototype.updateRawTexture3D=function(a,e,t,i,s=null,n=0){if(this._doNotHandleContextLost||(a._bufferView=e,a.format=t,a.invertY=i,a._compression=s),e){const r=a._hardwareTexture;t===4&&(e=Vn(e,a.width,a.height,n));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,a,a.width,a.height,a.depth,r.format,0,0,i,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0};Se.prototype.createRawTexture2DArray=function(a,e,t,i,s,n,r,o,l=null,h=0,c=0){const f=new Et(this,11);return f.baseWidth=e,f.baseHeight=t,f.baseDepth=i,f.width=e,f.height=t,f.depth=i,f.format=s,f.type=h,f.generateMipMaps=n,f.samplingMode=o,f.is2DArray=!0,f._creationFlags=c,this._doNotHandleContextLost||(f._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(f,e,t,i,c),this.updateRawTexture2DArray(f,a,s,r,l,h),this._internalTexturesCache.push(f),f};Se.prototype.updateRawTexture2DArray=function(a,e,t,i,s=null,n=0){if(this._doNotHandleContextLost||(a._bufferView=e,a.format=t,a.invertY=i,a._compression=s),e){const r=a._hardwareTexture;t===4&&(e=Vn(e,a.width,a.height,n));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,a,a.width,a.height,a.depth,r.format,0,0,i,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0};function Vn(a,e,t,i){let s,n=1;i===1?s=new Float32Array(e*t*4):i===2?(s=new Uint16Array(e*t*4),n=15360):i===7?s=new Uint32Array(e*t*4):s=new Uint8Array(e*t*4);for(let r=0;r0,a.is3D=h>0,a.depth=l||h,a.isReady=!0,a.samples=n,a.generateMipMaps=!1,a.samplingMode=i?2:1,a.type=1,a._comparisonFunction=s,a._cachedWrapU=0,a._cachedWrapV=0};Se.prototype.updateRenderTargetTextureSampleCount=function(a,e){return!a||!a.texture||a.samples===e||(e=Math.min(e,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(a.texture,e),a._depthStencilTexture&&(this._textureHelper.createMSAATexture(a._depthStencilTexture,e),a._depthStencilTexture.samples=e),a._samples=e,a.texture.samples=e),e};Se.prototype.createRenderTargetCubeTexture=function(a,e){var n;const t=this._createHardwareRenderTargetWrapper(!1,!0,a),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1,...e};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,t.label=(n=i.label)!=null?n:"RenderTargetWrapper",t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer;const s=new Et(this,5);return s.width=a,s.height=a,s.depth=0,s.isReady=!0,s.isCube=!0,s.samples=i.samples,s.generateMipMaps=i.generateMipMaps,s.samplingMode=i.samplingMode,s.type=i.type,s.format=i.format,this._internalTexturesCache.push(s),t.setTextures(s),(t._generateDepthBuffer||t._generateStencilBuffer)&&t.createDepthStencilTexture(0,i.samplingMode===void 0||i.samplingMode===2||i.samplingMode===2||i.samplingMode===3||i.samplingMode===3||i.samplingMode===5||i.samplingMode===6||i.samplingMode===7||i.samplingMode===11,t._generateStencilBuffer,t.samples),e&&e.createMipMaps&&!i.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s),e&&e.createMipMaps&&!i.generateMipMaps&&(s.generateMipMaps=!1),t};Se.prototype.setDepthStencilTexture=function(a,e,t,i){!t||!t.depthStencilTexture?this._setTexture(a,null,void 0,void 0,i):this._setTexture(a,t,!1,!0,i)};function Pv(a){return!!(a&&a.underlyingResource!==void 0)}Se.prototype.updateVideoTexture=function(a,e,t){var s;if(!a||a._isDisabled)return;this._videoTextureSupported===void 0&&(this._videoTextureSupported=!0);let i=a._hardwareTexture;if((s=a._hardwareTexture)!=null&&s.underlyingResource||(i=this._textureHelper.createGPUTextureForInternalTexture(a)),Pv(e)){if(e.isReady()){try{this._textureHelper.copyVideoToTexture(e,a,i.format,!t),a.generateMipMaps&&this._generateMipmaps(a)}catch{}a.isReady=!0}}else e&&this.createImageBitmap(e).then(n=>{this._textureHelper.updateTexture(n,a,a.width,a.height,a.depth,i.format,0,0,!t,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a),a.isReady=!0}).catch(()=>{a.isReady=!0})};var wv={value:()=>{}};function hc(){for(var a=0,e=arguments.length,t={},i;a=0&&(i=t.slice(s+1),t=t.slice(0,s)),t&&!e.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:i}})}nr.prototype=hc.prototype={constructor:nr,on:function(a,e){var t=this._,i=Dv(a+"",t),s,n=-1,r=i.length;if(arguments.length<2){for(;++n0)for(var t=new Array(s),i=0,s,n;i=0&&(e=a.slice(0,t))!=="xmlns"&&(a=a.slice(t+1)),yl.hasOwnProperty(e)?{space:yl[e],local:a}:a}function Ov(a){return function(){var e=this.ownerDocument,t=this.namespaceURI;return t===Ia&&e.documentElement.namespaceURI===Ia?e.createElement(a):e.createElementNS(t,a)}}function Lv(a){return function(){return this.ownerDocument.createElementNS(a.space,a.local)}}function yo(a){var e=Gr(a);return(e.local?Lv:Ov)(e)}function Bv(){}function To(a){return a==null?Bv:function(){return this.querySelector(a)}}function Nv(a){typeof a!="function"&&(a=To(a));for(var e=this._groups,t=e.length,i=new Array(t),s=0;s=I&&(I=x+1);!(y=_[I])&&++I=0;)(r=i[s])&&(n&&r.compareDocumentPosition(n)^4&&n.parentNode.insertBefore(r,n),n=r);return this}function l2(a){a||(a=h2);function e(u,f){return u&&f?a(u.__data__,f.__data__):!u-!f}for(var t=this._groups,i=t.length,s=new Array(i),n=0;ne?1:a>=e?0:NaN}function c2(){var a=arguments[0];return arguments[0]=this,a.apply(null,arguments),this}function u2(){return Array.from(this)}function f2(){for(var a=this._groups,e=0,t=a.length;e1?this.each((e==null?S2:typeof e=="function"?I2:E2)(a,e,t==null?"":t)):nn(this.node(),a)}function nn(a,e){return a.style.getPropertyValue(e)||pc(a).getComputedStyle(a,null).getPropertyValue(e)}function C2(a){return function(){delete this[a]}}function M2(a,e){return function(){this[a]=e}}function R2(a,e){return function(){var t=e.apply(this,arguments);t==null?delete this[a]:this[a]=t}}function P2(a,e){return arguments.length>1?this.each((e==null?C2:typeof e=="function"?R2:M2)(a,e)):this.node()[a]}function _c(a){return a.trim().split(/^|\s+/)}function So(a){return a.classList||new gc(a)}function gc(a){this._node=a,this._names=_c(a.getAttribute("class")||"")}gc.prototype={add:function(a){var e=this._names.indexOf(a);e<0&&(this._names.push(a),this._node.setAttribute("class",this._names.join(" ")))},remove:function(a){var e=this._names.indexOf(a);e>=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(a){return this._names.indexOf(a)>=0}};function mc(a,e){for(var t=So(a),i=-1,s=e.length;++i=0&&(t=e.slice(i+1),e=e.slice(0,i)),{type:e,name:t}})}function nx(a){return function(){var e=this.__on;if(e){for(var t=0,i=-1,s=e.length,n;t>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):t===8?Zn(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):t===4?Zn(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|e&240,((e&15)<<4|e&15)/255):null):(e=px.exec(a))?new ni(e[1],e[2],e[3],1):(e=_x.exec(a))?new ni(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=gx.exec(a))?Zn(e[1],e[2],e[3],e[4]):(e=mx.exec(a))?Zn(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=vx.exec(a))?Ml(e[1],e[2]/100,e[3]/100,1):(e=xx.exec(a))?Ml(e[1],e[2]/100,e[3]/100,e[4]):Tl.hasOwnProperty(a)?Il(Tl[a]):a==="transparent"?new ni(NaN,NaN,NaN,0):null}function Il(a){return new ni(a>>16&255,a>>8&255,a&255,1)}function Zn(a,e,t,i){return i<=0&&(a=e=t=NaN),new ni(a,e,t,i)}function Tx(a){return a instanceof zn||(a=wn(a)),a?(a=a.rgb(),new ni(a.r,a.g,a.b,a.opacity)):new ni}function Aa(a,e,t,i){return arguments.length===1?Tx(a):new ni(a,e,t,i==null?1:i)}function ni(a,e,t,i){this.r=+a,this.g=+e,this.b=+t,this.opacity=+i}Eo(ni,Aa,Tc(zn,{brighter(a){return a=a==null?vr:Math.pow(vr,a),new ni(this.r*a,this.g*a,this.b*a,this.opacity)},darker(a){return a=a==null?Rn:Math.pow(Rn,a),new ni(this.r*a,this.g*a,this.b*a,this.opacity)},rgb(){return this},clamp(){return new ni(Fs(this.r),Fs(this.g),Fs(this.b),xr(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Al,formatHex:Al,formatHex8:Sx,formatRgb:Cl,toString:Cl}));function Al(){return"#".concat(Rs(this.r)).concat(Rs(this.g)).concat(Rs(this.b))}function Sx(){return"#".concat(Rs(this.r)).concat(Rs(this.g)).concat(Rs(this.b)).concat(Rs((isNaN(this.opacity)?1:this.opacity)*255))}function Cl(){const a=xr(this.opacity);return"".concat(a===1?"rgb(":"rgba(").concat(Fs(this.r),", ").concat(Fs(this.g),", ").concat(Fs(this.b)).concat(a===1?")":", ".concat(a,")"))}function xr(a){return isNaN(a)?1:Math.max(0,Math.min(1,a))}function Fs(a){return Math.max(0,Math.min(255,Math.round(a)||0))}function Rs(a){return a=Fs(a),(a<16?"0":"")+a.toString(16)}function Ml(a,e,t,i){return i<=0?a=e=t=NaN:t<=0||t>=1?a=e=NaN:e<=0&&(a=NaN),new Pi(a,e,t,i)}function Sc(a){if(a instanceof Pi)return new Pi(a.h,a.s,a.l,a.opacity);if(a instanceof zn||(a=wn(a)),!a)return new Pi;if(a instanceof Pi)return a;a=a.rgb();var e=a.r/255,t=a.g/255,i=a.b/255,s=Math.min(e,t,i),n=Math.max(e,t,i),r=NaN,o=n-s,l=(n+s)/2;return o?(e===n?r=(t-i)/o+(t0&&l<1?0:r,new Pi(r,o,l,a.opacity)}function Ex(a,e,t,i){return arguments.length===1?Sc(a):new Pi(a,e,t,i==null?1:i)}function Pi(a,e,t,i){this.h=+a,this.s=+e,this.l=+t,this.opacity=+i}Eo(Pi,Ex,Tc(zn,{brighter(a){return a=a==null?vr:Math.pow(vr,a),new Pi(this.h,this.s,this.l*a,this.opacity)},darker(a){return a=a==null?Rn:Math.pow(Rn,a),new Pi(this.h,this.s,this.l*a,this.opacity)},rgb(){var a=this.h%360+(this.h<0)*360,e=isNaN(a)||isNaN(this.s)?0:this.s,t=this.l,i=t+(t<.5?t:1-t)*e,s=2*t-i;return new ni(oa(a>=240?a-240:a+120,s,i),oa(a,s,i),oa(a<120?a+240:a-120,s,i),this.opacity)},clamp(){return new Pi(Rl(this.h),Qn(this.s),Qn(this.l),xr(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const a=xr(this.opacity);return"".concat(a===1?"hsl(":"hsla(").concat(Rl(this.h),", ").concat(Qn(this.s)*100,"%, ").concat(Qn(this.l)*100,"%").concat(a===1?")":", ".concat(a,")"))}}));function Rl(a){return a=(a||0)%360,a<0?a+360:a}function Qn(a){return Math.max(0,Math.min(1,a||0))}function oa(a,e,t){return(a<60?e+(t-e)*a/60:a<180?t:a<240?e+(t-e)*(240-a)/60:e)*255}const Ec=a=>()=>a;function Ix(a,e){return function(t){return a+t*e}}function Ax(a,e,t){return a=Math.pow(a,t),e=Math.pow(e,t)-a,t=1/t,function(i){return Math.pow(a+i*e,t)}}function Cx(a){return(a=+a)==1?Ic:function(e,t){return t-e?Ax(e,t,a):Ec(isNaN(e)?t:e)}}function Ic(a,e){var t=e-a;return t?Ix(a,t):Ec(isNaN(a)?e:a)}const Pl=function a(e){var t=Cx(e);function i(s,n){var r=t((s=Aa(s)).r,(n=Aa(n)).r),o=t(s.g,n.g),l=t(s.b,n.b),h=Ic(s.opacity,n.opacity);return function(c){return s.r=r(c),s.g=o(c),s.b=l(c),s.opacity=h(c),s+""}}return i.gamma=a,i}(1);function _s(a,e){return a=+a,e=+e,function(t){return a*(1-t)+e*t}}var Ca=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,la=new RegExp(Ca.source,"g");function Mx(a){return function(){return a}}function Rx(a){return function(e){return a(e)+""}}function Px(a,e){var t=Ca.lastIndex=la.lastIndex=0,i,s,n,r=-1,o=[],l=[];for(a=a+"",e=e+"";(i=Ca.exec(a))&&(s=la.exec(e));)(n=s.index)>t&&(n=e.slice(t,n),o[r]?o[r]+=n:o[++r]=n),(i=i[0])===(s=s[0])?o[r]?o[r]+=s:o[++r]=s:(o[++r]=null,l.push({i:r,x:_s(i,s)})),t=la.lastIndex;return t180?c+=360:c-h>180&&(h+=360),f.push({i:u.push(s(u)+"rotate(",null,i)-2,x:_s(h,c)})):c&&u.push(s(u)+"rotate("+c+i)}function o(h,c,u,f){h!==c?f.push({i:u.push(s(u)+"skewX(",null,i)-2,x:_s(h,c)}):c&&u.push(s(u)+"skewX("+c+i)}function l(h,c,u,f,d,p){if(h!==u||c!==f){var g=d.push(s(d)+"scale(",null,",",null,")");p.push({i:g-4,x:_s(h,u)},{i:g-2,x:_s(c,f)})}else(u!==1||f!==1)&&d.push(s(d)+"scale("+u+","+f+")")}return function(h,c){var u=[],f=[];return h=a(h),c=a(c),n(h.translateX,h.translateY,c.translateX,c.translateY,u,f),r(h.rotate,c.rotate,u,f),o(h.skewX,c.skewX,u,f),l(h.scaleX,h.scaleY,c.scaleX,c.scaleY,u,f),h=c=null,function(d){for(var p=-1,g=f.length,_;++p=0&&a._call.call(void 0,e),a=a._next;--rn}function Dl(){Os=(yr=Dn.now())+zr,rn=gn=0;try{Bx()}finally{rn=0,Ux(),Os=0}}function Nx(){var a=Dn.now(),e=a-yr;e>Mc&&(zr-=e,yr=a)}function Ux(){for(var a,e=br,t,i=1/0;e;)e._call?(i>e._time&&(i=e._time),a=e,e=e._next):(t=e._next,e._next=null,e=a?a._next=t:br=t);mn=a,Ra(i)}function Ra(a){if(!rn){gn&&(gn=clearTimeout(gn));var e=a-Os;e>24?(a<1/0&&(gn=setTimeout(Dl,a-Dn.now()-zr)),pn&&(pn=clearInterval(pn))):(pn||(yr=Dn.now(),pn=setInterval(Nx,Mc)),rn=1,Rc(Dl))}}function Fl(a,e,t){var i=new Tr;return e=e==null?0:+e,i.restart(s=>{i.stop(),a(s+e)},e,t),i}var kx=hc("start","end","cancel","interrupt"),Vx=[],wc=0,Ol=1,Pa=2,rr=3,Ll=4,wa=5,ar=6;function Wr(a,e,t,i,s,n){var r=a.__transition;if(!r)a.__transition={};else if(t in r)return;Gx(a,t,{name:e,index:i,group:s,on:kx,tween:Vx,time:n.time,delay:n.delay,duration:n.duration,ease:n.ease,timer:null,state:wc})}function Ao(a,e){var t=Li(a,e);if(t.state>wc)throw new Error("too late; already scheduled");return t}function Hi(a,e){var t=Li(a,e);if(t.state>rr)throw new Error("too late; already running");return t}function Li(a,e){var t=a.__transition;if(!t||!(t=t[e]))throw new Error("transition not found");return t}function Gx(a,e,t){var i=a.__transition,s;i[e]=t,t.timer=Pc(n,0,t.time);function n(h){t.state=Ol,t.timer.restart(r,t.delay,t.time),t.delay<=h&&r(h-t.delay)}function r(h){var c,u,f,d;if(t.state!==Ol)return l();for(c in i)if(d=i[c],d.name===t.name){if(d.state===rr)return Fl(r);d.state===Ll?(d.state=ar,d.timer.stop(),d.on.call("interrupt",a,a.__data__,d.index,d.group),delete i[c]):+cPa&&i.state=0&&(e=e.slice(0,t)),!e||e==="start"})}function v3(a,e,t){var i,s,n=m3(e)?Ao:Hi;return function(){var r=n(this,a),o=r.on;o!==i&&(s=(i=o).copy()).on(e,t),r.on=s}}function x3(a,e){var t=this._id;return arguments.length<2?Li(this.node(),t).on.on(a):this.each(v3(t,a,e))}function b3(a){return function(){var e=this.parentNode;for(var t in this.__transition)if(+t!==a)return;e&&e.removeChild(this)}}function y3(){return this.on("end.remove",b3(this._id))}function T3(a){var e=this._name,t=this._id;typeof a!="function"&&(a=To(a));for(var i=this._groups,s=i.length,n=new Array(s),r=0;rn?n:Math.floor(r);const o=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE,l=a.uvs,h=a.colors,c=[],u=[],f=[],d=[],p=[],g=[],_=[],m=[];let x;const I=[],T=[];let y,b,S;if(e.length<2){const Z=[],Ee=[];for(b=0;b0&&(z=w[S].subtract(w[S-1]).length(),L=z+_[y],p[y].push(L),_[y]=L),S++;i&&(S--,c.push(w[0].x,w[0].y,w[0].z),z=w[S].subtract(w[0]).length(),L=z+_[y],p[y].push(L),_[y]=L),I[y]=P+M,T[y]=A,A+=P+M}let G,H,ce=null,J=null;for(b=0;b{let p=i[0].length;const g=o;let _=0;const m=g._originalBuilderSideOrientation===F.DOUBLESIDE?2:1;for(let x=1;x<=m;++x)for(let I=0;ILs(a,{pathArray:e,closeArray:t,closePath:i,offset:s,updatable:r,sideOrientation:o,instance:l},n);function Bc(a){const e=[],t=[],i=[],s=[],n=a.radius||.5,r=a.tessellation||64,o=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,l=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE;e.push(0,0,0),s.push(.5,.5);const h=Math.PI*2*o,c=o===1?h/r:h/(r-1);let u=0;for(let p=0;pNc(a,{radius:e,tessellation:t,sideOrientation:n,updatable:s},i);F._GroundMeshParser=(a,e)=>Wn.Parse(a,e);class Wn extends F{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);const i=this;i.createOrUpdateSubmeshesOctree&&i.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),s=N.Matrix[5];i.invertToRef(s);const n=N.Vector3[8];if(v.TransformCoordinatesFromFloatsToRef(e,0,t,s,n),e=n.x,t=n.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const r=this._getFacetAt(e,t),o=-(r.x*e+r.z*t+r.w)/r.y;return v.TransformCoordinatesFromFloatsToRef(0,o,0,i,n),n.y}getNormalAtCoordinates(e,t){const i=new v(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),n=N.Matrix[5];s.invertToRef(n);const r=N.Vector3[8];if(v.TransformCoordinatesFromFloatsToRef(e,0,t,n,r),e=r.x,t=r.z,ethis._maxX||tthis._maxZ)return this;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return v.TransformNormalFromFloatsToRef(o.x,o.y,o.z,s,i),this}updateCoordinateHeights(){return(!this._heightQuads||this._heightQuads.length==0)&&this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),s=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),n=this._heightQuads[s*this._subdivisionsX+i];let r;return ta.maxHeight){h=!0;const u=a.maxHeight;a.maxHeight=a.minHeight,a.minHeight=u}for(n=0;n<=a.subdivisions;n++)for(r=0;r<=a.subdivisions;r++){const u=new v(r*a.width/a.subdivisions-a.width/2,0,(a.subdivisions-n)*a.height/a.subdivisions-a.height/2),f=(u.x+a.width/2)/a.width*(a.bufferWidth-1)|0,d=(1-(u.z+a.height/2)/a.height)*(a.bufferHeight-1)|0,p=(f+d*a.bufferWidth)*4;let g=a.buffer[p]/255,_=a.buffer[p+1]/255,m=a.buffer[p+2]/255;const x=a.buffer[p+3]/255;h&&(g=1-g,_=1-_,m=1-m);const I=g*o.r+_*o.g+m*o.b;x>=l?u.y=a.minHeight+(a.maxHeight-a.minHeight)*I:u.y=a.minHeight-Ne,a.heightBuffer&&(a.heightBuffer[n*(a.subdivisions+1)+r]=u.y),t.push(u.x,u.y,u.z),i.push(0,0,0),s.push(r/a.subdivisions,1-n/a.subdivisions)}for(n=0;n=a.minHeight,_=t[f*3+1]>=a.minHeight,m=t[d*3+1]>=a.minHeight;g&&_&&m&&(e.push(u),e.push(f),e.push(d)),t[p*3+1]>=a.minHeight&&g&&m&&(e.push(p),e.push(u),e.push(d))}j.ComputeNormals(t,e,i);const c=new j;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function Gc(a,e={},t){const i=new Wn(a,t);return i._setReady(!1),i._subdivisionsX=e.subdivisionsX||e.subdivisions||1,i._subdivisionsY=e.subdivisionsY||e.subdivisions||1,i._width=e.width||1,i._height=e.height||1,i._maxX=i._width/2,i._maxZ=i._height/2,i._minX=-i._maxX,i._minZ=-i._maxZ,Uc(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function zc(a,e,t=null){const i=new F(a,t);return kc(e).applyToMesh(i,e.updatable),i}function Wc(a,e,t={},i=null){const s=t.width||10,n=t.height||10,r=t.subdivisions||1,o=t.minHeight||0,l=t.maxHeight||1,h=t.colorFilter||new pe(.3,.59,.11),c=t.alphaFilter||0,u=t.updatable,f=t.onReady;i=i||Ce.LastCreatedScene;const d=new Wn(a,i);d._subdivisionsX=r,d._subdivisionsY=r,d._width=s,d._height=n,d._maxX=d._width/2,d._maxZ=d._height/2,d._minX=-d._maxX,d._minZ=-d._maxZ,d._setReady(!1);let p;t.passHeightBufferInCallback&&(p=new Float32Array((r+1)*(r+1)));const g=(_,m,x)=>{Vc({width:s,height:n,subdivisions:r,minHeight:o,maxHeight:l,colorFilter:h,buffer:_,bufferWidth:m,bufferHeight:x,alphaFilter:c,heightBuffer:p}).applyToMesh(d,u),f&&f(d,p),d._setReady(!0)};if(typeof e=="string"){const _=m=>{const x=m.width,I=m.height;if(i.isDisposed)return;const T=i==null?void 0:i.getEngine().resizeImageBitmap(m,x,I);g(T,x,I)};ee.LoadImage(e,_,t.onError?t.onError:()=>{},i.offlineProvider)}else g(e.data,e.width,e.height);return d}j.CreateGround=Uc;j.CreateTiledGround=kc;j.CreateGroundFromHeightMap=Vc;F.CreateGround=(a,e,t,i,s,n)=>Gc(a,{width:e,height:t,subdivisions:i,updatable:n},s);F.CreateTiledGround=(a,e,t,i,s,n,r,o,l)=>zc(a,{xmin:e,zmin:t,xmax:i,zmax:s,subdivisions:n,precision:r,updatable:l},o);F.CreateGroundFromHeightMap=(a,e,t,i,s,n,r,o,l,h,c)=>Wc(a,e,{width:t,height:i,subdivisions:s,minHeight:n,maxHeight:r,updatable:l,onReady:h,alphaFilter:c},o);function Xc(a){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],s=[];let n=[];const r=a.width||a.size||1,o=a.height||a.size||1,l=a.depth||a.size||1,h=a.wrap||!1;let c=a.topBaseAt===void 0?1:a.topBaseAt,u=a.bottomBaseAt===void 0?0:a.bottomBaseAt;c=(c+4)%4,u=(u+4)%4;const f=[2,0,3,1],d=[2,0,1,3];let p=f[c],g=d[u],_=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-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(h){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],_=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let S=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],A=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const M=[17,18,19,16],C=[22,23,20,21];for(;p>0;)S.unshift(S.pop()),M.unshift(M.pop()),p--;for(;g>0;)A.unshift(A.pop()),C.unshift(C.pop()),g--;S=S.flat(),A=A.flat(),_=_.concat(S).concat(A),t.push(M[0],M[2],M[3],M[0],M[1],M[2]),t.push(C[0],C[2],C[3],C[0],C[1],C[2])}const m=[r/2,o/2,l/2];n=_.reduce((S,A,M)=>S.concat(A*m[M%3]),[]);const x=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE,I=a.faceUV||new Array(6),T=a.faceColors,y=[];for(let S=0;S<6;S++)I[S]===void 0&&(I[S]=new Pe(0,0,1,1)),T&&T[S]===void 0&&(T[S]=new X(1,1,1,1));for(let S=0;S<6;S++)if(s.push(I[S].z,Le.UseOpenGLOrientationForUV?1-I[S].w:I[S].w),s.push(I[S].x,Le.UseOpenGLOrientationForUV?1-I[S].w:I[S].w),s.push(I[S].x,Le.UseOpenGLOrientationForUV?1-I[S].y:I[S].y),s.push(I[S].z,Le.UseOpenGLOrientationForUV?1-I[S].y:I[S].y),T)for(let A=0;A<4;A++)y.push(T[S].r,T[S].g,T[S].b,T[S].a);j._ComputeSides(x,n,t,i,s,a.frontUVs,a.backUVs);const b=new j;if(b.indices=t,b.positions=n,b.normals=i,b.uvs=s,T){const S=x===j.DOUBLESIDE?y.concat(y):y;b.colors=S}return b}function Hc(a,e={},t=null){const i=new F(a,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Xc(e).applyToMesh(i,e.updatable),i}j.CreateBox=Xc;F.CreateBox=(a,e,t=null,i,s)=>Hc(a,{size:e,sideOrientation:s,updatable:i},t);function Tn(a){const e=a.pattern||F.NO_FLIP,t=a.tileWidth||a.tileSize||1,i=a.tileHeight||a.tileSize||1,s=a.alignHorizontal||0,n=a.alignVertical||0,r=a.width||a.size||1,o=Math.floor(r/t);let l=r-o*t;const h=a.height||a.size||1,c=Math.floor(h/i);let u=h-c*i;const f=t*o/2,d=i*c/2;let p=0,g=0,_=0,m=0,x=0,I=0;if(l>0||u>0){switch(_=-f,m=-d,x=f,I=d,s){case F.CENTER:l/=2,_-=l,x+=l;break;case F.LEFT:x+=l,p=-l/2;break;case F.RIGHT:_-=l,p=l/2;break}switch(n){case F.CENTER:u/=2,m-=u,I+=u;break;case F.BOTTOM:I+=u,g=-u/2;break;case F.TOP:m-=u,g=u/2;break}}const T=[],y=[],b=[];b[0]=[0,0,1,0,1,1,0,1],b[1]=[0,0,1,0,1,1,0,1],(e===F.ROTATE_TILE||e===F.ROTATE_ROW)&&(b[1]=[1,1,0,1,0,0,1,0]),(e===F.FLIP_TILE||e===F.FLIP_ROW)&&(b[1]=[1,0,0,0,0,1,1,1]),(e===F.FLIP_N_ROTATE_TILE||e===F.FLIP_N_ROTATE_ROW)&&(b[1]=[0,1,1,1,1,0,0,0]);let S=[];const A=[],M=[];let C=0;for(let L=0;L0||u>0){const L=u>0&&(n===F.CENTER||n===F.TOP),G=u>0&&(n===F.CENTER||n===F.BOTTOM),H=l>0&&(s===F.CENTER||s===F.RIGHT),ce=l>0&&(s===F.CENTER||s===F.LEFT);let J=[],W,V,R,k;if(L&&H&&(T.push(_+p,m+g,0),T.push(-f+p,m+g,0),T.push(-f+p,m+u+g,0),T.push(_+p,m+u+g,0),M.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,W=1-l/t,V=1-u/i,R=1,k=1,J=[W,V,R,V,R,k,W,k],e===F.ROTATE_ROW&&(J=[1-W,1-V,1-R,1-V,1-R,1-k,1-W,1-k]),e===F.FLIP_ROW&&(J=[1-W,V,1-R,V,1-R,k,1-W,k]),e===F.FLIP_N_ROTATE_ROW&&(J=[W,1-V,R,1-V,R,1-k,W,1-k]),S=S.concat(J),A.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),y.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),L&&ce&&(T.push(f+p,m+g,0),T.push(x+p,m+g,0),T.push(x+p,m+u+g,0),T.push(f+p,m+u+g,0),M.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,W=0,V=1-u/i,R=l/t,k=1,J=[W,V,R,V,R,k,W,k],(e===F.ROTATE_ROW||e===F.ROTATE_TILE&&o%2===0)&&(J=[1-W,1-V,1-R,1-V,1-R,1-k,1-W,1-k]),(e===F.FLIP_ROW||e===F.FLIP_TILE&&o%2===0)&&(J=[1-W,V,1-R,V,1-R,k,1-W,k]),(e===F.FLIP_N_ROTATE_ROW||e===F.FLIP_N_ROTATE_TILE&&o%2===0)&&(J=[W,1-V,R,1-V,R,1-k,W,1-k]),S=S.concat(J),A.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),y.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),G&&H&&(T.push(_+p,d+g,0),T.push(-f+p,d+g,0),T.push(-f+p,I+g,0),T.push(_+p,I+g,0),M.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,W=1-l/t,V=0,R=1,k=u/i,J=[W,V,R,V,R,k,W,k],(e===F.ROTATE_ROW&&c%2===1||e===F.ROTATE_TILE&&c%1===0)&&(J=[1-W,1-V,1-R,1-V,1-R,1-k,1-W,1-k]),(e===F.FLIP_ROW&&c%2===1||e===F.FLIP_TILE&&c%2===0)&&(J=[1-W,V,1-R,V,1-R,k,1-W,k]),(e===F.FLIP_N_ROTATE_ROW&&c%2===1||e===F.FLIP_N_ROTATE_TILE&&c%2===0)&&(J=[W,1-V,R,1-V,R,1-k,W,1-k]),S=S.concat(J),A.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),y.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),G&&ce&&(T.push(f+p,d+g,0),T.push(x+p,d+g,0),T.push(x+p,I+g,0),T.push(f+p,I+g,0),M.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,W=0,V=0,R=l/t,k=u/i,J=[W,V,R,V,R,k,W,k],(e===F.ROTATE_ROW&&c%2===1||e===F.ROTATE_TILE&&(c+o)%2===1)&&(J=[1-W,1-V,1-R,1-V,1-R,1-k,1-W,1-k]),(e===F.FLIP_ROW&&c%2===1||e===F.FLIP_TILE&&(c+o)%2===1)&&(J=[1-W,V,1-R,V,1-R,k,1-W,k]),(e===F.FLIP_N_ROTATE_ROW&&c%2===1||e===F.FLIP_N_ROTATE_TILE&&(c+o)%2===1)&&(J=[W,1-V,R,1-V,R,1-k,W,1-k]),S=S.concat(J),A.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),y.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),L){const Y=[];W=0,V=1-u/i,R=1,k=1,Y[0]=[W,V,R,V,R,k,W,k],Y[1]=[W,V,R,V,R,k,W,k],(e===F.ROTATE_TILE||e===F.ROTATE_ROW)&&(Y[1]=[1-W,1-V,1-R,1-V,1-R,1-k,1-W,1-k]),(e===F.FLIP_TILE||e===F.FLIP_ROW)&&(Y[1]=[1-W,V,1-R,V,1-R,k,1-W,k]),(e===F.FLIP_N_ROTATE_TILE||e===F.FLIP_N_ROTATE_ROW)&&(Y[1]=[W,1-V,R,1-V,R,1-k,W,1-k]);for(let he=0;heY+w)),w+=S[R].length,i)for(let Y=0;Y<4;Y++)b.push(i[R].r,i[R].g,i[R].b,i[R].a)}const P=new v(0,0,g),z=O.RotationY(Math.PI);x=S[0].map(R=>v.TransformNormal(R,z).add(P)).map(R=>[R.x,R.y,R.z]).reduce((R,k)=>R.concat(k),[]),I=A[0].map(R=>v.TransformNormal(R,z)).map(R=>[R.x,R.y,R.z]).reduce((R,k)=>R.concat(k),[]),x=x.concat(S[1].map(R=>R.subtract(P)).map(R=>[R.x,R.y,R.z]).reduce((R,k)=>R.concat(k),[])),I=I.concat(A[1].map(R=>[R.x,R.y,R.z]).reduce((R,k)=>R.concat(k),[]));const L=new v(d,0,0),G=O.RotationY(-Math.PI/2);x=x.concat(S[2].map(R=>v.TransformNormal(R,G).add(L)).map(R=>[R.x,R.y,R.z]).reduce((R,k)=>R.concat(k),[])),I=I.concat(A[2].map(R=>v.TransformNormal(R,G)).map(R=>[R.x,R.y,R.z]).reduce((R,k)=>R.concat(k),[]));const H=O.RotationY(Math.PI/2);x=x.concat(S[3].map(R=>v.TransformNormal(R,H).subtract(L)).map(R=>[R.x,R.y,R.z]).reduce((R,k)=>R.concat(k),[])),I=I.concat(A[3].map(R=>v.TransformNormal(R,H)).map(R=>[R.x,R.y,R.z]).reduce((R,k)=>R.concat(k),[]));const ce=new v(0,p,0),J=O.RotationX(Math.PI/2);x=x.concat(S[4].map(R=>v.TransformNormal(R,J).add(ce)).map(R=>[R.x,R.y,R.z]).reduce((R,k)=>R.concat(k),[])),I=I.concat(A[4].map(R=>v.TransformNormal(R,J)).map(R=>[R.x,R.y,R.z]).reduce((R,k)=>R.concat(k),[]));const W=O.RotationX(-Math.PI/2);x=x.concat(S[5].map(R=>v.TransformNormal(R,W).subtract(ce)).map(R=>[R.x,R.y,R.z]).reduce((R,k)=>R.concat(k),[])),I=I.concat(A[5].map(R=>v.TransformNormal(R,W)).map(R=>[R.x,R.y,R.z]).reduce((R,k)=>R.concat(k),[])),j._ComputeSides(f,x,y,I,T);const V=new j;if(V.indices=y,V.positions=x,V.normals=I,V.uvs=T,i){const R=f===j.DOUBLESIDE?b.concat(b):b;V.colors=R}return V}function q3(a,e,t=null){const i=new F(a,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Kc(e).applyToMesh(i,e.updatable),i}j.CreateTiledBox=Kc;function Yc(a){const e=(a.segments||32)|0,t=a.diameterX||a.diameter||1,i=a.diameterY||a.diameter||1,s=a.diameterZ||a.diameter||1,n=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,r=a.slice&&a.slice<=0?1:a.slice||1,o=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE,l=!!a.dedupTopBottomIndices,h=new v(t/2,i/2,s/2),c=2+e,u=2*c,f=[],d=[],p=[],g=[];for(let m=0;m<=c;m++){const x=m/c,I=x*Math.PI*r;for(let T=0;T<=u;T++){const y=T/u,b=y*Math.PI*2*n,S=O.RotationZ(-I),A=O.RotationY(b),M=v.TransformCoordinates(v.Up(),S),C=v.TransformCoordinates(M,A),w=C.multiply(h),P=C.divide(h).normalize();d.push(w.x,w.y,w.z),p.push(P.x,P.y,P.z),g.push(y,Le.UseOpenGLOrientationForUV?1-x:x)}if(m>0){const T=d.length/3;for(let y=T-2*(u+1);y+u+21&&(f.push(y),f.push(y+1),f.push(y+u+1)),(mqc(a,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:n,updatable:s},i);function $c(a){const e=a.height||2;let t=a.diameterTop===0?0:a.diameterTop||a.diameter||1,i=a.diameterBottom===0?0:a.diameterBottom||a.diameter||1;t=t||1e-5,i=i||1e-5;const s=(a.tessellation||24)|0,n=(a.subdivisions||1)|0,r=!!a.hasRings,o=!!a.enclose,l=a.cap===0?0:a.cap||F.CAP_ALL,h=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,c=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE,u=a.faceUV||new Array(3),f=a.faceColors,d=h!==1&&o?2:0,p=r?n:1,g=2+(1+d)*p;let _;for(_=0;_{const xe=ue?t/2:i/2;if(xe===0)return;let ae,Me,ke;const Z=ue?u[g-1]:u[0];let Ee=null;f&&(Ee=ue?f[g-1]:f[0]);const Oe=x.length/3,He=ue?e/2:-e/2,je=new v(0,He,0);x.push(je.x,je.y,je.z),I.push(0,ue?1:-1,0);const Ct=Z.y+(Z.w-Z.y)*.5;T.push(Z.x+(Z.z-Z.x)*.5,Le.UseOpenGLOrientationForUV?1-Ct:Ct),Ee&&y.push(Ee.r,Ee.g,Ee.b,Ee.a);const wt=new fe(.5,.5);for(ke=0;ke<=s;ke++){ae=Math.PI*2*ke*h/s;const ri=Math.cos(-ae),ei=Math.sin(-ae);Me=new v(ri*xe,He,ei*xe);const Ht=new fe(ri*wt.x+.5,ei*wt.y+.5);x.push(Me.x,Me.y,Me.z),I.push(0,ue?1:-1,0);const Bi=Z.y+(Z.w-Z.y)*Ht.y;T.push(Z.x+(Z.z-Z.x)*Ht.x,Le.UseOpenGLOrientationForUV?1-Bi:Bi),Ee&&y.push(Ee.r,Ee.g,Ee.b,Ee.a)}for(ke=0;ke((r===void 0||!(r instanceof Qe))&&(r!==void 0&&(l=o||F.DEFAULTSIDE,o=r),r=n,n=1),jc(a,{height:e,diameterTop:t,diameterBottom:i,tessellation:s,subdivisions:n,sideOrientation:l,updatable:o},r));function Zc(a){const e=[],t=[],i=[],s=[],n=a.diameter||1,r=a.thickness||.5,o=(a.tessellation||16)|0,l=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE,h=o+1;for(let u=0;u<=o;u++){const f=u/o,d=u*Math.PI*2/o-Math.PI/2,p=O.Translation(n/2,0,0).multiply(O.RotationY(d));for(let g=0;g<=o;g++){const _=1-g/o,m=g*Math.PI*2/o+Math.PI,x=Math.cos(m),I=Math.sin(m);let T=new v(x,I,0),y=T.scale(r/2);const b=new fe(f,_);y=v.TransformCoordinates(y,p),T=v.TransformNormal(T,p),t.push(y.x,y.y,y.z),i.push(T.x,T.y,T.z),s.push(b.x,Le.UseOpenGLOrientationForUV?1-b.y:b.y);const S=(u+1)%h,A=(g+1)%h;e.push(u*h+g),e.push(u*h+A),e.push(S*h+g),e.push(u*h+A),e.push(S*h+A),e.push(S*h+g)}}j._ComputeSides(l,t,e,i,s,a.frontUVs,a.backUVs);const c=new j;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function Qc(a,e={},t){const i=new F(a,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Zc(e).applyToMesh(i,e.updatable),i}j.CreateTorus=Zc;F.CreateTorus=(a,e,t,i,s,n,r)=>Qc(a,{diameter:e,thickness:t,tessellation:i,sideOrientation:r,updatable:n},s);function Jc(a){const e=[],t=[],i=[],s=[],n=a.radius||2,r=a.tube||.5,o=a.radialSegments||32,l=a.tubularSegments||32,h=a.p||2,c=a.q||3,u=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE,f=_=>{const m=Math.cos(_),x=Math.sin(_),I=c/h*_,T=Math.cos(I),y=n*(2+T)*.5*m,b=n*(2+T)*x*.5,S=n*Math.sin(I)*.5;return new v(y,b,S)};let d,p;for(d=0;d<=o;d++){const m=d%o/o*2*h*Math.PI,x=f(m),I=f(m+.01),T=I.subtract(x);let y=I.add(x);const b=v.Cross(T,y);for(y=v.Cross(b,T),b.normalize(),y.normalize(),p=0;peu(a,{radius:e,tube:t,radialSegments:i,tubularSegments:s,p:n,q:r,sideOrientation:h,updatable:l},o);function tu(a){const e=[],t=[],i=a.lines,s=a.colors,n=[];let r=0;for(let l=0;l0&&(e.push(r-1),e.push(r)),r++}}const o=new j;return o.indices=e,o.positions=t,s&&(o.colors=n),o}function iu(a){const e=a.dashSize||3,t=a.gapSize||1,i=a.dashNb||200,s=a.points,n=[],r=[],o=v.Zero();let l=0,h=0,c=0,u=0,f=0,d=0,p=0;for(p=0;p{const u=v.Zero(),f=c.length/6;let d=0,p=0,g=0,_=0,m=0,x=0,I=0,T=0;for(I=0;Inu(a,{points:e,updatable:i,instance:s},t);F.CreateDashedLines=(a,e,t,i,s,n=null,r,o)=>ru(a,{points:e,dashSize:t,gapSize:i,dashNb:s,updatable:r,instance:o},n);class $3 extends fe{constructor(e,t){super(e.x,e.y),this.index=t}}class ha{constructor(){this.elements=[]}add(e){const t=[];return e.forEach(i=>{const s=new $3(i,this.elements.length);t.push(s),this.elements.push(s)}),t}computeBounds(){const e=new fe(this.elements[0].x,this.elements[0].y),t=new fe(this.elements[0].x,this.elements[0].y);return this.elements.forEach(i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class j3{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){this._points=new ha,this._outlinepoints=new ha,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||Ce.LastCreatedScene;let n;t instanceof Mr?n=t.getPoints():n=t,this._addToepoint(n),this._points.add(n),this._outlinepoints.add(n),typeof this.bjsEarcut>"u"&&U.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new ha;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const s=new F(this._name,this._scene),n=this.buildVertexData(t,i);return s.setVerticesData(E.PositionKind,n.positions,e),s.setVerticesData(E.NormalKind,n.normals,e),s.setVerticesData(E.UVKind,n.uvs,e),s.setIndices(n.indices),s}buildVertexData(e=0,t=2){const i=new j,s=[],n=[],r=[],o=this._points.computeBounds();this._points.elements.forEach(c=>{s.push(0,1,0),n.push(c.x,0,c.y),r.push((c.x-o.min.x)/o.width,(c.y-o.min.y)/o.height)});const l=[],h=this.bjsEarcut(this._epoints,this._eholes,2);for(let c=0;c0){const c=n.length/3;this._points.elements.forEach(f=>{s.push(0,-1,0),n.push(f.x,-e,f.y),r.push(1-(f.x-o.min.x)/o.width,1-(f.y-o.min.y)/o.height)});const u=l.length;for(let f=0;f{this._addSide(n,s,r,l,o,f,e,!0,t)})}return i.indices=l,i.positions=n,i.normals=s,i.uvs=r,i}_addSide(e,t,i,s,n,r,o,l,h){let c=e.length/3,u=0;for(let f=0;fh?Sh?AMo(a,{shape:e,holes:i,updatable:s,sideOrientation:n},t,r);F.ExtrudePolygon=(a,e,t,i,s,n,r,o=earcut)=>Ro(a,{shape:e,holes:s,depth:t,updatable:n,sideOrientation:r},i,o);function ou(a,e,t=null){const i=e.path,s=e.shape,n=e.scale||1,r=e.rotation||0,o=e.cap===0?0:e.cap||F.NO_CAP,l=e.updatable,h=F._GetDefaultSideOrientation(e.sideOrientation),c=e.instance||null,u=e.invertUV||!1,f=e.closeShape||!1,d=e.closePath||!1;return hu(a,s,i,n,r,null,null,d,f,o,!1,t,!!l,h,c,u,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame)}function lu(a,e,t=null){const i=e.path,s=e.shape,n=e.scaleFunction||(()=>1),r=e.rotationFunction||(()=>0),o=e.closePath||e.ribbonCloseArray||!1,l=e.closeShape||e.ribbonClosePath||!1,h=e.cap===0?0:e.cap||F.NO_CAP,c=e.updatable,u=e.firstNormal||null,f=e.adjustFrame||!1,d=F._GetDefaultSideOrientation(e.sideOrientation),p=e.instance,g=e.invertUV||!1;return hu(a,s,i,null,null,n,r,o,l,h,!0,t,!!c,d,p||null,g,e.frontUVs||null,e.backUVs||null,u,f)}function hu(a,e,t,i,s,n,r,o,l,h,c,u,f,d,p,g,_,m,x,I){const T=(M,C,w,P,z,L,G,H,ce,J,W)=>{const V=w.getTangents(),R=w.getNormals(),k=w.getBinormals(),Y=w.getDistances();if(W){for(let Z=0;Z0){let Ee=V[Z-1];v.Dot(Ee,V[Z])<0&&V[Z].scaleInPlace(-1),Ee=R[Z-1],v.Dot(Ee,R[Z])<0&&R[Z].scaleInPlace(-1),Ee=k[Z-1],v.Dot(Ee,k[Z])<0&&k[Z].scaleInPlace(-1)}}let he=0;const oe=()=>z!==null?z:1,ue=J&&H?H:()=>L!==null?L:0,xe=J&&G?G:oe;let ae=ce===F.NO_CAP||ce===F.CAP_END?0:2;const Me=N.Matrix[0];for(let Z=0;Z{const Ee=Array(),Oe=v.Zero();let He;for(He=0;He3?0:h,b=T(e,t,y,S,i,s,n,r,h,c,I);const A=Ls(a,{pathArray:b,closeArray:o,closePath:l,updatable:f,sideOrientation:d,invertUV:g,frontUVs:_||void 0,backUVs:m||void 0},u);return A._creationDataStorage.pathArray=b,A._creationDataStorage.path3D=y,A._creationDataStorage.cap=h,A}F.ExtrudeShape=(a,e,t,i,s,n,r=null,o,l,h)=>{const c={shape:e,path:t,scale:i,rotation:s,cap:n===0?0:n||F.NO_CAP,sideOrientation:l,instance:h,updatable:o};return ou(a,c,r)};F.ExtrudeShapeCustom=(a,e,t,i,s,n,r,o,l,h,c,u)=>{const f={shape:e,path:t,scaleFunction:i,rotationFunction:s,ribbonCloseArray:n,ribbonClosePath:r,cap:o===0?0:o||F.NO_CAP,sideOrientation:c,instance:u,updatable:h};return lu(a,f,l)};function cu(a,e,t=null){const i=e.arc?e.arc<=0||e.arc>1?1:e.arc:1,s=e.closed===void 0?!0:e.closed,n=e.shape,r=e.radius||1,o=e.tessellation||64,l=e.clip||0,h=e.updatable,c=F._GetDefaultSideOrientation(e.sideOrientation),u=e.cap||F.NO_CAP,f=Math.PI*2,d=[],p=e.invertUV||!1;let g=0,_=0;const m=f/o*i;let x,I;for(g=0;g<=o-l;g++){for(I=[],(u==F.CAP_START||u==F.CAP_ALL)&&(I.push(new v(0,n[0].y,0)),I.push(new v(Math.cos(g*m)*n[0].x*r,n[0].y,Math.sin(g*m)*n[0].x*r))),_=0;_cu(a,{shape:e,radius:t,tessellation:i,sideOrientation:r,updatable:n},s);function uu(a){const e=[],t=[],i=[],s=[],n=a.width||a.size||1,r=a.height||a.size||1,o=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE,l=n/2,h=r/2;t.push(-l,-h,0),i.push(0,0,-1),s.push(0,Le.UseOpenGLOrientationForUV?1:0),t.push(l,-h,0),i.push(0,0,-1),s.push(1,Le.UseOpenGLOrientationForUV?1:0),t.push(l,h,0),i.push(0,0,-1),s.push(1,Le.UseOpenGLOrientationForUV?0:1),t.push(-l,h,0),i.push(0,0,-1),s.push(0,Le.UseOpenGLOrientationForUV?0:1),e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),j._ComputeSides(o,t,e,i,s,a.frontUVs,a.backUVs);const c=new j;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function fu(a,e={},t=null){const i=new F(a,t);return e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,uu(e).applyToMesh(i,e.updatable),e.sourcePlane&&(i.translate(e.sourcePlane.normal,-e.sourcePlane.d),i.setDirection(e.sourcePlane.normal.scale(-1))),i}j.CreatePlane=uu;F.CreatePlane=(a,e,t,i,s)=>fu(a,{size:e,width:e,height:e,sideOrientation:s,updatable:i},t);function du(a,e,t=null){const i=e.path;let s=e.instance,n=1;e.radius!==void 0?n=e.radius:s&&(n=s._creationDataStorage.radius);const r=e.tessellation||64,o=e.radiusFunction||null;let l=e.cap||F.NO_CAP;const h=e.invertUV||!1,c=e.updatable,u=F._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;const f=(m,x,I,T,y,b,S,A)=>{const M=x.getTangents(),C=x.getNormals(),w=x.getDistances(),z=Math.PI*2/y*A,G=b||(()=>T);let H,ce,J,W;const V=N.Matrix[0];let R=S===F.NO_CAP||S===F.CAP_END?0:2;for(let Y=0;Y{const oe=Array();for(let re=0;re3?0:l,p=f(i,d,g,n,r,o,l,e.arc);const _=Ls(a,{pathArray:p,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:h,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return _._creationDataStorage.pathArray=p,_._creationDataStorage.path3D=d,_._creationDataStorage.tessellation=r,_._creationDataStorage.cap=l,_._creationDataStorage.arc=e.arc,_._creationDataStorage.radius=n,_}F.CreateTube=(a,e,t,i,s,n,r,o,l,h)=>du(a,{path:e,radius:t,tessellation:i,radiusFunction:s,arc:1,cap:n,updatable:o,sideOrientation:l,instance:h},r);function pu(a){const e=[];e[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},e[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},e[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},e[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},e[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},e[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},e[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},e[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},e[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},e[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},e[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},e[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},e[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},e[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},e[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};const t=a.type&&(a.type<0||a.type>=e.length)?0:a.type||0,i=a.size,s=a.sizeX||i||1,n=a.sizeY||i||1,r=a.sizeZ||i||1,o=a.custom||e[t],l=o.face.length,h=a.faceUV||new Array(l),c=a.faceColors,u=a.flat===void 0?!0:a.flat,f=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE,d=[],p=[],g=[],_=[],m=[];let x=0,I=0;const T=[];let y=0,b=0,S,A,M,C,w,P;if(u)for(b=0;bPo(a,e,t);function _u(a){const e=a.sideOrientation||j.DEFAULTSIDE,t=a.radius||1,i=a.flat===void 0?!0:a.flat,s=(a.subdivisions||4)|0,n=a.radiusX||t,r=a.radiusY||t,o=a.radiusZ||t,l=(1+Math.sqrt(5))/2,h=[-1,l,-0,1,l,0,-1,-l,0,1,-l,0,0,-1,-l,0,1,-l,0,-1,l,0,1,l,l,0,1,l,0,-1,-l,0,1,-l,0,-1],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],u=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],f=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],d=138/1024,p=239/1024,g=60/1024,_=26/1024,m=-40/1024,x=20/1024,I=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],T=[],y=[],b=[],S=[];let A=0;const M=new Array(3),C=new Array(3);let w;for(w=0;w<3;w++)M[w]=v.Zero(),C[w]=fe.Zero();for(let z=0;z<20;z++){for(w=0;w<3;w++){const G=c[3*z+w];M[w].copyFromFloats(h[3*u[G]],h[3*u[G]+1],h[3*u[G]+2]),M[w].normalize(),C[w].copyFromFloats(f[2*G]*d+g+I[z]*m,f[2*G+1]*p+_+I[z]*x)}const L=(G,H,ce,J)=>{const W=v.Lerp(M[0],M[2],H/s),V=v.Lerp(M[1],M[2],H/s),R=s===H?M[2]:v.Lerp(W,V,G/(s-H));R.normalize();let k;if(i){const re=v.Lerp(M[0],M[2],J/s),ue=v.Lerp(M[1],M[2],J/s);k=v.Lerp(re,ue,ce/(s-J))}else k=new v(R.x,R.y,R.z);k.x/=n,k.y/=r,k.z/=o,k.normalize();const Y=fe.Lerp(C[0],C[2],H/s),he=fe.Lerp(C[1],C[2],H/s),oe=s===H?C[2]:fe.Lerp(Y,he,G/(s-H));y.push(R.x*n,R.y*r,R.z*o),b.push(k.x,k.y,k.z),S.push(oe.x,Le.UseOpenGLOrientationForUV?1-oe.y:oe.y),T.push(A),A++};for(let G=0;Ggu(a,e,t);const Z3=new v(1,0,0),Q3=new v(-1,0,0),J3=new v(0,1,0),eb=new v(0,-1,0),tb=new v(0,0,1),ib=new v(0,0,-1);class Sr{constructor(e=v.Zero(),t=v.Up(),i=fe.Zero(),s=0,n=0,r=null,o=null,l=null,h=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=s,this.vertexIdxForBones=n,this.localPositionOverride=r,this.localNormalOverride=o,this.matrixIndicesOverride=l,this.matrixWeightsOverride=h}clone(){var e,t,i,s;return new Sr(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,(e=this.localPositionOverride)==null?void 0:e.slice(),(t=this.localNormalOverride)==null?void 0:t.slice(),(i=this.matrixIndicesOverride)==null?void 0:i.slice(),(s=this.matrixWeightsOverride)==null?void 0:s.slice())}}function mu(a,e,t){var H,ce,J,W;const i=!!e.skeleton,s=t.localMode||i,n=e.getIndices(),r=i?e.getPositionData(!0,!0):e.getVerticesData(E.PositionKind),o=i?e.getNormalsData(!0,!0):e.getVerticesData(E.NormalKind),l=s?i?e.getVerticesData(E.PositionKind):r:null,h=s?i?e.getVerticesData(E.NormalKind):o:null,c=e.getVerticesData(E.UVKind),u=i?e.getVerticesData(E.MatricesIndicesKind):null,f=i?e.getVerticesData(E.MatricesWeightsKind):null,d=i?e.getVerticesData(E.MatricesIndicesExtraKind):null,p=i?e.getVerticesData(E.MatricesWeightsExtraKind):null,g=t.position||v.Zero();let _=t.normal||v.Up();const m=t.size||v.One(),x=t.angle||0;if(!_){const V=new v(0,0,1),R=e.getScene().activeCamera,k=v.TransformCoordinates(V,R.getWorldMatrix());_=R.globalPosition.subtract(k)}const I=-Math.atan2(_.z,_.x)-Math.PI/2,T=Math.sqrt(_.x*_.x+_.z*_.z),y=Math.atan2(_.y,T),b=new j;b.indices=[],b.positions=[],b.normals=[],b.uvs=[],b.matricesIndices=i?[]:null,b.matricesWeights=i?[]:null,b.matricesIndicesExtra=d?[]:null,b.matricesWeightsExtra=p?[]:null;let S=0;const A=(V,R)=>{const k=new Sr;if(!n||!r||!o)return k;const Y=n[V];if(k.vertexIdx=Y*3,k.vertexIdxForBones=Y*4,k.position=new v(r[Y*3],r[Y*3+1],r[Y*3+2]),v.TransformCoordinatesToRef(k.position,R,k.position),k.normal=new v(o[Y*3],o[Y*3+1],o[Y*3+2]),v.TransformNormalToRef(k.normal,R,k.normal),t.captureUVS&&c){const he=c[Y*2+1];k.uv=new fe(c[Y*2],Le.UseOpenGLOrientationForUV?1-he:he)}return k},M=[0,0,0,0],C=(V,R)=>{if(V.length===0)return V;const k=.5*Math.abs(v.Dot(m,R)),Y=(re,ue,xe,ae)=>{for(let Me=0;Me{var zt,qt,qi,Xn,Do,Fo,Oo,Lo,Bo,No,Uo,ko,Vo,Go,zo,Wo;const xe=v.GetClipFactor(re.position,ue.position,R,k);let ae=M,Me=M;if(u&&f){const cn=re.matrixIndicesOverride?0:re.vertexIdxForBones,Yr=(zt=re.matrixIndicesOverride)!=null?zt:u,Xo=(qt=re.matrixWeightsOverride)!=null?qt:f,qr=ue.matrixIndicesOverride?0:ue.vertexIdxForBones,Ho=(qi=ue.matrixIndicesOverride)!=null?qi:u,Ko=(Xn=ue.matrixWeightsOverride)!=null?Xn:f;ae=[0,0,0,0],Me=[0,0,0,0];let Ts=0;for(let Si=0;Si<4;++Si)if(Xo[cn+Si]>0){const un=Y(Ho,Yr[cn+Si],qr,4);ae[Ts]=Yr[cn+Si],Me[Ts]=Ye.Lerp(Xo[cn+Si],un>=0?Ko[un]:0,xe),Ts++}for(let Si=0;Si<4&&Ts<4;++Si){const un=Ho[qr+Si];Y(Yr,un,cn,4)===-1&&(ae[Ts]=un,Me[Ts]=Ye.Lerp(0,Ko[qr+Si],xe),Ts++)}const Hn=Me[0]+Me[1]+Me[2]+Me[3];Me[0]/=Hn,Me[1]/=Hn,Me[2]/=Hn,Me[3]/=Hn}const ke=re.localPositionOverride?re.localPositionOverride[0]:(Do=l==null?void 0:l[re.vertexIdx])!=null?Do:0,Z=re.localPositionOverride?re.localPositionOverride[1]:(Fo=l==null?void 0:l[re.vertexIdx+1])!=null?Fo:0,Ee=re.localPositionOverride?re.localPositionOverride[2]:(Oo=l==null?void 0:l[re.vertexIdx+2])!=null?Oo:0,Oe=ue.localPositionOverride?ue.localPositionOverride[0]:(Lo=l==null?void 0:l[ue.vertexIdx])!=null?Lo:0,He=ue.localPositionOverride?ue.localPositionOverride[1]:(Bo=l==null?void 0:l[ue.vertexIdx+1])!=null?Bo:0,je=ue.localPositionOverride?ue.localPositionOverride[2]:(No=l==null?void 0:l[ue.vertexIdx+2])!=null?No:0,Ct=re.localNormalOverride?re.localNormalOverride[0]:(Uo=h==null?void 0:h[re.vertexIdx])!=null?Uo:0,wt=re.localNormalOverride?re.localNormalOverride[1]:(ko=h==null?void 0:h[re.vertexIdx+1])!=null?ko:0,ri=re.localNormalOverride?re.localNormalOverride[2]:(Vo=h==null?void 0:h[re.vertexIdx+2])!=null?Vo:0,ei=ue.localNormalOverride?ue.localNormalOverride[0]:(Go=h==null?void 0:h[ue.vertexIdx])!=null?Go:0,Ht=ue.localNormalOverride?ue.localNormalOverride[1]:(zo=h==null?void 0:h[ue.vertexIdx+1])!=null?zo:0,Bi=ue.localNormalOverride?ue.localNormalOverride[2]:(Wo=h==null?void 0:h[ue.vertexIdx+2])!=null?Wo:0,ys=Ct+(ei-Ct)*xe,Ti=wt+(Ht-wt)*xe,Kt=ri+(Bi-ri)*xe,ai=Math.sqrt(ys*ys+Ti*Ti+Kt*Kt);return new Sr(v.Lerp(re.position,ue.position,xe),v.Lerp(re.normal,ue.normal,xe).normalize(),fe.Lerp(re.uv,ue.uv,xe),-1,-1,l?[ke+(Oe-ke)*xe,Z+(He-Z)*xe,Ee+(je-Ee)*xe]:null,h?[ys/ai,Ti/ai,Kt/ai]:null,ae,Me)};let oe=null;V.length>3&&(oe=[]);for(let re=0;re0,je=Ee>0,Ct=Oe>0;switch(ue=(He?1:0)+(je?1:0)+(Ct?1:0),ue){case 0:V.length>3?(oe.push(V[re]),oe.push(V[re+1]),oe.push(V[re+2])):oe=V;break;case 1:if(oe=oe!=null?oe:new Array,He&&(xe=V[re+1],ae=V[re+2],Me=he(V[re],xe),ke=he(V[re],ae)),je){xe=V[re],ae=V[re+2],Me=he(V[re+1],xe),ke=he(V[re+1],ae),oe.push(Me),oe.push(ae.clone()),oe.push(xe.clone()),oe.push(ae.clone()),oe.push(Me.clone()),oe.push(ke);break}Ct&&(xe=V[re],ae=V[re+1],Me=he(V[re+2],xe),ke=he(V[re+2],ae)),xe&&ae&&Me&&ke&&(oe.push(xe.clone()),oe.push(ae.clone()),oe.push(Me),oe.push(ke),oe.push(Me.clone()),oe.push(ae.clone()));break;case 2:oe=oe!=null?oe:new Array,He||(xe=V[re].clone(),ae=he(xe,V[re+1]),Me=he(xe,V[re+2]),oe.push(xe),oe.push(ae),oe.push(Me)),je||(xe=V[re+1].clone(),ae=he(xe,V[re+2]),Me=he(xe,V[re]),oe.push(xe),oe.push(ae),oe.push(Me)),Ct||(xe=V[re+2].clone(),ae=he(xe,V[re]),Me=he(xe,V[re+1]),oe.push(xe),oe.push(ae),oe.push(Me));break}}return oe},w=e instanceof F?e:null,P=w==null?void 0:w._thinInstanceDataStorage.matrixData,z=(w==null?void 0:w.thinInstanceCount)||1,L=N.Matrix[0];L.copyFrom(O.IdentityReadOnly);for(let V=0;Vmu(a,e,{position:t,normal:i,size:s,angle:n});function vu(a={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const e=Math.max(a.subdivisions?a.subdivisions:2,1)|0,t=Math.max(a.tessellation?a.tessellation:16,3)|0,i=Math.max(a.height?a.height:1,0),s=Math.max(a.radius?a.radius:.25,0),n=Math.max(a.capSubdivisions?a.capSubdivisions:6,1)|0,r=t,o=e,l=Math.max(a.radiusTop?a.radiusTop:s,0),h=Math.max(a.radiusBottom?a.radiusBottom:s,0),c=i-(l+h),u=0,f=2*Math.PI,d=Math.max(a.topCapSubdivisions?a.topCapSubdivisions:n,1),p=Math.max(a.bottomCapSubdivisions?a.bottomCapSubdivisions:n,1),g=Math.acos((h-l)/i);let _=[];const m=[],x=[],I=[];let T=0;const y=[],b=c*.5,S=Math.PI*.5;let A,M;const C=v.Zero(),w=v.Zero(),P=Math.cos(g),z=Math.sin(g),L=new fe(l*z,b+l*P).subtract(new fe(h*z,-b+h*P)).length(),G=l*g+L+h*(S-g);let H=0;for(M=0;M<=d;M++){const V=[],R=S-g*(M/d);H+=l*g/d;const k=Math.cos(R),Y=Math.sin(R),he=k*l;for(A=0;A<=r;A++){const oe=A/r,re=oe*f+u,ue=Math.sin(re),xe=Math.cos(re);w.x=he*ue,w.y=b+Y*l,w.z=he*xe,m.push(w.x,w.y,w.z),C.set(k*ue,Y,k*xe),x.push(C.x,C.y,C.z),I.push(oe,Le.UseOpenGLOrientationForUV?H/G:1-H/G),V.push(T),T++}y.push(V)}const ce=i-l-h+P*l-P*h,J=z*(h-l)/ce;for(M=1;M<=o;M++){const V=[];H+=L/o;const R=z*(M*(h-l)/o+l);for(A=0;A<=r;A++){const k=A/r,Y=k*f+u,he=Math.sin(Y),oe=Math.cos(Y);w.x=R*he,w.y=b+P*l-M*ce/o,w.z=R*oe,m.push(w.x,w.y,w.z),C.set(he,J,oe).normalize(),x.push(C.x,C.y,C.z),I.push(k,Le.UseOpenGLOrientationForUV?H/G:1-H/G),V.push(T),T++}y.push(V)}for(M=1;M<=p;M++){const V=[],R=S-g-(Math.PI-g)*(M/p);H+=h*g/p;const k=Math.cos(R),Y=Math.sin(R),he=k*h;for(A=0;A<=r;A++){const oe=A/r,re=oe*f+u,ue=Math.sin(re),xe=Math.cos(re);w.x=he*ue,w.y=-b+Y*h,w.z=he*xe,m.push(w.x,w.y,w.z),C.set(k*ue,Y,k*xe),x.push(C.x,C.y,C.z),I.push(oe,Le.UseOpenGLOrientationForUV?H/G:1-H/G),V.push(T),T++}y.push(V)}for(A=0;Axu(a,e,t);j.CreateCapsule=vu;class at{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&U.Warn("x is not an integer, floor(x) used"),t!==Math.floor(t)&&U.Warn("y is not an integer, floor(y) used")}clone(){return new at(this.x,this.y)}rotate60About(e){const t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){const t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&U.Warn("m not an integer only floor(m) used"),t!==Math.floor(t)&&U.Warn("n not an integer only floor(n) used");const i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&U.Warn("m is not an integer, floor(m) used"),t!==Math.floor(t)&&U.Warn("n is not an integer, floor(n) used");const i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){const i=v.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new at(0,0)}}class bu{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new Da("icosahedron","Regular",[[0,xt,-1],[-xt,1,0],[-1,0,-xt],[1,0,-xt],[xt,1,0],[0,xt,1],[-1,0,xt],[-xt,-1,0],[0,-xt,-1],[xt,-1,0],[1,0,xt],[0,-xt,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12;const t={},i=this.m,s=this.n;let n=i,r=1,o=0;s!==0&&(n=Ye.HCF(i,s)),r=i/n,o=s/n;let l,h,c,u,f;const d=at.Zero(),p=new at(i,s),g=new at(-s,i+s),_=at.Zero(),m=at.Zero(),x=at.Zero();let I=[],T,y,b,S;const A=[],M=this.vertByDist,C=(w,P,z,L)=>{T=w+"|"+z,y=P+"|"+L,T in t||y in t?T in t&&!(y in t)?t[y]=t[T]:y in t&&!(T in t)&&(t[T]=t[y]):(t[T]=e,t[y]=e,e++),M[z][0]>2?A[t[T]]=[-M[z][0],M[z][1],t[T]]:A[t[T]]=[I[M[z][0]],M[z][1],t[T]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let w=0;w<20;w++){if(I=this.IDATA.face[w],c=I[2],u=I[1],f=I[0],b=d.x+"|"+d.y,T=w+"|"+b,T in t||(t[T]=c,A[c]=[I[M[b][0]],M[b][1]]),b=p.x+"|"+p.y,T=w+"|"+b,T in t||(t[T]=u,A[u]=[I[M[b][0]],M[b][1]]),b=g.x+"|"+g.y,T=w+"|"+b,T in t||(t[T]=f,A[f]=[I[M[b][0]],M[b][1]]),l=this.IDATA.edgematch[w][0],h=this.IDATA.edgematch[w][1],h==="B")for(let P=1;P2?A[t[T]]=[-M[b][0],M[b][1],t[T]]:A[t[T]]=[I[M[b][0]],M[b][1],t[T]])}this.closestTo=A,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,s=e*e+t*t+e*t;this.coau=(e+t)/s,this.cobu=-t/s,this.coav=-i*(e-t)/s,this.cobv=i*(2*e+t)/s}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&s0){const y=Ye.HCF(e,t),b=e/y,S=t/y;for(let M=1;My.x-b.x),i.sort((y,b)=>y.y-b.y);const o=new Array(e+t+1),l=new Array(e+t+1);for(let y=0;y{const S=y.clone();return b==="A"&&S.rotateNeg120(e,t),b==="B"&&S.rotate120(e,t),S.x<0?S.y:S.x+S.y},d=[],p=[],g=[],_=[],m={},x=[];let I=-1,T=-1;for(let y=0;yy[2]-b[2]),x.sort((y,b)=>y[3]-b[3]),x.sort((y,b)=>y[1]-b[1]),x.sort((y,b)=>y[0]-b[0]);for(let y=0;yt.vecToidx[e+s]))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let s=0;s-1?i[r][1]>0&&t[i[r][0]].push([r,i[r][1]]):t[12].push([r,i[r][0]]);const s=[];for(let r=0;r<12;r++)s[r]=r;let n=12;for(let r=0;r<12;r++){t[r].sort((o,l)=>o[1]-l[1]);for(let o=0;or[3]-o[3]);for(let r=0;r0;)n=t[l],this.face[n].indexOf(o)>-1?(r=(this.face[n].indexOf(o)+1)%3,o=this.face[n][r],i.push(o),s.push(n),t.splice(l,1),l=0):l++;return this.adjacentFaces.push(i),s}toGoldbergPolyhedronData(){const e=new Da("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let h=0;h{s=0,n=0,r=0,o=this.face[c];for(let u=0;u<3;u++)l=this.vertex[o[u]],s+=l[0],n+=l[1],r+=l[2];e.vertex[c]=[s/3,n/3,r/3]});return e}static BuildGeodesicData(e){const t=new Xr("Geodesic-m-n","Geodesic",[[0,xt,-1],[-xt,1,0],[-1,0,-xt],[1,0,-xt],[xt,1,0],[0,xt,1],[-1,0,xt],[-xt,-1,0],[0,-xt,-1],[xt,-1,0],[1,0,xt],[0,-xt,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let s=0;si){const h=s;s=i,i=h,U.Warn("n > m therefore m and n swapped")}const n=new bu;n.build(i,s);const o={custom:Xr.BuildGeodesicData(n),size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,faceUV:e.faceUV,faceColors:e.faceColors,flat:e.flat,updatable:e.updatable,sideOrientation:e.sideOrientation,frontUVs:e.frontUVs,backUVs:e.backUVs};return Po(a,o,t)}F._GoldbergMeshParser=(a,e)=>Hr.Parse(a,e);class Hr extends F{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return t===void 0?(e>this.goldbergData.nbUnsharedFaces-1&&(U.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(U.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(U.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let i=0;i1&&(u=1),h.push(u,f);for(let d=0;d<6;d++)u=r.x+o*Math.cos(l+d*Math.PI/3),f=r.y+o*Math.sin(l+d*Math.PI/3),u<0&&(u=0),u>1&&(u=1),c.push(u,f);for(let d=s;dX.FromArray(n)),i.faceCenters=i.faceCenters.map(n=>v.FromArray(n)),i.faceZaxis=i.faceZaxis.map(n=>v.FromArray(n)),i.faceXaxis=i.faceXaxis.map(n=>v.FromArray(n)),i.faceYaxis=i.faceYaxis.map(n=>v.FromArray(n));const s=new Hr(e.name,t);return s.goldbergData=i,s}}function nb(a,e){const t=a.size,i=a.sizeX||t||1,s=a.sizeY||t||1,n=a.sizeZ||t||1,r=a.sideOrientation===0?0:a.sideOrientation||j.DEFAULTSIDE,o=[],l=[],h=[],c=[];let u=1/0,f=-1/0,d=1/0,p=-1/0;for(let m=0;mo){const p=l;l=o,o=p,U.Warn("n > m therefore m and n swapped")}const h=new bu;h.build(o,l);const c=Xr.BuildGeodesicData(h),u=c.toGoldbergPolyhedronData(),f=new Hr(a,t);e.sideOrientation=F._GetDefaultSideOrientation(e.sideOrientation),f._originalBuilderSideOrientation=e.sideOrientation,nb(e,u).applyToMesh(f,e.updatable),f.goldbergData.nbSharedFaces=c.sharedNodes,f.goldbergData.nbUnsharedFaces=c.poleNodes,f.goldbergData.adjacentFaces=c.adjacentFaces,f.goldbergData.nbFaces=f.goldbergData.nbSharedFaces+f.goldbergData.nbUnsharedFaces,f.goldbergData.nbFacesAtPole=(f.goldbergData.nbUnsharedFaces-12)/12;for(let p=0;p0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function ob(a,e,t,i,s,n){const r=n.glyphs[a]||n.glyphs["?"];if(!r)return null;const o=new ab(s);if(r.o){const l=r.o.split(" ");for(let h=0,c=l.length;h=this._thinInstanceDataStorage.instancesCount)return!1;const i=this._thinInstanceDataStorage.matrixData;return e.copyToArray(i,a*16),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[a]=e),t&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0};F.prototype.thinInstanceSetAttributeAt=function(a,e,t,i=!0){return a===E.ColorKind&&(a=E.ColorInstanceKind),!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[a]||e>=this._thinInstanceDataStorage.instancesCount?!1:(this._thinInstanceUpdateBufferSize(a,0),this._userThinInstanceBuffersStorage.data[a].set(t,e*this._userThinInstanceBuffersStorage.strides[a]),i&&this.thinInstanceBufferUpdated(a),!0)};Object.defineProperty(F.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(a){var i,s;const e=(s=this._thinInstanceDataStorage.matrixData)!=null?s:(i=this.source)==null?void 0:i._thinInstanceDataStorage.matrixData,t=e?e.length/16:0;a<=t&&(this._thinInstanceDataStorage.instancesCount=a)},enumerable:!0,configurable:!0});F.prototype._thinInstanceCreateMatrixBuffer=function(a,e,t=!0){const i=new Js(this.getEngine(),e,!t,16,!1,!0);for(let s=0;s<4;s++)this.setVerticesBuffer(i.createVertexBuffer(a+s,s*4,4));return i};F.prototype.thinInstanceSetBuffer=function(a,e,t=0,i=!0){var s,n,r;t=t||16,a==="matrix"?((s=this._thinInstanceDataStorage.matrixBuffer)==null||s.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=e?e.length:32*t,this._thinInstanceDataStorage.matrixData=e,this._thinInstanceDataStorage.worldMatrices=null,e!==null?(this._thinInstanceDataStorage.instancesCount=e.length/t,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",e,i),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):a==="previousMatrix"?((n=this._thinInstanceDataStorage.previousMatrixBuffer)==null||n.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=e,e!==null&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",e,i))):(a===E.ColorKind&&(a=E.ColorInstanceKind),e===null?(r=this._userThinInstanceBuffersStorage)!=null&&r.data[a]&&(this.removeVerticesData(a),delete this._userThinInstanceBuffersStorage.data[a],delete this._userThinInstanceBuffersStorage.strides[a],delete this._userThinInstanceBuffersStorage.sizes[a],delete this._userThinInstanceBuffersStorage.vertexBuffers[a]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[a]=e,this._userThinInstanceBuffersStorage.strides[a]=t,this._userThinInstanceBuffersStorage.sizes[a]=e.length,this._userThinInstanceBuffersStorage.vertexBuffers[a]=new E(this.getEngine(),e,a,!i,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[a])))};F.prototype.thinInstanceBufferUpdated=function(a){var e,t,i;a==="matrix"?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(a),(e=this._thinInstanceDataStorage.matrixBuffer)==null||e.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):a==="previousMatrix"?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(a),(t=this._thinInstanceDataStorage.previousMatrixBuffer)==null||t.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(a===E.ColorKind&&(a=E.ColorInstanceKind),(i=this._userThinInstanceBuffersStorage)!=null&&i.vertexBuffers[a]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[a].isUpdatable()&&this._thinInstanceRecreateBuffer(a),this._userThinInstanceBuffersStorage.vertexBuffers[a].updateDirectly(this._userThinInstanceBuffersStorage.data[a],0)))};F.prototype.thinInstancePartialBufferUpdate=function(a,e,t){var i;a==="matrix"?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(e,t):(a===E.ColorKind&&(a=E.ColorInstanceKind),(i=this._userThinInstanceBuffersStorage)!=null&&i.vertexBuffers[a]&&this._userThinInstanceBuffersStorage.vertexBuffers[a].updateDirectly(e,t))};F.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const a=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let e=0;e{this._outputTexture?d.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):d.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)}),this.kernel=i}updateEffect(e=null,t=null,i=null,s,n,r){this._updateParameters(n,r)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let n=[],r=[],o=0;for(let _=0;_0)return Math.max(i,3);return Math.max(t,3)}_gaussianWeight(e){const t=.3333333333333333,i=Math.sqrt(2*Math.PI)*t,s=-(e*e/(2*t*t));return 1/i*Math.exp(s)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,s){return Ae.Parse(()=>new bs(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,s)}}D([B("kernel")],bs.prototype,"_kernel",void 0);D([B("packedFloat")],bs.prototype,"_packedFloat",void 0);D([Oh()],bs.prototype,"direction",void 0);ft("BABYLON.BlurPostProcess",bs);const Eb="glowMapGenerationPixelShader",Ib="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;uniform float glowIntensity;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a{if((i||t===0)&&e.subMeshes)for(let s=0;s{this.onBeforeRenderMainTextureObservable.notifyObservers(this);let n;const r=this._scene.getEngine();if(s.length){for(r.setColorWrite(!1),n=0;n{e.clear(this.neutralColor,!0,!0,!0)}),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e}),this._mainTexture.onAfterUnbindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=e})}}_addCustomEffectDefines(e){}_isReady(e,t,i){var x;const s=this._scene.getEngine(),n=e.getMesh(),r=(x=n._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:x[s.currentRenderPassId];if(r)return r.isReadyForSubMesh(n,e,t);const o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);const l=[],h=[E.PositionKind];let c=!1,u=!1;if(o){const I=o.needAlphaTesting(),T=o.getAlphaTestTexture(),y=T&&T.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);T&&(I||y)&&(l.push("#define DIFFUSE"),n.isVerticesDataPresent(E.UV2Kind)&&T.coordinatesIndex===1?(l.push("#define DIFFUSEUV2"),u=!0):n.isVerticesDataPresent(E.UVKind)&&(l.push("#define DIFFUSEUV1"),c=!0),I&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),T.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));const b=o.opacityTexture;b&&(l.push("#define OPACITY"),n.isVerticesDataPresent(E.UV2Kind)&&b.coordinatesIndex===1?(l.push("#define OPACITYUV2"),u=!0):n.isVerticesDataPresent(E.UVKind)&&(l.push("#define OPACITYUV1"),c=!0))}i&&(l.push("#define EMISSIVE"),n.isVerticesDataPresent(E.UV2Kind)&&i.coordinatesIndex===1?(l.push("#define EMISSIVEUV2"),u=!0):n.isVerticesDataPresent(E.UVKind)&&(l.push("#define EMISSIVEUV1"),c=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),n.useVertexColors&&n.isVerticesDataPresent(E.ColorKind)&&n.hasVertexAlpha&&o.transparencyMode!==q.MATERIAL_OPAQUE&&(h.push(E.ColorKind),l.push("#define VERTEXALPHA")),c&&(h.push(E.UVKind),l.push("#define UV1")),u&&(h.push(E.UV2Kind),l.push("#define UV2"));const f=new bo;if(n.useBones&&n.computeBonesUsingShaders){h.push(E.MatricesIndicesKind),h.push(E.MatricesWeightsKind),n.numBoneInfluencers>4&&(h.push(E.MatricesIndicesExtraKind),h.push(E.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers);const I=n.skeleton;I&&I.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(I?I.bones.length+1:0)),n.numBoneInfluencers>0&&f.addCPUSkinningFallback(0,n)}else l.push("#define NUM_BONE_INFLUENCERS 0");const d=n.morphTargetManager;let p=0;d&&(p=d.numMaxInfluencers||d.numInfluencers,p>0&&(l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+p),d.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),eg(h,n,p))),t&&(l.push("#define INSTANCES"),go(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),qh(o,this._scene,l),this._addCustomEffectDefines(l);const g=e._getDrawWrapper(void 0,!0),_=g.defines,m=l.join("\n");if(_!==m){const I=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];uo(I),g.setEffect(this._engine.createEffect("glowMapGeneration",h,I,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],m,f,void 0,void 0,{maxSimultaneousMorphTargets:p}),m)}return g.effect.isReady()}render(){for(let r=0;rx.setMatrix("world",T))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(s)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[E.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return ee.Instantiate(e.customType).Parse(e,t,i)}}yi._SceneComponentInitialization=a=>{throw Te("EffectLayerSceneComponent")};D([B()],yi.prototype,"name",void 0);D([to()],yi.prototype,"neutralColor",void 0);D([B()],yi.prototype,"isEnabled",void 0);D([Yp()],yi.prototype,"camera",null);D([B()],yi.prototype,"renderingGroupId",null);D([B()],yi.prototype,"disableBoundingBoxesFromEffectLayer",void 0);const Mb="glowMapMergePixelShader",Rb="varying vec2 vUV;uniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";K.ShadersStore[Mb]=Rb;const Pb="glowMapMergeVertexShader",wb="attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";K.ShadersStore[Pb]=wb;const Db="glowBlurPostProcessPixelShader",Fb="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color)\n{return dot(color,vec3(0.2126,0.7152,0.0722));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++)\n{vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;}\ngl_FragColor=baseColor;}";K.ShadersStore[Db]=Fb;Xi.AddParser(be.NAME_EFFECTLAYER,(a,e,t,i)=>{if(a.effectLayers){t.effectLayers||(t.effectLayers=[]);for(let s=0;s{this.scene.addEffectLayer(t)})}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach(i=>{this.scene.removeEffectLayer(i),t&&i.dispose()})}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,s=this.scene.effectLayers;for(const n of s){if(!n.hasMesh(e))continue;const r=n._mainTexture;this._engine.currentRenderPassId=r.renderPassId;for(const o of e.subMeshes)if(!n.isReady(o,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const s of i)if(s.shouldRender()&&(!s.camera||s.camera.cameraRigMode===ve.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==ve.RIG_MODE_NONE&&s.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||s.needStencil();const n=s._mainTexture;n._shouldRender()&&(this.scene.incrementRenderId(),n.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i{let e=a._getComponent(be.NAME_EFFECTLAYER);e||(e=new Ob(a),a._addComponent(e))};Xi.prototype.getHighlightLayerByName=function(a){var e;for(let t=0;t<((e=this.effectLayers)==null?void 0:e.length);t++)if(this.effectLayers[t].name===a&&this.effectLayers[t].getEffectName()===Gt.EffectName)return this.effectLayers[t];return null};class Bl extends it{constructor(e,t,i,s,n,r=ne.BILINEAR_SAMPLINGMODE,o,l){super(e,"glowBlurPostProcess",["screenSize","direction","blurWidth"],null,s,n,r,o,l),this.direction=t,this.kernel=i,this.onApplyObservable.add(h=>{h.setFloat2("screenSize",this.width,this.height),h.setVector2("direction",this.direction),h.setFloat("blurWidth",this.kernel)})}}class Gt extends yi{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new Q,this.onAfterBlurObservable=new Q,this._instanceGlowingMeshStencilReference=Gt.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=Gt.NeutralColor,this._engine.isStencilEnable||U.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return Gt.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[E.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?fi(e,this._maxSize):e,t=this._engine.needPOTTextures?fi(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture=new wi("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=ne.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=ne.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(ne.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new Bn("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,ne.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(s=>{s.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new Bl("HighlightLayerHBP",new fe(1,0),this._options.blurHorizontalSize,1,null,ne.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(s=>{s.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new Bl("HighlightLayerVBP",new fe(0,1),this._options.blurVerticalSize,1,null,ne.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add(s=>{s.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new bs("HighlightLayerHBP",new fe(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,ne.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add(s=>{s.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new bs("HighlightLayerVBP",new fe(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,ne.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);const s=this._blurTexture.renderTarget;s&&(this._scene.postProcessManager.directRender(this._postProcesses,s,!0),this._engine.unBindFramebuffer(s,!0)),this.onAfterBlurObservable.notifyObservers(this)}),this._postProcesses.map(s=>{s.autoClear=!1})}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s||!this._meshes)return!1;let n=null;const r=this._meshes[s.uniqueId];return r&&r.glowEmissiveOnly&&i&&(n=i.emissiveTexture),super._isReady(e,t,n)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);const i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&t===0&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(q.TriangleFillMode,0,6)),this.innerGlow&&t===1&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(q.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return super.shouldRender()?!!this._meshes:!1}_shouldRenderMesh(e){return!(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]||!super.hasMesh(e))}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){const s=this._meshes[e.uniqueId];s?this._emissiveTextureAndColor.color.set(s.color.r,s.color.g,s.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),s&&s.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(!this._excludedMeshes)return;if(!this._excludedMeshes[e.uniqueId]){const i={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};i.beforeBind=e.onBeforeBindObservable.add(s=>{i.stencilState=s.getEngine().getStencilBuffer(),s.getEngine().setStencilBuffer(!1)}),i.afterRender=e.onAfterRenderObservable.add(s=>{s.getEngine().setStencilBuffer(i.stencilState)}),this._excludedMeshes[e.uniqueId]=i}}removeExcludedMesh(e){if(!this._excludedMeshes)return;const t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!this._meshes||!super.hasMesh(e)?!1:this._meshes[e.uniqueId]!==void 0&&this._meshes[e.uniqueId]!==null}addMesh(e,t,i=!1){if(!this._meshes)return;const s=this._meshes[e.uniqueId];s?s.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(n=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[n.uniqueId]?this._defaultStencilReference(n):n.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(n=>{this.isEnabled&&this._defaultStencilReference(n)}),glowEmissiveOnly:i},e.onDisposeObservable.add(()=>{this._disposeMesh(e)})),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;const t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(const i in this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes){for(const e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){const t=this._meshes[e];t&&this.removeMesh(t.mesh)}}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(Gt.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(const e in this._meshes){const t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(const e in this._excludedMeshes){const t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){const e=Ae.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(const t in this._meshes){const i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(const t in this._excludedMeshes){const i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){const s=Ae.Parse(()=>new Gt(e.name,t,e.options),e,t,i);let n;for(n=0;nnew Xt(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GridMaterial",e}getClassName(){return"GridMaterial"}static Parse(e,t,i){return Ae.Parse(()=>new Xt(e.name,t),e,t,i)}}D([ls()],Xt.prototype,"mainColor",void 0);D([ls()],Xt.prototype,"lineColor",void 0);D([B()],Xt.prototype,"gridRatio",void 0);D([bi()],Xt.prototype,"gridOffset",void 0);D([B()],Xt.prototype,"majorUnitFrequency",void 0);D([B()],Xt.prototype,"minorUnitVisibility",void 0);D([B()],Xt.prototype,"opacity",void 0);D([B()],Xt.prototype,"antialias",void 0);D([B()],Xt.prototype,"preMultiplyAlpha",void 0);D([B()],Xt.prototype,"useMaxLine",void 0);D([pi("opacityTexture")],Xt.prototype,"_opacityTexture",void 0);D([qe("_markAllSubMeshesAsTexturesDirty")],Xt.prototype,"opacityTexture",void 0);ft("BABYLON.GridMaterial",Xt);Fe.prototype.createDynamicTexture=function(a,e,t,i){const s=new Et(this,4);return s.baseWidth=a,s.baseHeight=e,t&&(a=this.needPOTTextures?fi(a,this._caps.maxTextureSize):a,e=this.needPOTTextures?fi(e,this._caps.maxTextureSize):e),s.width=a,s.height=e,s.isReady=!1,s.generateMipMaps=t,s.samplingMode=i,this.updateTextureSamplingMode(i,s),this._internalTexturesCache.push(s),s};Fe.prototype.updateDynamicTexture=function(a,e,t,i=!1,s,n=!1,r=!1){if(!a)return;const o=this._gl,l=o.TEXTURE_2D,h=this._bindTextureDirectly(l,a,!0,n);this._unpackFlipY(t===void 0?a.invertY:t),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(a.type),u=this._getInternalFormat(s||a.format),f=this._getRGBABufferInternalSizedFormat(a.type,u);o.texImage2D(l,0,f,u,c,e),a.generateMipMaps&&o.generateMipmap(l),h||this._bindTextureDirectly(l,null),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),s&&(a.format=s),a._dynamicTextureSource=e,a._premulAlpha=i,a.invertY=t||!1,a.isReady=!0};class Fn extends ne{constructor(e,t,i=null,s=!1,n=3,r=5,o){super(null,i,!s,o,n,void 0,void 0,void 0,void 0,r),this.name=e,this.wrapU=ne.CLAMP_ADDRESSMODE,this.wrapV=ne.CLAMP_ADDRESSMODE,this._generateMipMaps=s;const l=this._getEngine();if(!l)return;t.getContext?(this._canvas=t,this._ownCanvas=!1,this._texture=l.createDynamicTexture(t.width,t.height,s,n)):(this._canvas=l.createCanvas(1,1),this._ownCanvas=!0,t.width||t.width===0?this._texture=l.createDynamicTexture(t.width,t.height,s,n):this._texture=l.createDynamicTexture(t,t,s,n));const h=this.getSize();this._canvas.width!==h.width&&(this._canvas.width=h.width),this._canvas.height!==h.height&&(this._canvas.height=h.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){const t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){const i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){const t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,e===void 0?!0:e,t,this._format||void 0,void 0,i)}drawText(e,t,i,s,n,r,o,l=!0){const h=this.getSize();if(r&&(this._context.fillStyle=r,this._context.fillRect(0,0,h.width,h.height)),this._context.font=s,t==null){const c=this._context.measureText(e);t=(h.width-c.width)/2}if(i==null){const c=parseInt(s.replace(/\D/g,""));i=h.height/2+c/3.65}this._context.fillStyle=n||"",this._context.fillText(e,t,i),l&&this.update(o)}dispose(){var e,t;super.dispose(),this._ownCanvas&&((t=(e=this._canvas)==null?void 0:e.remove)==null||t.call(e)),this._canvas=null,this._context=null}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Fn(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){const e=this.getScene();e&&!e.isReady()&&U.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return Fn._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return e.toDataURL!==void 0}_rebuild(){this.update()}}mt.AddNodeConstructor("Light_Type_3",(a,e)=>()=>new an(a,v.Zero(),e));class an extends De{constructor(e,t,i){super(e,i),this.groundColor=new pe(0,0,0),this.direction=t||v.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=v.Normalize(e.subtract(v.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=v.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=v.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=O.Identity()),this._worldMatrix}getTypeID(){return De.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}D([ls()],an.prototype,"groundColor",void 0);D([bi()],an.prototype,"direction",void 0);ft("BABYLON.HemisphericLight",an);function yt(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */yt=()=>a;var a={},e=Object.prototype,t=e.hasOwnProperty,i=typeof Symbol=="function"?Symbol:{},s=i.iterator||"@@iterator",n=i.asyncIterator||"@@asyncIterator",r=i.toStringTag||"@@toStringTag";function o(C,w,P){return Object.defineProperty(C,w,{value:P,enumerable:!0,configurable:!0,writable:!0}),C[w]}try{o({},"")}catch{o=(w,P,z)=>w[P]=z}function l(C,w,P,z){var L=w&&w.prototype instanceof u?w:u,G=Object.create(L.prototype),H=new S(z||[]);return G._invoke=((ce,J,W)=>{var V="suspendedStart";return(R,k)=>{if(V==="executing")throw new Error("Generator is already running");if(V==="completed"){if(R==="throw")throw k;return M()}for(W.method=R,W.arg=k;;){var Y=W.delegate;if(Y){var he=T(Y,W);if(he){if(he===c)continue;return he}}if(W.method==="next")W.sent=W._sent=W.arg;else if(W.method==="throw"){if(V==="suspendedStart")throw V="completed",W.arg;W.dispatchException(W.arg)}else W.method==="return"&&W.abrupt("return",W.arg);V="executing";var oe=h(ce,J,W);if(oe.type==="normal"){if(V=W.done?"completed":"suspendedYield",oe.arg===c)continue;return{value:oe.arg,done:W.done}}oe.type==="throw"&&(V="completed",W.method="throw",W.arg=oe.arg)}}})(C,P,H),G}function h(C,w,P){try{return{type:"normal",arg:C.call(w,P)}}catch(z){return{type:"throw",arg:z}}}a.wrap=l;var c={};function u(){}function f(){}function d(){}var p={};o(p,s,function(){return this});var g=Object.getPrototypeOf,_=g&&g(g(A([])));_&&_!==e&&t.call(_,s)&&(p=_);var m=d.prototype=u.prototype=Object.create(p);function x(C){["next","throw","return"].forEach(function(w){o(C,w,function(P){return this._invoke(w,P)})})}function I(C,w){function P(L,G,H,ce){var J=h(C[L],C,G);if(J.type!=="throw"){var W=J.arg,V=W.value;return V&&typeof V=="object"&&t.call(V,"__await")?w.resolve(V.__await).then(R=>{P("next",R,H,ce)},R=>{P("throw",R,H,ce)}):w.resolve(V).then(R=>{W.value=R,H(W)},R=>P("throw",R,H,ce))}ce(J.arg)}var z;this._invoke=(L,G)=>{function H(){return new w((ce,J)=>{P(L,G,ce,J)})}return z=z?z.then(H,H):H()}}function T(C,w){var P=C.iterator[w.method];if(P===void 0){if(w.delegate=null,w.method==="throw"){if(C.iterator.return&&(w.method="return",w.arg=void 0,T(C,w),w.method==="throw"))return c;w.method="throw",w.arg=new TypeError("The iterator does not provide a 'throw' method")}return c}var z=h(P,C.iterator,w.arg);if(z.type==="throw")return w.method="throw",w.arg=z.arg,w.delegate=null,c;var L=z.arg;return L?L.done?(w[C.resultName]=L.value,w.next=C.nextLoc,w.method!=="return"&&(w.method="next",w.arg=void 0),w.delegate=null,c):L:(w.method="throw",w.arg=new TypeError("iterator result is not an object"),w.delegate=null,c)}function y(C){var w={tryLoc:C[0]};1 in C&&(w.catchLoc=C[1]),2 in C&&(w.finallyLoc=C[2],w.afterLoc=C[3]),this.tryEntries.push(w)}function b(C){var w=C.completion||{};w.type="normal",delete w.arg,C.completion=w}function S(C){this.tryEntries=[{tryLoc:"root"}],C.forEach(y,this),this.reset(!0)}function A(C){if(C){var w=C[s];if(w)return w.call(C);if(typeof C.next=="function")return C;if(!isNaN(C.length)){var P=-1,z=function L(){for(;++P{var w=typeof C=="function"&&C.constructor;return!!w&&(w===f||(w.displayName||w.name)==="GeneratorFunction")},a.mark=C=>(Object.setPrototypeOf?Object.setPrototypeOf(C,d):(C.__proto__=d,o(C,r,"GeneratorFunction")),C.prototype=Object.create(m),C),a.awrap=C=>({__await:C}),x(I.prototype),o(I.prototype,n,function(){return this}),a.AsyncIterator=I,a.async=(C,w,P,z,L)=>{L===void 0&&(L=Promise);var G=new I(l(C,w,P,z),L);return a.isGeneratorFunction(w)?G:G.next().then(H=>H.done?H.value:G.next())},x(m),o(m,r,"Generator"),o(m,s,function(){return this}),o(m,"toString",()=>"[object Generator]"),a.keys=C=>{var w=[];for(var P in C)w.push(P);return w.reverse(),function z(){for(;w.length;){var L=w.pop();if(L in C)return z.value=L,z.done=!1,z}return z.done=!0,z}},a.values=A,S.prototype={constructor:S,reset:function(C){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(b),!C)for(var w in this)w.charAt(0)==="t"&&t.call(this,w)&&!isNaN(+w.slice(1))&&(this[w]=void 0)},stop:function(){this.done=!0;var C=this.tryEntries[0].completion;if(C.type==="throw")throw C.arg;return this.rval},dispatchException:function(C){if(this.done)throw C;var w=this;function P(J,W){return G.type="throw",G.arg=C,w.next=J,W&&(w.method="next",w.arg=void 0),!!W}for(var z=this.tryEntries.length-1;z>=0;--z){var L=this.tryEntries[z],G=L.completion;if(L.tryLoc==="root")return P("end");if(L.tryLoc<=this.prev){var H=t.call(L,"catchLoc"),ce=t.call(L,"finallyLoc");if(H&&ce){if(this.prev=0;--P){var z=this.tryEntries[P];if(z.tryLoc<=this.prev&&t.call(z,"finallyLoc")&&this.prev=0;--w){var P=this.tryEntries[w];if(P.finallyLoc===C)return this.complete(P.completion,P.afterLoc),b(P),c}},catch:function(C){for(var w=this.tryEntries.length-1;w>=0;--w){var P=this.tryEntries[w];if(P.tryLoc===C){var z=P.completion;if(z.type==="throw"){var L=z.arg;b(P)}return L}}throw new Error("illegal catch attempt")},delegateYield:function(C,w,P){return this.delegate={iterator:A(C),resultName:w,nextLoc:P},this.method==="next"&&(this.arg=void 0),c}},a}function Fa(a){return Fa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?e=>typeof e:e=>e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e,Fa(a)}function Nl(a,e,t,i,s,n,r){try{var o=a[n](r),l=o.value}catch(h){return void t(h)}o.done?e(l):Promise.resolve(l).then(i,s)}function zi(a){return function(){var e=this,t=arguments;return new Promise((i,s)=>{var n=a.apply(e,t);function r(l){Nl(n,i,s,r,o,"next",l)}function o(l){Nl(n,i,s,r,o,"throw",l)}r(void 0)})}}function It(a,e){if(!(a instanceof e))throw new TypeError("Cannot call a class as a function")}function Ul(a,e){for(var t=0;t"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],()=>{})),!0}catch{return!1}}();return function(){var t,i=Er(a);if(e){var s=Er(this).constructor;t=Reflect.construct(i,arguments,s)}else t=i.apply(this,arguments);return zb(this,t)}}function kl(a,e){return function(t){if(Array.isArray(t))return t}(a)||function(t,i){var s=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(s!=null){var n,r,o=[],l=!0,h=!1;try{for(s=s.call(t);!(l=(n=s.next()).done)&&(o.push(n.value),!i||o.length!==i);l=!0);}catch(c){h=!0,r=c}finally{try{l||s.return==null||s.return()}finally{if(h)throw r}}return o}}(a,e)||wo(a,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Vl(a){return function(e){if(Array.isArray(e))return La(e)}(a)||function(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}(a)||wo(a)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function wo(a,e){if(a){if(typeof a=="string")return La(a,e);var t=Object.prototype.toString.call(a).slice(8,-1);return t==="Object"&&a.constructor&&(t=a.constructor.name),t==="Map"||t==="Set"?Array.from(a):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?La(a,e):void 0}}function La(a,e){(e==null||e>a.length)&&(e=a.length);for(var t=0,i=new Array(e);tsetTimeout(a)).then(()=>Date.now())}var Wb=Math.PI/2,Xb=new v(2,2,2),Gl=function(){function a(){It(this,a),this.tool=0,this.start=v.Zero(),this.end=v.Zero(),this.extruding=!1,this.gcodeLineNumber=0,this.gcodeFilePosition=0,this.color=null,this.feedRate=0,this.layerHeight=0,this.isPerimeter=!1}return At(a,[{key:"length",value:function(){return v.Distance(this.start,this.end)}},{key:"renderLine",value:function(e){var t=[this.start,this.end],i=Qt.CreateLines("lines",t,e);i.enableEdgesRendering(),i.edgesWidth=10,i.edgesColor=new X(1,1,0,1)}},{key:"renderLinev4",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:.4,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;this.layerHeight===0&&(this.layerHeight=this.start.y);var i={},s=this.length()+t,n=this.start.add(this.end).divide(Xb),r=this.end.subtract(this.start),o=Math.sqrt(Math.pow(r.x,2)+Math.pow(r.y,2)+Math.pow(r.z,2)),l=Math.atan2(r.z,r.x),h=Math.acos(r.y/o);return i.matrix=O.Compose(new v(s,this.layerHeight,e),le.FromEulerVector(new v(0,-l,Wb-h)),n),i.color=this.color,i.props={gcodeLineNumber:this.gcodeLineNumber,gcodeFilePosition:this.gcodeFilePosition,originalColor:this.color},i}},{key:"renderParticle",value:function(e){e.position.x=this.start.x,e.position.y=this.start.y,e.position.z=this.start.z,e.color=this.color}},{key:"getPoints",value:function(){return{points:[this.start,this.end],colors:[this.color,this.color]}}},{key:"getColor",value:function(){return this.extruding?new X(1,1,1,1):new X(1,0,0,1)}},{key:"getVoxelSegments",value:function(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,s=arguments.length>3?arguments[3]:void 0,n=new Array,r=v.Distance(this.start,this.end);if(!(r<.1)){var o=Math.round(100*(r/(e/2)-1))/100,l=Math.atan2(this.end.z-this.start.z,this.end.x-this.start.x);s&&(this.start.y-=e/2,this.end.y-=e/2);var h=this.start.clone(),c=0;n.push(h.clone());var u=e/2*Math.cos(l),f=e/2*Math.sin(l),d=0;for(o!==0&&(d=(this.end.y-this.start.y)/o);ce)for(var p=h.x-i;p<=h.x+i;p+=e)for(var g=h.z-i;gt&&s){for(var _=[],m=0;m5e4||this.currentFilePositionthis.scrubDistance&&e>=t-1e3&&e<=i+1e3}},{key:"getTransparentValue",value:function(){return this.vertexAlpha?this.transparentValue:0}},{key:"canUpdateColor",value:function(){return this.colorMode==Ji.Color&&!this.hasMixing}},{key:"forceDraw",value:function(){this.timeStamp=0}}]),a}(),Hb=function(a){Ki(t,Kr);var e=Yi(t);function t(i,s,n,r,o,l){var h;return It(this,t),(h=e.call(this,i,s,n,r,o)).meshIndex=l!=null?l:0,h.lostInSpace=O.Identity().setTranslation(new v(1e4,1e4,1e4)),h.additiveColor=new X(0,1,0,.8),h}return At(t,[{key:"buildBox",value:function(){if(this.solidMat)try{this.solidMat.dispose(),this.solidMat=null}catch{console.warn("nothing to dispose")}if(this.transparentMat)try{this.transparentMat.dispose(),this.transparentMat=null}catch{console.warn("nothing to dispose")}var i=Qt.CreateBox("box",{width:1,height:1,depth:1,sideOrientation:F.FRONTSIDE},this.scene);return this.material=new te("mat",this.scene),this.material.specularColor=this.specularColor,i.material=this.material,this.vertexAlpha&&(i.hasVertexAlpha=!0,i.material.forceDepthWrite=!0,i.material.alpha=.99),i}},{key:"render",value:function(i){for(var s=this,n=new Array(i.length),r=0,o=new Array(i.length),l=0;l.5&&p[L+3]<1){p[L+3]+=.02;var G=10*(p[L+3]-.9);p[L]=s.lerp(s.progressColor.r,n[P].color.r,G),p[L+1]=s.lerp(s.progressColor.g,n[P].color.g,G),p[L+2]=s.lerp(s.progressColor.b,n[P].color.b,G),C=!0}p[L+3]>=1&&!g[P]&&(n[P].color.toArray(p,L),p[L+3]=1,g[P]=!0,C=!0)}}else o[P]<=s.currentFilePosition?(n[P].color.toArray(p,L),n[P].matrix.copyToArray(d,16*P),p[L+3]=1,g[P]=!0):(s.getTransparentValue()===0?s.lostInSpace.copyToArray(d,16*P):n[P].matrix.copyToArray(d,16*P),p[L+3]=s.getTransparentValue(),g[P]=!1)}C&&x.thinInstanceBufferUpdated("color"),w&&(x.thinInstanceBufferUpdated("matrix"),x.thinInstanceRefreshBoundingInfo())};if(i.length!==0){var T=i[0].gcodeFilePosition,y=i.slice(-1)[0].gcodeFilePosition,b=0,S=!1,A=!1;this.timeStamp=Date.now();var M=function(){if(!(s.isLoading||Date.now()-s.timeStamp<200)){if(s.timeStamp=Date.now(),s.doScrub(b,T,y)||s.forceRedraw){S=!0,s.forceRedraw=!1,b=0;for(var C=0;C=T-3e4&&s.currentFilePosition<=y+3e4?(S=!1,A&&x.unfreezeWorldMatrix(),I()):A||(x.freezeWorldMatrix(),A=!0);b=s.currentFilePosition}};this.renderFuncs.push(M),this.scene.registerBeforeRender(M)}}}]),t}(),Kb=function(a){Ki(t,Kr);var e=Yi(t);function t(i,s,n,r,o,l){var h;return It(this,t),(h=e.call(this,i,s,n,r,o)).meshIndex=l!=null?l:0,h.lostInSpace=O.Identity().setTranslation(new v(1e4,1e4,1e4)),h.additiveColor=new X(0,1,0,.8),h}return At(t,[{key:"buildCylinder",value:function(){if(this.solidMat)try{this.solidMat.dispose(),this.solidMat=null}catch{console.warn("nothing to dispose")}if(this.transparentMat)try{this.transparentMat.dispose(),this.transparentMat=null}catch{console.warn("nothing to dispose")}var i=Qt.CreateCylinder("box",{height:1,diameter:1},this.scene);return i.locallyTranslate(new v(0,0,0)),i.rotate(new v(0,0,1),Math.PI/2,ci.WORLD),i.bakeCurrentTransformIntoVertices(),this.material=new te("mat",this.scene),this.material.specularColor=this.specularColor,i.material=this.material,this.vertexAlpha&&(i.hasVertexAlpha=!0,i.material.forceDepthWrite=!0,i.material.alpha=.99),i}},{key:"render",value:function(i){for(var s=this,n=new Array(i.length),r=0,o=new Array(i.length),l=0;l.5&&p[L+3]<1){p[L+3]+=.02;var G=10*(p[L+3]-.9);p[L]=s.lerp(s.progressColor.r,n[P].color.r,G),p[L+1]=s.lerp(s.progressColor.g,n[P].color.g,G),p[L+2]=s.lerp(s.progressColor.b,n[P].color.b,G)}p[L+3]>=1&&!g[P]&&(n[P].color.toArray(p,L),p[L+3]=1,g[P]=!0,C=!0)}}else o[P]<=s.currentFilePosition?(n[P].color.toArray(p,L),n[P].matrix.copyToArray(d,z),p[L+3]=1,g[P]=!0):(s.getTransparentValue()===0?s.lostInSpace.copyToArray(d,z):n[P].matrix.copyToArray(d,z),p[L+3]=s.getTransparentValue(),g[P]=!1)}C&&x.thinInstanceBufferUpdated("color"),w&&(x.thinInstanceBufferUpdated("matrix"),x.thinInstanceRefreshBoundingInfo())};if(i.length!==0){var T=i[0].gcodeFilePosition,y=i.slice(-1)[0].gcodeFilePosition,b=0,S=!1,A=!1;this.timeStamp=Date.now();var M=function(){if(!(s.isLoading||Date.now()-s.timeStamp<200)){if(s.timeStamp=Date.now(),s.doScrub(b,T,y)||s.forceRedraw){S=!0,s.forceRedraw=!1,b=0;for(var C=0;C=T-3e4&&s.currentFilePosition<=y+3e4?(S=!1,A&&x.unfreezeWorldMatrix(),I()):A||(A=!0,x.freezeWorldMatrix());b=s.currentFilePosition}};this.renderFuncs.push(M),this.scene.registerBeforeRender(M)}}}]),t}(),Yb=At(function a(e,t){It(this,a),this.filePosition=e,this.add=t,this.complete=!1}),Tu=function(a){Ki(i,Kr);var e,t=Yi(i);function i(s,n,r,o,l,h,c){var u;return It(this,i),(u=t.call(this,s,n,r,o,l)).voxelWidth=parseFloat(h),u.voxelHeight=parseFloat(c),u.solidMat,u.transparentMat,u.hasSubtractive=!1,u.lostInSpace=O.Identity().setTranslation(new v(1e4,1e4,1e4)),u.clearColor=new X(1,0,0,0),u.additiveColor=new X(0,1,0,.8),u.subtractiveColor=new X(1,0,0,.8),u}return At(i,[{key:"buildBox",value:function(){if(this.solidMat)try{this.solidMat.dispose(),this.solidMat=null}catch{}if(this.transparentMat)try{this.transparentMat.dispose(),this.transparentMat=null}catch{}var s=Qt.CreateBox("box",{width:this.voxelWidth,height:this.voxelHeight,depth:this.voxelWidth},this.scene);return s.hasVertexAlpha=!0,s.updateFacetData=!0,this.material=new te("mat",this.scene),this.material.needDepthPrePass=!0,this.material.forceDepthWrite=!0,this.material.backFaceCulling=!1,s.material=this.material,s}},{key:"render",value:(e=zi(yt().mark(function s(n){var r,o,l,h,c,u,f,d,p,g,_,m,x,I,T,y,b,S,A,M,C,w=this;return yt().wrap(function(P){for(;;)switch(P.prev=P.next){case 0:for(this.isLoading=!0,r=parseInt(300/this.voxelWidth)+1,o=r,l=parseInt(300/this.voxelHeight)+1,h=new Array(o),c=0;c<=l;c++)h[c]=new Object;u=0,f=new Date,d=0;case 10:if(!(d5e3)){P.next=57;break}return f=new Date,this.loadingProgressCallback(d/n.length,"Generating Voxel Map..."),P.next=57,Ir();case 57:x++,P.next=22;break;case 60:d++,P.next=10;break;case 63:this.loadingProgressCallback(d/n.length,"Rendering Voxel..."),M=yt().mark(function z(L){var G,H,ce,J,W,V,R,k,Y,he,oe,re,ue,xe,ae,Me,ke,Z,Ee,Oe,He,je,Ct,wt,ri,ei,Ht,Bi,ys;return yt().wrap(Ti=>{for(;;)switch(Ti.prev=Ti.next){case 0:if(G=[],h[L]!==void 0){Ti.next=3;break}return Ti.abrupt("return","continue");case 3:for(H=999999999999,ce=-999999999999,J=[],W=0,V=Object.entries(h[L]);Wce&&(ce=ae.voxelEvents[0].filePosition),(re=J).push.apply(re,Vl(ae.voxelEvents.map(Kt=>Kt.filePosition))),ae.color.a=1,(Me={matrix:O.Identity(),color:ae.color.clone(),voxelEvents:ae.voxelEvents,lastDrawnCount:0}).matrix.setTranslation(new v(k*w.voxelWidth,L*w.voxelHeight,xe*w.voxelWidth)),G.push(Me);for(ke=0,J=J.sort((Kt,ai)=>Kt-ai),J=Vl(new Set(J)),G.length,h[L]=null,(Z=w.buildBox()).alphaIndex=L,Z.renderingGroupId=1,Ee=new Float32Array(16*G.length),Oe=new Float32Array(4*G.length),He=0;He{for(var Kt=!1,ai=!1,zt=0;ztXn.filePositionwt&&qi.filePosition<=w.currentFilePosition&&(qt.lastDrawnCount=0,w.hasSubtractive&&qt.matrix.copyToArray(Ee,16*zt)),ei&&(qt.lastDrawnCount=i.drawDelay),qt.lastDrawnCount=wt&&qi.filePosition<=w.currentFilePosition&&(qt.lastDrawnCount=0),ei&&(qt.lastDrawnCount=i.drawDelay),qt.lastDrawnCount{if(!(w.isLoading||Date.now()-Bi<200)){if(Bi=Date.now(),w.doScrub(wt,H,ce)||ri||w.forceRedraw){ke=0,ei=!0,w.forceRedraw=!1;for(var Kt=0;Ktzt.complete=!1);Ct(),ri=!1}else if(kew.currentFilePosition));ai++);}else Ht<10&&(Ht++,Ct());wt=w.currentFilePosition}},w.loadingProgressCallback&&w.loadingProgressCallback(L/u,"Rendering Voxels..."),w.renderFuncs.push(ys),w.scene.registerBeforeRender(ys),!(new Date-f>1e3)){Ti.next=36;break}return f=new Date,Ti.next=36,Ir();case 36:case"end":return Ti.stop()}},z,this)}),C=0;case 67:if(!(CW===!1);G<=C;G++){var H=8*G;if(l[G]){if(h[G])continue;s.progressMode||M[H+3]<=.5?(M[H]=s.progressColor.r,M[H+1]=s.progressColor.g,M[H+2]=s.progressColor.b,M[H+3]=.9,M[H+4]=s.progressColor.r,M[H+5]=s.progressColor.g,M[H+6]=s.progressColor.b,M[H+7]=.9):M[H+3]<1?(M[H+3]+=.02,M[H+7]+=.02):M[H+3]>=1&&(M[H]=o[G][0].r,M[H+1]=o[G][0].g,M[H+2]=o[G][0].b,M[H+3]=1,M[H+4]=o[G][1].r,M[H+5]=o[G][1].g,M[H+6]=o[G][1].b,M[H+7]=1,h[G]=!0)}else{if(h[G])continue;M[H+3]===0?(M[H]=1,M[H+1]=0,M[H+2]=0,M[H+3]=.9,M[H+4]=1,M[H+5]=0,M[H+6]=0,M[H+7]=.9):M[H+3]<1?(M[H+3]+=.02,M[H+7]+=.02):(M[H+3]=1e-4,M[H+7]=1e-4,h[G]=!0)}y=G}for(var ce=C;ce=m-3e4&&s.currentFilePosition<=x+3e4&&(T=!1,b());I=s.currentFilePosition}};this.renderFuncs.push(A),this.scene.registerBeforeRender(A)}}]),t}(),Ns=function(){function a(){It(this,a),yu(this,"unknownFeatureColor",new X(.5,.5,.5,1)),this.feature=null,this.perimeter=!0,this.support=!1,this.missingFeatures=[]}return At(a,[{key:"isTypeComment",value:function(e){return!1}},{key:"getFeatureColor",value:function(e){return new X(1,1,1,1)}},{key:"isPerimeter",value:function(){return this.perimeter}},{key:"isSupport",value:function(){return this.support}},{key:"processComments",value:function(e,t){}},{key:"reportMissingFeature",value:function(e){this.missingFeatures.includes(e)||(console.error("Missing feature ".concat(e)),this.missingFeatures.push(e))}}]),a}(),qb=function(a){Ki(t,Ns);var e=Yi(t);function t(){var i;return It(this,t),(i=e.call(this)).featureList={Perimeter:{color:new X(1,.9,.3,1),perimeter:!1,support:!1},"External perimeter":{color:new X(1,.5,.2,1),perimeter:!0,support:!1},"Internal infill":{color:new X(.59,.19,.16,1),perimeter:!1,support:!1},"Solid infill":{color:new X(.59,.19,.8,1),perimeter:!1,support:!1},"Top solid infill":{color:new X(.95,.25,.25,1),perimeter:!0,support:!1},"Bridge infill":{color:new X(.3,.5,.73,1),perimeter:!1,support:!1},"Gap fill":{color:new X(1,1,1,1),perimeter:!1,support:!1},Skirt:{color:new X(0,.53,.43,1),perimeter:!1,support:!1},"Skirt/Brim":{color:new X(0,.53,.43,1),perimeter:!1,support:!1},"Supported material":{color:new X(0,1,0,1),perimeter:!1,support:!0},"Supported material interface":{color:new X(0,.5,0,1),perimeter:!1,support:!0},Custom:{color:new X(.5,.5,.5,1),perimeter:!1,support:!1},Unknown:{color:new X(.5,.5,.5,1),perimeter:!1,support:!1},"Support material":{color:new X(.5,.5,.5,1),perimeter:!1,support:!0},"Support material interface":{color:new X(.5,.5,.5,1),perimeter:!1,support:!0},"Overhang perimeter":{color:new X(.5,.5,.5,1),perimeter:!0,support:!1},"Wipe tower":{color:new X(.5,.5,.5,1),perimeter:!0,support:!1}},i}return At(t,[{key:"isTypeComment",value:function(i){return!!i.trim().startsWith(";TYPE:")&&(this.feature=i.substring(6).trim(),!0)}},{key:"getFeatureColor",value:function(){if(Object.prototype.hasOwnProperty.call(this.featureList,this.feature))try{return this.featureList[this.feature].color}catch{this.reportMissingFeature(this.feature)}return this.unknownFeatureColor}},{key:"isPerimeter",value:function(){try{return this.featureList[this.feature].perimeter}catch{return this.reportMissingFeature(this.feature),!0}}},{key:"isSupport",value:function(){try{return this.featureList[this.feature].support}catch{return this.reportMissingFeature(this.feature),!1}}},{key:"processComments",value:function(i,s){try{for(var n=i.length-350;n{},this.hasSpindle=!1,this.voxelWidth=1,this.voxelHeight=1,this.forceVoxels=!1,this.renderInstances=new Array,this.meshIndex=0,this.highQualityExtrusion=!1,this.perimeterOnly=!1,this.lastUpdate=Date.now(),this.g1AsExtrusion=!1,this.firstGCodeByte=0,this.lastGCodeByte=0,this.zBelt=!1,this.gantryAngle=45*Math.PI/180,this.hyp=Math.cos(this.gantryAngle),this.adj=Math.tan(this.gantryAngle),this.currentZ=0,this.beltLength=100,this.nozzleStartPosition=new v(0,0,0),this.nozzlePosition=new v(0,0,0),this.nozzleFeedRate=0,this.firmwareRetraction=!1,this.inches=!1,this.fixRadius=!1,this.csysContainers=new Array,this.lastCommand="G0",this.arcPlane="XY",this.workplaceOffsets=[new v(0,0,0),new v(0,0,0)],this.currentWorkplace=0,this.progressMode=!1,this.transparentValue=.25,this.hasMixing=!1,this.renderAnimation=!0}var e,t,i,s,n;return At(a,[{key:"doUpdate",value:function(){this.lastUpdate=Date.now()}},{key:"setProgressColor",value:function(r){var o=this;this.progressColor=X.FromHexString(r.padEnd(9,"F")),this.renderInstances.forEach(l=>l.progressColor=o.progressColor)}},{key:"getMaxHeight",value:function(){return this.maxHeight+1}},{key:"getMinHeight",value:function(){return this.minHeight}},{key:"setRenderQualitySettings",value:function(r,o){if(this.forceVoxels)return this.renderVersion=Es.Voxel,this.meshBreakPoint=Wl,void(this.lines=new Array(Wl));this.lines=new Array(1.5*this.meshBreakPoint),o===void 0&&(o=1);var l=0,h=this.forceWireMode?2:1,c=2;switch(this.refreshTime=5e3,this.everyNthRow=1,this.renderTravels=!0,o){case 1:h=2,this.refreshTime=3e4,l=25e3,c=50,this.renderTravels=!1;break;case 2:h=2,this.refreshTime=3e4,l=5e5,c=10,this.renderTravels=!1;break;case 3:l=1e6,c=3;break;case 4:l=15e6,c=2;break;case 5:l=25e6;break;default:return this.renderVersion=Es.Block,void(this.everyNthRow=1)}for(var u=h;u<4;u++){var f=void 0;switch(u){case 1:f=24;break;case 2:f=2;break;case 3:f=1}for(var d=this.everyNthRow;d<=c;d++)if(this.debug&&console.log("Mode: "+u+" NRow: "+d+" vertexcount: "+r*f/d),r*f/d0&&(p.extruding=!0,this.maxHeight=this.currentPosition.y);break;case"F":if(this.currentFeedRate=Number(m.substring(1)),p.feedRate=this.currentFeedRate,this.currentFeedRate>this.maxFeedRate&&(this.maxFeedRate=this.currentFeedRate),this.currentFeedRate=1?this.maxFeedColor:x<=0?this.minFeedColor:X.Lerp(this.minFeedColor,this.maxFeedColor,x)}}}if(this.zBelt&&(this.beltLength=this.currentPosition.z1&&p.extruding&&(this.currentPosition.y>this.currentZ&&(this.currentRowIdx++,this.currentRowIdx%3==0&&this.currentRowIdx++,this.currentZ=this.currentPosition.y),this.currentRowIdx%this.everyNthRow==0&&this.currentRowIdx>2)))){var I=this.hasSpindle&&c[0]==="G1",T=this.g1AsExtrusion||p.length()>=this.lineLengthTolerance;h&&(this.renderedLines.push(p),p.extruding&&this.lastZExtrusionthis.currentLayerHeight&&!this.isSupport&&g&&(this.previousLayerHeight=this.currentLayerHeight,this.currentLayerHeight=this.currentPosition.y)):this.renderTravels&&!p.extruding&&(p.color=new X(1,0,0,1),this.travels.push(p)),this.zBelt?p.layerHeight=Math.abs(this.currentLayerHeight-this.previousLayerHeight):this.g1AsExtrusion?p.layerHeight=1:p.layerHeight=this.currentLayerHeight-this.previousLayerHeight)}}},{key:"g2g3",value:function(r,o,l,h){var c=this,u=r.split(/(?=[GXYZIJKFREUVAB])/),f=r.indexOf("E")>0||this.g1AsExtrusion,d=u.filter(_=>_==="G2"||_==="G02"),p={position:this.currentPosition.clone(),points:[]};try{p=function(_,m,x,I,T,y,b){for(var S=new v(m.x,m.z,m.y),A=S.clone(),M=0,C=0,w=0,P=_.some(Bi=>Bi.includes("G2")),z=0;z<_.length;z++){var L=_[z];switch(L[0]){case"X":A.x=Gs(L,A.x,x,b.x);break;case"Y":A.y=Gs(L,A.y,x,b.y);break;case"Z":A.z=Gs(L,A.z,x,b.z);break;case"I":M=Gs(L,M,!1,0);break;case"J":case"K":C=Gs(L,C,!1,0);break;case"R":w=Gs(L,w,!1,0)}}var G="x",H="y",ce="z";switch(y){case"XY":G="x",H="y",ce="z";break;case"XZ":G="z",H="x",ce="y";var J=C;C=M,M=J;break;case"YZ":G="y",H="z",ce="x"}if(w){var W=A[G]-S[G],V=A[H]-S[H],R=Math.pow(W,2)+Math.pow(V,2);if(R===0)return{position:S.clone(),points:[]};var k=Math.pow(w,2)-R/4,Y=0;if(k>=0)Y=Math.sqrt(k/R);else if(k<-.02*Math.pow(w,2)){if(!T)return console.error("G2/G3: Radius too small"),{position:{x:A.x,y:A.z,z:A.y},points:[]};var he=Math.sqrt(Math.pow(W/2,2)+Math.pow(V/2,2));k=Math.pow(he,2)-R/4,Y=Math.sqrt(k/R)}(P&&w<0||!P&&w>0)&&(Y=-Y),M=W/2+V*Y,C=V/2-W*Y}else if(M===0&&C===0)return{position:S.clone(),points:[]};var oe,re=S[G]===A[G]&&S[H]===A[H],ue=S[G]+M,xe=S[H]+C,ae=Math.sqrt(M*M+C*C),Me=Math.atan2(-C,-M),ke=Math.atan2(A[H]-xe,A[G]-ue);re?oe=2*Math.PI:(oe=P?Me-ke:ke-Me)<0&&(oe+=2*Math.PI);var Z=ae*oe/I;Z<1&&(Z=1);var Ee=oe/Z;Ee*=P?-1:1;for(var Oe=new Array,He=(A[ce]-S[ce])/Z,je=S[G],Ct=S[H],wt=S[ce],ri=Me,ei=0;ei{var x=new Gl;x.tool=c.currentTool,x.gcodeLineNumber=o,x.gcodeFilePosition=l,x.feedRate=c.currentFeedRate,x.isPerimeter=c.slicer.isPerimeter(),c.g1AsExtrusion?x.layerHeight=1:x.layerHeight=c.currentLayerHeight-c.previousLayerHeight,x.start=g.clone(),x.end=new v(_.x,_.y,_.z),x.extruding=f,x.color=f?c.currentColor.clone():new X(1,0,0,1),c.debug&&(x.color=d?new X(0,1,1,1):new X(1,1,0,1),m===0&&(x.color=new X(0,1,0,1))),g=x.end.clone(),c.debug&&console.log(x),h&&(c.renderedLines.push(x),x.extruding?c.lines[c.linesIndex++]=x:c.travels.push(x))}),this.currentPosition=new v(g.x,g.y,g.z),this.currentPosition.y>this.currentLayerHeight&&!this.isSupport&&(this.previousLayerHeight=this.currentLayerHeight,this.currentLayerHeight=this.currentPosition.y)}},{key:"m567",value:function(r){var o=r.split(/(?=[PE])/),l=[1,1,1];if(this.colorMode!==Ji.Feed){for(var h=1;h0&&(this.firstGCodeByte=f),this.lastGCodeByte=f,this.processLine(p,d,f,g)),!(Date.now()-this.timeStamp>10)){_.next=33;break}return this.loadingProgressCallback&&this.loadingProgressCallback(f/o.length,"Loading File..."),_.next=32,Ir();case 32:this.timeStamp=_.sent;case 33:this.doUpdate(),_.next=19;break;case 36:if(this.layerDictionary.push(o.length),!this.renderTravels){_.next=40;break}return _.next=40,this.createTravelLines(this.scene);case 40:this.loadingProgressCallback&&this.loadingProgressCallback(1),o={};case 42:case"end":return _.stop()}},r,this)})),function(r,o,l){return n.apply(this,arguments)})},{key:"loadingComplete",value:function(){this.renderInstances.forEach(r=>r.isLoading=!1),this.updateFilePosition(Number.MAX_VALUE-1),this.updateFilePosition(Number.MAX_VALUE)}},{key:"processLine",value:(s=zi(yt().mark(function r(o,l,h){var c,u,f,d,p,g,_,m,x,I,T,y,b=arguments;return yt().wrap(function(S){for(;;)switch(S.prev=S.next){case 0:if(c=!(b.length>3&&b[3]!==void 0)||b[3],(u=o.indexOf(";"))>-1&&(o=o.substring(0,u-1).trim()),o=o.toUpperCase(),(d=o.match(/[GM]+[0-9.]+/g))===null&&o.match(/[XYZ]+[+-]?[0-9.]+/g)!==null&&(d=this.lastCommand),!d){S.next=61;break}p=0;case 8:if(!(pA.trim()==="X")&&(this.currentPosition.x=this.workplaceOffsets[this.currentWorkplace].x),f.some(A=>A.trim()==="Y")&&(this.currentPosition.z=this.workplaceOffsets[this.currentWorkplace].y),f.some(A=>A.trim()==="Z")&&(this.currentPosition.y=this.workplaceOffsets[this.currentWorkplace].z)),S.abrupt("break",55);case 31:return S.abrupt("break",55);case 32:return this.currentWorkplace=54-Number(d[p].substring(1)),this.currentPosition=this.workplaceOffsets[this.currentWorkplace].clone(),S.abrupt("break",55);case 35:return this.currentWorkplace=10*(58.6-Number(d[p].substring(1))),this.currentPosition=this.workplaceOffsets[this.currentWorkplace].clone(),S.abrupt("break",55);case 38:return this.absolute=!0,S.abrupt("break",55);case 40:return this.absolute=!1,S.abrupt("break",55);case 42:return S.abrupt("break",55);case 43:return this.hasSpindle=!0,S.abrupt("break",55);case 45:return g=o.split(/(?=[SM])/),(_=(_=g.filter(A=>A.startsWith("S")))[0]?Number(_[0].substring(1)):0)>0&&(this.hasSpindle=!0),S.abrupt("break",55);case 50:return this.hasMixing=!0,this.m567(o),S.abrupt("break",55);case 53:try{this.currentTool++,this.currentTool>=this.tools.length&&(this.currentTool=0),this.colorMode!==Ji.Feed&&(this.currentColor=this.tools[this.currentTool].color.clone())}catch(A){console.log(A)}return S.abrupt("break",55);case 55:this.lastCommand=d;case 56:p++,S.next=8;break;case 59:S.next=63;break;case 61:o.startsWith("T")&&(m=Number.parseInt(o.substring(1),10),isNaN(m)||(this.currentPosition.z+=10,this.currentTool=m,this.currentTool>=this.tools.length?this.currentTool=this.currentTool%this.tools.length:m<0&&(this.currentTool=0),this.colorMode!==Ji.Feed&&((y=Number(o.substring(1))%this.extruderCount)<0&&(y=0),this.currentColor=(x=(I=this.tools[y])===null||I===void 0||(T=I.color)===null||T===void 0?void 0:T.clone())!==null&&x!==void 0?x:new pe(1,0,0)))),this.debug&&console.log(o);case 63:if(!(this.linesIndex>=this.meshBreakPoint)){S.next=70;break}return S.next=66,this.createMesh(this.scene);case 66:return S.next=68,Ir();case 68:this.doUpdate(),this.meshIndex++;case 70:case"end":return S.stop()}},r,this)})),function(r,o,l){return s.apply(this,arguments)})},{key:"createMesh",value:(i=zi(yt().mark(function r(o){var l,h,c;return yt().wrap(function(u){for(;;)switch(u.prev=u.next){case 0:if(this.zBelt&&(l=this.lines[this.linesIndex-1].layerHeight,this.lines.forEach(f=>{f.layerHeight=l})),this.renderVersion===Es.Line||this.renderVersion===Es.Point?h=new zl(o,this.specularColor,this.loadingProgressCallback,this.renderFuncs,this.tools,this.meshIndex):this.renderVersion===Es.Block?h=this.highQualityExtrusion?new Kb(o,this.specularColor,this.loadingProgressCallback,this.renderFuncs,this.tools,this.meshIndex):new Hb(o,this.specularColor,this.loadingProgressCallback,this.renderFuncs,this.tools,this.meshIndex):this.renderVersion===Es.Voxel&&(h=new Tu(o,this.specularColor,this.loadingProgressCallback,this.renderFuncs,this.tools,this.voxelWidth,this.voxelHeight)),h.progressColor=this.progressColor,h.vertexAlpha=this.vertexAlpha,h.g1AsExtrusion=this.g1AsExtrusion,h.progressMode=this.progressMode,h.transparentValue=this.transparentValue,h.hasMixing=this.hasMixing,h.colorMode=this.colorMode,h.renderAnimation=this.renderAnimation,this.renderInstances.push(h),!((c=this.lines.slice(0,this.linesIndex-1))!=null&&c.length>0)){u.next=15;break}return u.next=15,h.render(c);case 15:this.linesIndex=0;case 16:case"end":return u.stop()}},r,this)})),function(r){return i.apply(this,arguments)})},{key:"chunk",value:function(r,o){for(var l=[],h=0,c=r.length;hl.updateFilePosition(r));try{rr+5);o++)this.currentLineNumber=this.renderedLines[o].gcodeLineNumber,this.nozzleStartPosition=this.renderedLines[o].start,this.nozzlePosition=this.renderedLines[o].end,this.nozzleFeedRate=this.renderedLines[o].feedRate,this.lastFilePositionIndex=o;this.doUpdate()}},{key:"updateFilePositionIndex",value:function(r){var o=this;r>=this.renderedLines.length||(this.currentLineNumber=this.renderedLines[r].gcodeLineNumber,this.nozzleStartPosition=this.renderedLines[r].start,this.nozzlePosition=this.renderedLines[r].end,this.nozzleFeedRate=this.renderedLines[r].feedRate,this.lastFilePositionIndex=r,this.renderInstances.forEach(l=>l.updateFilePosition(o.renderedLines[r].gcodeFilePosition)),this.doUpdate())}},{key:"doFinalPass",value:function(){var r=this;this.liveTracking=!0,this.gcodeFilePosition=Number.MAX_VALUE,setTimeout(()=>{r.liveTracking=!1},this.refreshTime+200)}},{key:"updateMesh",value:function(){this.renderVersion===1?console.log("Version 1"):this.renderVersion===2&&console.log("Version 2")}},{key:"unregisterEvents",value:function(){for(var r=0;r2&&arguments[2]!==void 0?arguments[2]:Ba.Extruder,h=new er;h.color=X.FromHexString(r.padEnd(9,"F")),h.updateDarkerValue(),h.diameter=o,h.toolType=l,this.tools.push(h)}},{key:"updateTool",value:function(r,o,l){l{if(l.material!==null&&Object.prototype.hasOwnProperty.call(l.material,"specularColor"))try{l.material.specularColor=o}catch(h){console.error(h)}}),this.scene&&this.scene.render(!0,!0)}},{key:"g1AsExtrusion",value:function(r){this.g1AsExtrusion=r}},{key:"cancel",value:(e=zi(yt().mark(function r(){return yt().wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return this.cancelLoad=!0,o.next=3,this.pauseProcessing();case 3:case"end":return o.stop()}},r,this)})),function(){return e.apply(this,arguments)})},{key:"setZBeltAngle",value:function(r){this.gantryAngle=(90-r)*Math.PI/180,this.hyp=Math.cos(this.gantryAngle),this.adj=Math.tan(this.gantryAngle)}},{key:"setTransparencyValue",value:function(r){this.transparentValue=r,this.renderInstances.forEach(o=>{o.transparentValue=r})}},{key:"setRenderAnimation",value:function(r){var o=this;this.renderAnimation=r,this.renderInstances.forEach(l=>l.renderAnimation=o.renderAnimation)}}]),a}(),Xl=0,iy=1,sy=function(){function a(e){It(this,a),this.buildVolume={x:{min:0,max:100},y:{min:0,max:100},z:{min:0,max:100}};var t=localStorage.getItem("buildVolume");t!==null&&(this.buildVolume=JSON.parse(t)),this.renderMode=Number.parseInt(localStorage.getItem("renderBedMode"),10),this.renderMode||(this.renderMode=Xl),this.bedMesh,this.isDelta=!1,this.scene=e,this.registerClipIgnore=()=>{},this.bedLineColor="#0000FF",this.getBedColor()||this.setBedColor("#0000FF"),this.planeMaterial=this.buildGridMaterial(),this.boxMaterial=new te("bedBoxMaterial",this.scene),this.boxMaterial.alpha=0,this.debug=!1}return At(a,[{key:"setRenderMode",value:function(e){this.renderMode=e,localStorage.setItem("renderBedMode",this.renderMode),this.bedMesh&&(this.scene.removeMesh(this.bedMesh),this.bedMesh.dispose(!1,!0)),this.buildBed(),this.scene.render()}},{key:"buildBed",value:function(){if(!(this.renderMode>1||this.debug)){if(this.bedMesh&&this.bedMesh.isDisposed()&&(this.bedMesh=null),this.bedMesh)return this.bedMesh;switch(this.renderMode){case Xl:this.buildFlatBed();break;case iy:this.buildBox()}return this.bedMesh}}},{key:"setDelta",value:function(e){this.isDelta=e,this.setRenderMode(this.renderMode)}},{key:"buildFlatBed",value:function(){var e=this.getCenter(),t=this.getSize();if(this.isDelta){var i=Math.abs(this.buildVolume.x.max-this.buildVolume.x.min)/2;this.bedMesh=Qt.CreateDisc("BuildPlate",{radius:i},this.scene),this.bedMesh.rotationQuaternion=le.RotationAxis(new v(1,0,0),Math.PI/2),this.bedMesh.material=this.planeMaterial}else{var s=t.x,n=t.y;this.bedMesh=Qt.CreatePlane("BuildPlate",{width:s,height:n},this.scene),this.bedMesh.material=this.planeMaterial,this.bedMesh.rotationQuaternion=le.RotationAxis(new v(1,0,0),Math.PI/2),this.bedMesh.translate(new v(e.x,0,e.y),1,ci.WORLD)}this.registerClipIgnore(this.bedMesh)}},{key:"getCenter",value:function(){return{x:(this.buildVolume.x.max+this.buildVolume.x.min)/2,y:(this.buildVolume.y.max+this.buildVolume.y.min)/2,z:(this.buildVolume.z.max+this.buildVolume.z.min)/2}}},{key:"getSize",value:function(){return{x:Math.abs(this.buildVolume.x.max-this.buildVolume.x.min),y:Math.abs(this.buildVolume.y.max-this.buildVolume.y.min),z:Math.abs(this.buildVolume.z.max-this.buildVolume.z.min)}}},{key:"buildBox",value:function(){var e=this,t=this.getSize(),i=this.getCenter();if(this.isDelta)this.bedMesh=Qt.CreateCylinder("bed",{diameterTop:t.x,diameterBottom:t.x,height:t.z},this.scene),this.bedMesh.position.x=i.x,this.bedMesh.position.y=i.z,this.bedMesh.position.z=i.x,this.bedMesh.alpha=0,this.bedMesh.diffuseColor=new X(0,0,0,0),this.bedMesh.isPickable=!1,this.bedMesh.enableEdgesRendering(void 0,!0),this.bedMesh.renderingGroupId=2,this.scene.setRenderingAutoClearDepthStencil(2,!1,!1,!1),new Gt("hl",this.scene,{isStroke:!0,blurTextureSizeRatio:3}).addMesh(this.bedMesh,this.getBedColor4()),this.bedMesh.onBeforeRenderObservable.add(()=>{e.scene.getEngine().setColorWrite(!1)}),this.bedMesh.onAfterRenderObservable.add(()=>{e.scene.getEngine().setColorWrite(!0)}),this.registerClipIgnore(this.bedMesh);else{this.bedMesh=Qt.CreateBox("bed",{width:t.x,depth:t.y,height:t.z},this.scene);var s=this.getCenter();this.bedMesh.position.x=s.x-this.buildVolume.x.min,this.bedMesh.position.y=s.z-this.buildVolume.z.min,this.bedMesh.position.z=s.y-this.buildVolume.y.min,this.bedMesh.diffuseColor=new X(0,0,0,0),this.bedMesh.enableEdgesRendering(),this.bedMesh.edgesWidth=100,this.bedMesh.material=this.boxMaterial,this.bedMesh.isPickable=!1,this.bedMesh.edgesColor=this.getBedColor4(),this.registerClipIgnore(this.bedMesh)}}},{key:"setVisibility",value:function(e){this.bedMesh&&this.bedMesh.setEnabled(e)}},{key:"commitBedSize",value:function(){localStorage.setItem("buildVolume",JSON.stringify(this.buildVolume)),this.setRenderMode(this.renderMode)}},{key:"buildGridMaterial",value:function(){var e=new Xt("bedMaterial",this.scene);return e.mainColor=new X(0,0,0,0),e.lineColor=pe.FromHexString(this.getBedColor()),e.gridRatio=5,e.opacity=.8,e.majorUnitFrequency=10,e.minorUnitVisibility=.6,e.gridOffset=new v(0,0,0),e}},{key:"getBedColor",value:function(){return localStorage.getItem("bedLineColor")}},{key:"setBedColor",value:function(e){localStorage.setItem("bedLineColor",e),this.renderMode>1||this.planeMaterial&&(this.planeMaterial=this.buildGridMaterial(),this.dispose(),this.buildBed(),this.scene.render())}},{key:"getBedColor4",value:function(){return X.FromHexString(this.getBedColor().padEnd(9,"F"))}},{key:"dispose",value:function(){this.bedMesh&&!this.bedMesh.isDisposed&&this.bedMesh.dispose(!1,!0)}}]),a}(),ny=function(){function a(e){It(this,a),this.scene=e,this.checkerBoard="iVBORw0KGgoAAAANSUhEUgAAAQEAAAEBCAIAAAD3joeqAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAALnSURBVHhe7dZBEYQwFAVBWBtogAv+IhIEsZd4yGG6L/lPwFRl31jqPM/neeZghd98oUoD1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjTAHUaoE4D1GmAOg1QpwHqNECdBqjb7/ueJyscxzHGmIMV9u/75skK7/te1zUHK/gLUacB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA9RpgDoNUKcB6jRAnQao0wB1GqBOA7Rt2x+drw1hSNi5LQAAAABJRU5ErkJggg==",this.xmark="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAADPCAMAAAD1TAyiAAAAkFBMVEX39/eZAAD8//+TAACWAACRAAD4+vr5/PyaAAD39fX18vLy6enr29v18PDm0dG1Y2PewMDYtbWuUFDkzc2jLy+iKSnLlpbRpKS/enrIjo6hJCTbu7u8dHSxWFi4a2vEh4eoOzudEhKdEBDPn5+pQUHq2dmsSUmnODjUqqqhJye0YGCeGRnIk5OrTEy6b2+fHh7/wUBWAAAIiElEQVR4nO2d2ULbOhRF4yNFijNAQiCBMoShhBTo7f//3bUc2kLIIOnsI6ut90v7hLS8ZCVWZJ1Op02bNm3atGnTps0fGGOsizGm6Z4kiiHqDMeT+Wo1vxwPS6IGwI2lqt3qqlf/WPH2DZnpYqnVz3SL5cXUpuWumnucL66Xp1WW14v5UUlWsDlDw0VPaV28i9aqWAyTYRsqJ8fVRdfrXlT/VP9/nvTFOkDDY/UB+Be4uhmSUKMbXRgsis990EqfD0Q6YMvz7cjrZs9Ledm2v7MLVQdG+EFO07udyC7q5UhaNk2KPV3QxSW6A/TQ3Yfs0n0QpTblsTrQgRvsRyhdHWiwln0lSG0Hp3tHWi37dASkpkMX+Y36WIzaDvVBZjeZD2HUXp5r6nMhajPw64C+R7mmC09mMeqK2cNzTX2HoaaJN7MQtRn0PJkr6q+ITy4zCGAWmc2st2dYB2gZ0GIhMJvZR3/PdQcu2a7tKkg0nrqatwM70Otz2yx7gU2Cqe1jcPuaO6/QLFQ0ljrcs2t/wJvBTXiTSGr7GMHMVW0uI0TjqKM8u+ZHnFbpOK5VDHWcZ9f6ijWBxzVaU7MXr2I9V+N7ybjk5ihudNfUJ8wHPZrGMlfUjPFt5/HQheZRc5gLNY5vmv5jNMyjpinjehf6Nf6mpu8c6Io6+r5mea5afo6/qc0Lp2WGa57nKreMmYzXcrRrpucqvXjmzsHVwMPUEa7Znqt2m4SOoeZ7Lopuo9CFvg38GYDGbM88aP4ld9SdEGoIc6HimeOesTYT5JrGgNFVJR6aviJUF/rJ2zXGc1F8Y3w5iX3I2oi3a5RnfR3/OW0fMNC+rlGeC71gfCPjf2D+7IXPbAZjLtSE8UBdgkx7ucYx81bJ6BpHfdrf3xGKXJraljPOuk3sGtm26LO9s1nQr0eHmprx1vvDl713d+V0DzVdYubtOsw1YHrFXf/K9c4RThMgM+dpuk4fdlMXe1wj7+dK9BFzTZI4y2SfssM11DPrm8lb7OG9HiEd2uYa67lQ/D0YZgjt0RbXWM+FmiF+oF5B+6RfNqZWCv4xeP/f5yyPvevVObZXdx+oaQ69pkXB/MnyV7+usdTvXWMnSjdzo3ZLWjD1b9doz2qM2xBgT2So0Z670P2hMq7hnsF7YiVc5+25pvbbH+qbajbL3bML3YBd++++9IqaSmzRBFOHbAP0iAwznhoZKeacqeWY86WWZM6VWpY5T2ppZrf5JjdqeWb4kyY7WvyFsJra9z2WJNGwZ8kD1Bm5TsWck2vcmoEHdSau03muqbNwndJzTZ2B67Se86BO7bmmvgCv3YZmmJ456B3Mv4a5YdcNMTfpWjfG3KDrBpkbc90oc0OuG2ZuwLVuntnrNBAo8/2geWZHndB1xZzHeWAJXWfDnNB1RszJXGfFnMj1xm6V5pPAtdaZMeN3Unxmzs2zC3gP3CfmL8gjqGARpd6zg7jZCFLrL5kyC1Jn69kF+U7Ce+Z8PbuIuM7as4uA68w9u9AEu2uoKJ6yZ+4Yc4Zl1qs0p88yYvpPaNMqd2pTQl/5WEf4GFZuTAn37AJ5LUMqIp5dMnYt5NlF5Upt+kKeXbp5jnCxsb1Olq7N6Ickc5auTf+LLHOGrsU9u2TmOoFnF/WaEXUSzzX1RTbUiTzX1Lm4Tua5ps7DdVLmTKjNwKeEwN9F7X+cPo666fvaDO5TMzfuOqSEAJKacQgVgLkBzzW1VMEPH+ZGPDdK3ZjnBqltc54bo7bD5J9VjVPHH7P+51JXnptPYuoMPLskpc7Cs4u6SUadiWcXwWJsm8xNo75LItfRJUFkksQ1HWXFnMR1dswJXGfILO46S2Zh15ky1+WL/jlmV75IiJoYNZXEo05E9l0hymN86Cb2cVzENU3BR6bNRi9garhrQOmXD+nOCL3cpNGu8Z4Jv0kF/Mkl4Nn9WTP6hqVG/gpgJTyvqbGuu2PYCDfg5+d32yjQrgvU2y2mDzy4v9jY9Ai+rzXqtgbWpXDZ2C5jRmfIP9/lHl3/xow9f/vTRmasa1Ydz9+BlioouvNPncK6ZlcpcKFz6OjbtmHdjDAlquog7urAkvIHssVz3UgJpOaVJK5Dr0DRWz3X1B0cNauC0jr2HtWZnZ5rapxr/vjGVcza47luCOeaU8izDi1ww27/Szc46i63+AjdYjriccw6jJpTh7lOH1ag7fAx6yhq9cCbyWC3tNdx+qZzC6keytxwZUGvi3oep286iK/5mvmrtcV8SnuXTTB0wm+QC42ZvEPKJli+azY04ot3WHkMvuscoEPLY7Af37kTGQC6G1zih+tazXkfWfx7OqasEbNUFffLiZ0xoeNKOfEK+XSZx/1YZkm+2PJVLNcvzG+hzG9k8SW76Dm6Yf6jZcmB5pQpi6fmLyJwCqzzSrNFU6s+k5kzfWtmOTqKK9AFWBiMv6k1uyRIHDViCZheIpkBJUFiRjigUG3V8CxukEHKoES4hqz1d0YxN7UClX4Jdq2vMEVbIw44xpW7CS3adM+eutcpg5lRnl3CCn50p6Af5W1otXdsWaOQ0hfAoyLoJui2Rpdy8neNfaUj6K1w+JHjvq6xm4HNwB9aomwCLXxuMPSrO/bRc4QJHS3vc+Qu/vVi67f/V/eEjtOn8YEzCLREoVo79Dj5QP8QO6LY9vcuK6jlQGKbux08HRpiail47KOhy7tdHVB6RTItG7P/o0OrC6GW32JpdaY+Dzet7mcduXoNNL7fja1u5SstWju90kr/vtG0Vur6siPasDUPxVZsrV6kBtjHGLJHDzdf77RL7/Z6Ni7l26Vy/qQ2prTqai8nJllBEGOJyr5LSWTTnB1r6XH2vVBK1RdbqW7veT6gHGqgiKa61J3H8fzi9fX1YjIedFJd7sZjjF3H/CPAbdq0adOmTZs2bbD5H8lJpKRvNiuNAAAAAElFTkSuQmCC",this.buildObjectMeshes=new Array,this.labels=new Array,this.labelSVGS=new Array,this.baseMaterial=null,this.highlightMaterial=null,this.cancelledMaterial=null,this.cancelledHighlightMaterial=null,this.showCancelObjects=!1,this.objectCallback=null,this.renderFailedCallback=null,this.labelCallback=null,this.registerClipIgnore=null,this.getMaxHeight=null,this.alphaLevel=.5,this.observableControls=null,this.showLabel=localStorage.getItem("showObjectLabels"),this.showLabel===null?this.showLabel=!0:this.showLabel=JSON.parse(this.showLabel),this.rebuildMaterials()}return At(a,[{key:"setBuildMaterial",value:function(e,t,i){i||(i=this.alphaLevel);var s=new te(e,this.scene);return s.diffuseColor=t,s.specularColor=new pe(0,0,0),s.alpha=i,s.needAlphaTesting=()=>!0,s.separateCullingPass=!0,s.backFaceCulling=!0,s}},{key:"rebuildMaterials",value:function(){this.baseMaterial=this.setBuildMaterial("BuildObjectBaseMaterial",new X(.1,.5,.1),.25),this.highlightMaterial=this.setBuildMaterial("BuildObjectHighlightMateria",new pe(.8,.8,.8)),this.cancelledMaterial=this.setBuildMaterial("BuildObjectHighlightMateria",new pe(1,0,0),.4),this.cancelledHighlightMaterial=this.setBuildMaterial("BuildObjectHighlightMateria",new pe(1,1,0),.6);var e=ne.CreateFromBase64String(this.xmark,"checkerboard",this.scene);this.cancelledMaterial.diffuseTexture=e,this.cancelledHighlightMaterial.diffuseTexture=e}},{key:"loadObjectBoundaries",value:function(e){if(this.rebuildMaterials(),this.buildObjectMeshes.length>0){for(var t=0;twindow.URL.revokeObjectURL(o)),this.buildObjectMeshes=new Array,this.labels=new Array}if(e)for(var i=0;i'+r],{type:"image/svg+xml"}),l=window.URL.createObjectURL(o);this.labelSVGS.push(l);var h=Qt.CreatePlane("TextPlane",{width:i,height:8},this.scene);return h.material=new te("TextPlaneMaterial",this.scene),h.material.backFaceCulling=!1,h.material.specularColor=new pe(0,0,0),h.material.diffuseTexture=new ne(l,this.scene),h.material.diffuseTexture.hasAlpha=!0,h.billboardMode=7,this.registerClipIgnore(h),h}},{key:"buildObservables",value:function(){var e=this;if(!this.observableControls){var t=0,i=!1,s=0;this.observableControls=this.scene.onPointerObservable.add(n=>{var r=n.pickInfo;switch(n.type){case Re.POINTERDOWN:i=!0,s=Date.now();break;case Re.POINTERUP:if(i=!1,Date.now()-s>200)return;e.handleClick(r);break;case Re.POINTERMOVE:if(i||Date.now()-t<100)return;t=Date.now(),e.handlePointerMove(r)}})}}},{key:"clearObservables",value:function(){this.observableControls&&(this.scene.onPointerObservable.remove(this.observableControls),this.observableControls=null)}},{key:"showObjectSelection",value:function(e){this.showCancelObjects=e,this.buildObjectMeshes.forEach(t=>t.setEnabled(e)),e?this.buildObservables():this.clearObservables()}},{key:"setObjectTexture",value:function(e){e.metadata&&(e.metadata.cancelled?(e.material=this.cancelledMaterial,e.enableEdgesRendering(),e.edgesWidth=15,e.edgesColor=new X(1,0,0,1)):(e.material=this.baseMaterial,e.enableEdgesRendering(),e.edgesWidth=15,e.edgesColor=new X(0,1,0,1)))}},{key:"handleClick",value:function(e){this.showCancelObjects&&e.hit&&e.pickedMesh&&e.pickedMesh.name.includes("OBJECTMESH")&&this.objectCallback&&this.objectCallback(e.pickedMesh.metadata)}},{key:"handlePointerMove",value:function(e){var t=this;this.showCancelObjects&&(this.buildObjectMeshes.forEach(i=>t.setObjectTexture(i)),e.hit&&e.pickedMesh&&e.pickedMesh.name.includes("OBJECTMESH")?(e.pickedMesh.material=e.pickedMesh.metadata.cancelled?this.cancelledHighlightMaterial:this.highlightMaterial,this.labelCallback&&this.labelCallback(e.pickedMesh.metadata.name)):this.labelCallback&&this.labelCallback(""))}},{key:"showLabels",value:function(e){localStorage.setItem("showObjectLabels",e),this.showLabel=e,this.labels.forEach(t=>t.setEnabled(e))}}]),a}(),ry=function(){function a(e){It(this,a),this.visible=localStorage.getItem("axesVisible"),this.visible===null?this.visible=!0:this.visible=JSON.parse(this.visible),this.scene=e,this.registerClipIgnore=()=>{},this.axesMesh=null,this.axesMeshPosition=null,this.size=50,this.debug=!1}return At(a,[{key:"show",value:function(e){localStorage.setItem("axesVisible",e),this.axesMesh&&this.axesMesh.setEnabled(e),this.scene.render()}},{key:"makeTextPlane",value:function(e,t,i){var s=new Fn("DynamicTexture",50,this.scene,!0);s.hasAlpha=!0,s.drawText(e,5,40,"bold 36px Arial",t,"transparent",!0);var n=F.CreatePlane("TextPlane",i,this.scene,!0);return n.material=new te("TextPlaneMaterial",this.scene),n.material.backFaceCulling=!1,n.material.specularColor=new pe(0,0,0),n.material.diffuseTexture=s,n}},{key:"resize",value:function(e){this.size=e,this.axesMesh.dispose(!1,!0),this.render()}},{key:"render",value:function(e){var t=this;if(!this.debug)if(!this.axesMesh||this.axesMesh.isDisposed()){this.axesMesh=new F("axis",this.scene),this.registerClipIgnore(this.axesMesh);var i=F.CreateLines("axisX",[v.Zero(),new v(this.size,0,0),new v(.95*this.size,.05*this.size,0),new v(this.size,0,0),new v(.95*this.size,-.05*this.size,0)],this.scene);i.color=new pe(1,0,0),i.parent=this.axesMesh;var s=this.makeTextPlane("X","red",this.size/10);s.billboardMode=7,s.position=new v(.9*this.size,.05*this.size,0),s.parent=this.axesMesh;var n=F.CreateLines("axisZ",[v.Zero(),new v(0,0,this.size),new v(0,-.05*this.size,.95*this.size),new v(0,0,this.size),new v(0,.05*this.size,.95*this.size)],this.scene);n.color=new pe(0,1,0),n.parent=this.axesMesh;var r=this.makeTextPlane("Y","green",this.size/10);r.billboardMode=7,r.position=new v(0,.05*this.size,.9*this.size),r.parent=this.axesMesh;var o=F.CreateLines("axisY",[v.Zero(),new v(0,this.size,0),new v(-.05*this.size,.95*this.size,0),new v(0,this.size,0),new v(.05*this.size,.95*this.size,0)],this.scene);o.color=new pe(0,0,1),o.parent=this.axesMesh;var l=this.makeTextPlane("Z","blue",this.size/10);l.billboardMode=7,l.position=new v(0,.9*this.size,-.05*this.size),l.parent=this.axesMesh,this.axesMesh.setEnabled(this.visible),this.axesMesh.getChildren().forEach(h=>t.registerClipIgnore(h)),e&&(this.axesMesh.position=e)}else e&&(this.axesMesh.position=e)}},{key:"dispose",value:function(){this.axesMesh&&this.axesMesh.dispose(!1,!0)}}]),a}(),Je=null;function Ws(a,e,t){var i=function(s,n,r,o,l,h){var c=arguments.length>6&&arguments[6]!==void 0?arguments[6]:75,u=yc("svg").attr("width",400).attr("height",300);u.append("rect").attr("x",0).attr("y",0).attr("width",400).attr("height",300).attr("fill","#333333"),u.append("text").attr("x",200).attr("y",150).attr("font-family","Roboto").attr("font-size",c+"px").attr("text-anchor","middle").attr("alignment-baseline","middle").attr("fill",o).attr("stroke",r).attr("stroke-width",2).attr("text-rendering","optimizeLegibility").text(n);var f=u.attr("title","test2").attr("version",1.1).attr("xmlns","http://www.w3.org/2000/svg").node(),d='',p=new XMLSerializer().serializeToString(f),g=new Blob([d+p],{type:"image/svg+xml"}),_=window.URL.createObjectURL(g),m=Qt.CreatePlane("TextPlane",{width:l,height:h},s);return m.material=new te("TextPlaneMaterial",s),m.material.backFaceCulling=!1,m.material.specularColor=new pe(0,0,0),m.material.diffuseTexture=new ne(_,s),m.material.diffuseTexture.hasAlpha=!1,m}(a,e,"white","white",6,6,90);i.name=e,i.lookAt(t),i.position=t.scale(-3),e==="Top"&&i.rotate(Wt.Z,Math.PI/2,ci.LOCAL),e==="Bottom"&&i.rotate(Wt.Z,-Math.PI/2,ci.LOCAL),i.metadata={x:Math.sign(t.x),y:Math.sign(t.y),z:Math.sign(t.z)},i.isPickable=!0}function fs(a,e,t){var i=Qt.CreateSphere(e,{diameter:1.1},a),s=v.Zero();s.x=t.x-.25*Math.sign(t.x),s.y=t.y-.1*Math.sign(t.y),s.z=t.z-.25*Math.sign(t.z),i.metadata={x:-1*Math.sign(t.x),y:-1*Math.sign(t.y),z:-1*Math.sign(t.z)},i.position=s,i.isPickable=!0}var Na,ca=null;function _i(a,e,t){ca||((ca=new te("edgematerial",a)).diffuseColor=new pe(.5,.5,.5));var i=Qt.CreateBox(e,{width:.35,height:5.8,depth:.35},a),s=v.Zero();t.y!==0&&(i.rotate(Wt.Z,Math.PI/2,ci.WORLD),t.x!==0&&i.rotate(Wt.Y,Math.PI/2,ci.WORLD),i.bakeCurrentTransformIntoVertices()),s.x=t.x-Math.sign(t.x),s.y=t.y-Math.sign(t.y),s.z=t.z-Math.sign(t.z),i.metadata={x:-1*Math.sign(t.x),y:-1*Math.sign(t.y),z:-1*Math.sign(t.z)},i.position=s,i.material=ca}function ay(a,e,t){(Je=new Qe(a)).autoClear=!1;var i=new st("camera1",5*Math.PI/8,5*Math.PI/8,13,new v(0,0,0),Je);i.viewport=new Qs(.85,.85,.15,.15),i.viewport.toGlobal(200,200),e.afterRender=()=>{Je.render(),i.alpha=t.alpha,i.beta=t.beta,i.radius=15},new an("light1",new v(0,1,0),Je).intensity=.8,new an("light2",new v(-1,-.5,0),Je).intensity=.8;var s=3.9;_i(Je,"FrontLeft",new v(-s,0,-s)),_i(Je,"BackLeft",new v(-s,0,s)),_i(Je,"BackRight",new v(s,0,s)),_i(Je,"FrontRight",new v(s,0,-s)),_i(Je,"TopFront",new v(0,s,-s)),_i(Je,"TopBack",new v(0,s,s)),_i(Je,"TopLeft",new v(-s,s,0)),_i(Je,"TopRight",new v(s,s,0)),_i(Je,"BottomFront",new v(0,-s,-s)),_i(Je,"BottomBack",new v(0,-s,s)),_i(Je,"BottomLeft",new v(-s,-s,0)),_i(Je,"BottomRight",new v(s,-s,0)),fs(Je,"FrontTopLeft",new v(-3,3,-3)),fs(Je,"FrontTopRight",new v(3,3,-3)),fs(Je,"BackTopLeft",new v(-3,3,3)),fs(Je,"BackTopRight",new v(3,3,3)),fs(Je,"FrontBottomLeft",new v(-3,-3,-3)),fs(Je,"FrontBottomRight",new v(3,-3,-3)),fs(Je,"BackBottomLeft",new v(-3,-3,3)),fs(Je,"BackBottomRight",new v(3,-3,3)),Ws(Je,"Front",new v(0,0,1)),Ws(Je,"Right",new v(-1,0,0)),Ws(Je,"Back",new v(0,0,-1)),Ws(Je,"Left",new v(1,0,0)),Ws(Je,"Top",new v(0,-1,0)),Ws(Je,"Bottom",new v(0,1,0)),Je.onPointerDown=(n,r)=>{r.distance>0&&Na&&(Na(r.pickedMesh.metadata),Je.render(!0))}}var oy=function(){function a(e){It(this,a),this.visible=!0,this.scene=e,this.workplacePoints=[],this.workplaceMeshes=[],this.registerClipIgnore=()=>{}}return At(a,[{key:"setOffsets",value:function(e){this.workplacePoints=e,this.render()}},{key:"makeTextPlane",value:function(e,t,i){var s=new Fn("DynamicTexture",50,this.scene,!0);s.hasAlpha=!0,s.drawText(e,5,40,"bold 36px Arial",t,"transparent",!0);var n=F.CreatePlane("TextPlane",i,this.scene,!0);return n.material=new te("TextPlaneMaterial",this.scene),n.material.backFaceCulling=!1,n.material.specularColor=new pe(0,0,0),n.material.diffuseTexture=s,n}},{key:"render",value:function(){if(this.workplaceMeshes.length>0){for(var e=0;e{},this.simulationStopped=()=>{},this.simLine=v.Zero(),this.isMMS=!1}var e,t,i,s;return At(a,[{key:"getMaxHeight",value:function(){return this.maxHeight}},{key:"getMinHeight",value:function(){return this.minHeight}},{key:"setCameraType",value:function(n){this.scene.activeCamera=n?this.orbitCamera:this.flyCamera}},{key:"setZClipPlane",value:function(n,r){this.zTopClipValue=-n,this.zBottomClipValue=r,r>n&&(this.zTopClipValue=r+1),this.scene.clipPlane=new Yt(0,1,0,this.zTopClipValue),this.scene.clipPlane2=new Yt(0,-1,0,this.zBottomClipValue),this.scene.render()}},{key:"isArcRotateCameraStopped",value:function(n){return n.inertialAlphaOffset===0&&n.inertialBetaOffset===0&&n.inertialRadiusOffset===0&&n.inertialPanningX===0&&n.inertialPanningY===0}},{key:"init",value:(s=zi(yt().mark(function n(r){var o,l,h=this;return yt().wrap(function(c){for(;;)switch(c.prev=c.next){case 0:return r===void 0&&(r=!1),console.info("GCode Viewer - Sindarius - ".concat("3.7.11"," ")),c.next=4,Se.IsSupportedAsync;case 4:if(!c.sent||!r){c.next=13;break}return console.log("WebGPU Supported"),this.engine=new Se(this.canvas,{doNotHandleContextLost:!0}),c.next=10,this.engine.initAsync();case 10:console.log(this.engine),c.next=15;break;case 13:console.log("WebGPU Not Supported"),this.engine=new ie(this.canvas,!0,{doNotHandleContextLost:!0});case 15:this.engine.enableOfflineSupport=!1,this.scene=new Qe(this.engine),this.scene.performancePriority=Ta.BackwardCompatible,this.debug,this.scene.clearColor=pe.FromHexString(this.getBackgroundColor()),this.bed=new sy(this.scene),this.bed.registerClipIgnore=u=>{h.registerClipIgnore(u)},o=this.bed.getCenter(),this.orbitCamera=new st("Camera",Math.PI/2,2.356194,250,new v(o.x,-2,o.y),this.scene),this.orbitCamera.attachControl(!1),this.orbitCamera.invertRotation=!1,this.orbitCamera.attachControl(this.canvas,!1),this.orbitCamera.maxZ=1e5,this.orbitCamera.lowerRadiusLimit=5,this.updateCameraInertiaProperties(),(l=new Or("light2",new v(0,1,-1),this.scene)).diffuse=new pe(1,1,1),l.specular=new pe(1,1,1),this.engine.runRenderLoop(()=>{if(!document.hidden){if(h.simulation){if(h.pause)return}else if(h.pause||Date.now()-h.gcodeProcessor.lastUpdate>h.renderTimeout&&h.isArcRotateCameraStopped(h.orbitCamera))return;if(h.simulation)try{h.runSimulation(),h.gcodeProcessor.doUpdate()}catch{h.simulation=!1,h.simulationStopped()}h.scene.render(!0),l.position=h.scene.cameras[0].position}}),this.buildObjects=new ny(this.scene),this.buildObjects.getMaxHeight=()=>h.gcodeProcessor.getMaxHeight(),this.buildObjects.registerClipIgnore=u=>{h.registerClipIgnore(u)},this.bed.buildBed(),this.axes=new ry(this.scene),this.axes.registerClipIgnore=u=>{h.registerClipIgnore(u)},this.axes.render(),this.workplace=new oy(this.scene),this.workplace.registerClipIgnore=u=>{h.registerClipIgnore(u)},this.workplace.setOffsets(this.gcodeProcessor.workplaceOffsets),this.workplace.render(),this.resetCamera(),ay(this.engine,this.scene,this.orbitCamera),Na=u=>{h.setCameraPosition(u)},setTimeout(()=>{h.forceRender()},1e3);case 49:case"end":return c.stop()}},n,this)})),function(n){return s.apply(this,arguments)})},{key:"setCameraPosition",value:function(n,r,o){console.log(this.scene.activeCamera.position);var l=Number(n),h=Number(r),c=Number(o);l!==NaN&&h!==NaN&&c!==NaN&&(this.scene.activeCamera.position=new v(Number(n),Number(o),Number(r)),this.forceRender())}},{key:"resize",value:function(){this.engine.resize(),this.scene.render(!0)}},{key:"refreshUI",value:function(){setTimeout(()=>{},0)}},{key:"resetCamera",value:function(){var n=this.bed.getCenter(),r=this.bed.getSize();this.bed.isDelta?(this.scene.activeCamera.radius=n.x,this.scene.activeCamera.target=new v(n.x,-2,n.y),this.scene.activeCamera.position=new v(-r.x,r.z,-r.x)):(this.scene.activeCamera.radius=3*n.x,this.scene.activeCamera.target=new v(n.x,-2,n.y),this.scene.activeCamera.position=new v(-r.x/2,r.z,-r.y/2)),this.scene.render(!0),this.scene.render(!0)}},{key:"lastLoadFailed",value:function(){return!!localStorage&&localStorage.getItem(this.lastLoadKey)==="true"}},{key:"setLoadFlag",value:function(){localStorage&&localStorage.setItem(this.lastLoadKey,"true")}},{key:"clearLoadFlag",value:function(){localStorage&&(localStorage.setItem(this.lastLoadKey,""),localStorage.removeItem(this.lastLoadKey))}},{key:"processFile",value:(i=zi(yt().mark(function n(r){return yt().wrap(function(o){for(;;)switch(o.prev=o.next){case 0:this.clearScene(),this.refreshUI(),r?(this.fileData=r,this.fileSize=r.length):(this.fileData=0,this.fileSize=0),this.fileDataArray=[];try{this.fileData===null&&this.fileData===""||(this.fileDataArray=this.fileData.split("\n"))}catch{this.fileDataArray=[]}return this.gcodeProcessor.setProgressColor(this.getProgressColor()),this.gcodeProcessor.scene=this.scene,this.lastLoadFailed()&&(console.error("Last rendering failed dropping to SBC quality"),this.updateRenderQuality(1),this.clearLoadFlag()),this.setLoadFlag(),o.next=11,this.gcodeProcessor.processGcodeFile(r,this.renderQuality);case 11:return this.clearLoadFlag(),o.next=14,this.gcodeProcessor.createMesh(this.scene);case 14:this.gcodeProcessor.loadingComplete(),this.maxHeight=this.gcodeProcessor.getMaxHeight(),this.minHeight=this.gcodeProcessor.getMinHeight(),this.toggleTravels(this.travelVisible),this.setCursorVisiblity(this.toolCursorVisible),this.gcodeProcessor.zBelt&&(this.bed.buildVolume.y.min=this.gcodeProcessor.beltLength,this.bed.buildVolume.y.max=0,this.bed.dispose(),this.bed.buildBed());case 20:case"end":return o.stop()}},n,this)})),function(n){return i.apply(this,arguments)})},{key:"toggleTravels",value:function(n){var r,o=function(h,c){var u=typeof Symbol<"u"&&h[Symbol.iterator]||h["@@iterator"];if(!u){if(Array.isArray(h)||(u=wo(h))||c&&h&&typeof h.length=="number"){u&&(h=u);var f=0,d=()=>{};return{s:d,n:()=>f>=h.length?{done:!0}:{done:!1,value:h[f++]},e:m=>{throw m},f:d}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var p,g=!0,_=!1;return{s:()=>{u=u.call(h)},n:()=>{var m=u.next();return g=m.done,m},e:m=>{_=!0,p=m},f:()=>{try{g||u.return==null||u.return()}finally{if(_)throw p}}}}(this.scene.meshes);try{for(o.s();!(r=o.n()).done;){var l=r.value;l.name==="travels"&&(l.isVisible=n)}}catch(h){o.e(h)}finally{o.f()}this.travelVisible=n,this.scene.render(!0)}},{key:"getProgressColor",value:function(){var n=localStorage.getItem("progressColor");return n===null&&(n="#FFFFFF"),n}},{key:"setProgressColor",value:function(n){localStorage.setItem("progressColor",n),this.gcodeProcessor.setProgressColor(n)}},{key:"getBackgroundColor",value:function(){var n=localStorage.getItem("sceneBackgroundColor");return n===null&&(n="#000000"),n}},{key:"setBackgroundColor",value:function(n){this.scene!==null&&this.scene!==void 0&&(n.length>7&&(n=n.substring(0,7)),this.scene.clearColor=pe.FromHexString(n),this.scene.render()),localStorage.setItem("sceneBackgroundColor",n)}},{key:"clearScene",value:function(n){this.fileData&&n&&(this.fileData=""),this.gcodeProcessor.unregisterEvents();for(var r=this.scene.meshes.length-1;r>=0;r--){var o=this.scene.meshes[r];o&&this.debug&&console.log("Disposing ".concat(o.name)),this.scene.removeMesh(o),o&&typeof o.dispose=="function"&&o.dispose(!1,!0)}for(var l=this.scene.materials.length-1;l>=0;l--){var h=this.scene.materials[l];h.name==="solidMaterial"&&(h&&this.debug&&console.log("Disposing ".concat(h.name)),this.scene.removeMaterial(h),h&&typeof h.dispose=="function"&&h.dispose(!1,!0))}this.toolCursor&&(this.toolCursor.dispose(!1,!0),this.toolCursor=void 0),this.buildtoolCursor(),this.bed.buildBed(),this.axes.render(),this.workplace.render()}},{key:"reload",value:(t=zi(yt().mark(function n(){return yt().wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return this.clearScene(),r.next=3,this.processFile(this.fileData);case 3:case"end":return r.stop()}},n,this)})),function(){return t.apply(this,arguments)})},{key:"getRenderMode",value:function(){return this.gcodeProcessor.renderMode}},{key:"setCursorVisiblity",value:function(n){this.scene!==void 0&&(this.toolCursor===void 0&&this.buildtoolCursor(),this.toolCursorMesh.isVisible=n,this.toolCursorVisible=n,this.scene.render())}},{key:"updateToolPosition",value:function(n){var r=0,o=0,l=0;if(this.buildtoolCursor(),n instanceof v)r=n.x,o=n.z,l=n.y;else for(var h=0;h{r.scene.clipPlane=null,r.scene.clipPlane2=null}),n.onAfterRenderObservable.add(()=>{r.scene.clipPlane=new Yt(0,1,0,r.zTopClipValue),r.scene.clipPlane2=new Yt(0,-1,0,r.zBottomClipValue)}))}},{key:"updateCameraInertiaProperties",value:function(){this.cameraInertia?(this.orbitCamera.speed=2,this.orbitCamera.inertia=.9,this.orbitCamera.panningInertia=.9,this.orbitCamera.inputs.attached.keyboard.angularSpeed=.005,this.orbitCamera.inputs.attached.keyboard.zoomingSensibility=2,this.orbitCamera.inputs.attached.keyboard.panningSensibility=2,this.orbitCamera.angularSensibilityX=1e3,this.orbitCamera.angularSensibilityY=1e3,this.orbitCamera.panningSensibility=10,this.orbitCamera.wheelPrecision=1):(this.orbitCamera.speed=500,this.orbitCamera.inertia=0,this.orbitCamera.panningInertia=0,this.orbitCamera.inputs.attached.keyboard.angularSpeed=.05,this.orbitCamera.inputs.attached.keyboard.zoomingSensibility=.5,this.orbitCamera.inputs.attached.keyboard.panningSensibility=.5,this.orbitCamera.angularSensibilityX=200,this.orbitCamera.angularSensibilityY=200,this.orbitCamera.panningSensibility=2,this.orbitCamera.wheelPrecision=.25)}},{key:"setCameraInertia",value:function(n){this.cameraInertia=n,localStorage.setItem("cameraInertia",n),this.updateCameraInertiaProperties()}},{key:"forceRender",value:function(){this.scene&&this.scene.render(!0)}},{key:"getLayers",value:function(){return this.gcodeProcessor.layerDictionary}},{key:"getGCodeLine",value:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:5;try{var r=Math.max(0,this.gcodeProcessor.currentLineNumber-n),o=Math.min(this.gcodeProcessor.currentLineNumber,this.fileDataArray.length-1);return this.fileDataArray.slice(r,o).join("\r\n").trim()}catch{return""}}},{key:"getGCodeLineNumber",value:function(){return this.gcodeProcessor.currentLineNumber}},{key:"goToGCodeLine",value:function(n){}},{key:"simulateToolPosition",value:function(){this.updateToolPosition(this.gcodeProcessor.nozzlePosition)}},{key:"setZBelt",value:function(n,r){this.gcodeProcessor.zBelt=n,n&&(this.gcodeProcessor.setZBeltAngle(r),this.toolCursorMesh.rotate(Wt.X,Math.PI/2-r*Math.PI/180,ci.LOCAL))}},{key:"setWorkplaceVisiblity",value:function(n){this.workplace.visible=n,this.workplace.setOffsets(this.gcodeProcessor.workplaceOffsets),this.workplace.render(),this.scene.render()}},{key:"startSimulation",value:function(){this.gcodeProcessor.lastFilePositionIndex>=this.gcodeProcessor.renderedLines.length-1&&this.gcodeProcessor.updateFilePositionIndex(1),this.simulation=!0,this.gcodeProcessor.doUpdate()}},{key:"stopSimulation",value:function(){this.simulation=!1,this.simulationStopped()}},{key:"clamp",value:function(n,r,o){return Math.min(Math.max(n,r),o)}},{key:"runSimulation",value:function(){if(this.gcodeProcessor.renderedLines.length!==0){if(this.gcodeProcessor.lastFilePositionIndex>=this.gcodeProcessor.renderedLines.length-1&&(this.simulation=!1,this.simulationStopped()),this.simulationCurrentLine!=this.gcodeProcessor.renderedLines[this.gcodeProcessor.lastFilePositionIndex]){this.simulationCurrentLine=this.gcodeProcessor.renderedLines[this.gcodeProcessor.lastFilePositionIndex],this.updateToolPosition(this.simulationCurrentLine.start),this.simulationLastUpdate=0;var n=this.isMMS?this.simulationCurrentLine.feedRate:this.simulationCurrentLine.feedRate/60;this.simulationTimeToMove=this.simulationCurrentLine.length()/n*1e3,this.simulationUpdatePosition(this.simulationCurrentLine.gcodeFilePosition)}this.simLine=this.simulationCurrentLine.start.clone(),this.simulationLastUpdate+=this.engine.getDeltaTime()*this.simulationMultiplier*this.scene.getAnimationRatio();var r=this.clamp(this.simulationLastUpdate/this.simulationTimeToMove,0,1);if(v.LerpToRef(this.simulationCurrentLine.start,this.simulationCurrentLine.end,r,this.simLine),this.updateToolPosition(this.simLine),this.simulationLastUpdate>=this.simulationTimeToMove||this.simulationTimeToMove==1/0||this.simulationTimeToMove==0){var o=this.simulationMultiplier>10?this.simulationMultiplier:1,l=this.scene.getAnimationRatio();l>3&&(o+=~~l),this.gcodeProcessor.updateFilePositionIndex(this.gcodeProcessor.lastFilePositionIndex+o)}}}},{key:"getCameraPosition",value:function(){return this.scene.cameras[0].position}},{key:"getCameraTarget",value:function(){return this.scene.cameras[0].target}},{key:"setCameraTarget",value:function(n,r,o){var l=Number(n),h=Number(r),c=Number(o);l!==NaN&&h!==NaN&&c!==NaN&&(this.scene.activeCamera.target=new v(Number(n),Number(o),Number(r)),this.forceRender())}},{key:"createScreenshot",value:(e=zi(yt().mark(function n(){var r,o,l,h,c=arguments;return yt().wrap(function(u){for(;;)switch(u.prev=u.next){case 0:return r=c.length>0&&c[0]!==void 0?c[0]:1920,o=c.length>1&&c[1]!==void 0?c[1]:1080,l=this.scene.clearColor,this.scene.clearColor=new X(0,0,0,0),this.displayViewBox(!1),this.gcodeProcessor.forceRender(),this.gcodeProcessor.doUpdate(),this.scene.render(!0,!0),this.scene.onAfterRenderObservable.addOnce(()=>{}),u.next=13,lv.CreateScreenshotAsync(this.engine,this.scene.activeCamera,{width:r,height:o});case 13:return h=u.sent,this.scene.clearColor=l,u.abrupt("return",h);case 16:case"end":return u.stop()}},n,this)})),function(){return e.apply(this,arguments)})},{key:"displayViewBox",value:function(n){(function(r){Je.meshes.forEach(o=>{o.setEnabled(r)})})(n)}}]),a}(),hy=Object.defineProperty,cy=Object.getOwnPropertyDescriptor,Us=(a,e,t,i)=>{for(var s=i>1?void 0:i?cy(e,t):e,n=a.length-1,r;n>=0;n--)(r=a[n])&&(s=(i?r(e,t,s):r(s))||s);return i&&s&&hy(e,t,s),s};let os=class extends Vu{constructor(){super(...arguments),this.view=void 0}mounted(){this.view=new Qu({doc:this.document,extensions:[Ju,ef.readOnly.of(!0)],parent:this.$refs.view})}mouseUp(){if(this.view){let a=this.view.state.doc.lineAt(this.view.state.selection.ranges[0].from);this.$emit("update:currentline",a.to),this.view.contentDOM.blur(),this.$emit("got-focus")}}keyPress(){if(this.view){let a=this.view.state.doc.lineAt(this.view.state.selection.ranges[0].from);this.$emit("update:currentline",a.to),this.$emit("got-focus")}}documentUpdated(){this.view&&this.shown&&this.view.dispatch({changes:{from:0,to:this.view.state.doc.length,insert:this.document}})}currentlineUpdated(a){if(this.view&&this.shown){let e=this.view.state.doc.lineAt(a);this.view.dispatch({selection:{anchor:e.from,head:e.from},scrollIntoView:!0})}}};Us([tf("currentline")],os.prototype,"currentLineNumber",2);Us([Ar({type:String,default:""})],os.prototype,"document",2);Us([Ar({type:Boolean,default:!1})],os.prototype,"isSimulating",2);Us([Ar({type:Boolean,default:!1})],os.prototype,"shown",2);Us([nt("document")],os.prototype,"documentUpdated",1);Us([nt("currentLineNumber")],os.prototype,"currentlineUpdated",1);os=Us([ka({})],os);var uy=function(){var a=this,e=a.$createElement,t=a._self._c||e;return t("div",{ref:"view",staticClass:"codeview",on:{mouseup:a.mouseUp,keydown:a.keyPress}})},fy=[];const Hl={};var dy=Va(os,uy,fy,!1,py,"7831183a",null,null);function py(a){for(let e in Hl)this[e]=Hl[e]}const Su=function(){return dy.exports}();var _y=Object.defineProperty,gy=Object.getOwnPropertyDescriptor,tt=(a,e,t,i)=>{for(var s=i>1?void 0:i?gy(e,t):e,n=a.length-1,r;n>=0;n--)(r=a[n])&&(s=(i?r(e,t,s):r(s))||s);return i&&s&&_y(e,t,s),s};let $=null,$e=class extends ql($l){constructor(){super(...arguments),this.mdiReloadAlert=Cu,this.mdiCameraRetake=Mu,this.mdiToggleSwitch=Ru,this.mdiToggleSwitchOffOutline=Pu,this.mdiClose=wu,this.mdiCog=Du,this.mdiVideo3d=Fu,this.mdiPlay=Ou,this.mdiPause=Lu,this.mdiFastForward=Bu,this.mdiBroom=Nu,this.mdiSelectionRemove=Uu,this.formatFilesize=ku,this.isBusy=!1,this.loading=!1,this.loadingPercent=0,this.tracking=!1,this.loadedFile=null,this.reloadRequired=!1,this.fileSize=0,this.renderQuality=this.renderQualities[2],this.scrubPosition=0,this.scrubPlaying=!1,this.scrubSpeed=1,this.scrubInterval=void 0,this.scrubFileSize=0,this.downloadSnackbar={status:!1,filename:"",percent:0,speed:0,total:0,cancelTokenSource:{}},this.excludeObject={bool:!1,name:""},this.fileData="",this.colorModes=[{text:"Extruder",value:0},{text:"Feed Rate",value:1},{text:"Feature",value:2}]}get renderQualities(){return[{label:this.$t("GCodeViewer.Low"),value:2},{label:this.$t("GCodeViewer.Medium"),value:3},{label:this.$t("GCodeViewer.High"),value:4},{label:this.$t("GCodeViewer.Ultra"),value:5},{label:this.$t("GCodeViewer.Max"),value:6}]}async mounted(){var e,t,i,s;this.loadedFile=(t=(e=this.$store.state.gcodeviewer)==null?void 0:e.loadedFileBackup)!=null?t:null,$=(s=(i=this.$store.state.gcodeviewer)==null?void 0:i.viewerBackup)!=null?s:null,await this.init(),this.loadedFile!==null&&(this.scrubFileSize=$.fileSize),$&&(this.fileData=$.fileData)}beforeDestroy(){$&&($.gcodeProcessor.loadingProgressCallback=null,this.$store.dispatch("gcodeviewer/setLoadedFileBackup",this.loadedFile),this.$store.dispatch("gcodeviewer/setViewerBackup",$)),this.scrubPlaying=!1,this.scrubInterval&&(clearInterval(this.scrubInterval),this.scrubInterval=void 0)}handleResize(){this.$nextTick(()=>{$==null||$.resize()})}get panelTitle(){let e=this.$t("GCodeViewer.Title").toString();return this.loadedFile&&(e+=": ".concat(this.loadedFile)),e}get filePosition(){return this.printerIsPrinting?this.$store.state.printer.virtual_sdcard.file_position:0}get sdCardFilePath(){var e,t;return(t=(e=this.$store.state.printer.print_stats)==null?void 0:e.filename)!=null?t:""}get livePosition(){var e,t;return(t=(e=this.$store.state.printer.motion_report)==null?void 0:e.live_position)!=null?t:[0,0,0,0]}get gcodeOffset(){var e,t,i;return(i=(t=(e=this.$store.state.printer)==null?void 0:e.gcode_move)==null?void 0:t.homing_origin)!=null?i:[0,0,0]}get currentPosition(){return[this.livePosition[0]-this.gcodeOffset[0],this.livePosition[1]-this.gcodeOffset[1],this.livePosition[2]-this.gcodeOffset[2],this.livePosition[3]]}get showTrackingButton(){return this.printerIsPrinting&&this.sdCardFilePath===this.loadedFile}get printing_objects(){var e,t;return(t=(e=this.$store.state.printer.exclude_object)==null?void 0:e.objects)!=null?t:[]}printing_objectsChanged(){this.refreshPrintingObjects()}get excluded_objects(){var e,t;return(t=(e=this.$store.state.printer.exclude_object)==null?void 0:e.excluded_objects)!=null?t:[]}excluded_objectsChanged(){this.refreshPrintingObjects()}get nozzle_diameter(){var e,t,i,s;return(s=(i=(t=(e=this.$store.state.printer.configfile)==null?void 0:e.settings)==null?void 0:t.extruder)==null?void 0:i.nozzle_diameter)!=null?s:.4}async init(){var t,i,s,n,r;let e=(i=(t=this.$store.state.gcodeviewer)==null?void 0:t.canvasBackup)!=null?i:null;e===null?(e=document.createElement("canvas"),e.className="viewer",this.$refs.viewerCanvasContainer.appendChild(e),await this.$store.dispatch("gcodeviewer/setCanvasBackup",e)):(this.$refs.viewerCanvasContainer.appendChild(e),$!=null&&$.gcodeProcessor&&$.gcodeProcessor.updateFilePosition($==null?void 0:$.fileSize)),$===null&&await this.viewerInit(e),this.registerProgressCallback(),(s=this.$route.query)!=null&&s.filename&&this.loadedFile!==((r=(n=this.$route.query)==null?void 0:n.filename)==null?void 0:r.toString())&&(await this.sleep(1e3),await this.loadFile(this.$route.query.filename.toString()))}async viewerInit(e){$=new ly(e),await $.init(),$.setBackgroundColor(this.backgroundColor),$.bed.setBedColor(this.gridColor),$.setCursorVisiblity(this.showCursor),$.setZClipPlane(1e6,-1e6),$.axes.show(this.showAxes),$.bed.setDelta(this.kinematics.includes("delta")),this.bedMaxSize!==null&&($.bed.buildVolume.x.max=this.bedMaxSize[0],$.bed.buildVolume.y.max=this.bedMaxSize[1],$.bed.buildVolume.z.max=this.bedMaxSize[2]),this.bedMinSize!==null&&($.bed.buildVolume.x.min=this.bedMinSize[0],$.bed.buildVolume.y.min=this.bedMinSize[1],$.bed.buildVolume.z.min=this.bedMinSize[2]),$.gcodeProcessor.useHighQualityExtrusion(this.hdRendering),$.gcodeProcessor.updateForceWireMode(this.forceLineRendering||this.cncMode),$.gcodeProcessor.setAlpha(this.transparency),$.gcodeProcessor.setVoxelMode(this.voxelMode),$.gcodeProcessor.voxelWidth=this.voxelWidth,$.gcodeProcessor.voxelHeight=this.voxelHeight,$.gcodeProcessor.useSpecularColor(this.specularLighting),$.gcodeProcessor.setLiveTracking(!1),$.gcodeProcessor.g1AsExtrusion=this.cncMode,$.buildObjects.objectCallback=this.objectCallback,this.loadToolColors(this.extruderColors),$.lastLoadFailed()&&(this.renderQuality=this.renderQualities[0],$.updateRenderQuality(1),$.clearLoadFlag())}registerProgressCallback(){$&&($.gcodeProcessor.loadingProgressCallback=e=>{this.loadingPercent=Math.ceil(e*100),this.loading=this.loadingPercent<=99})}async cancelRendering(){$&&($.gcodeProcessor.cancelLoad=!0,await this.sleep(1e3))}clearLoadedFile(){$&&(this.scrubPlaying=!1,this.scrubFileSize=0,$.clearScene(!0),this.loadedFile=null,this.tracking=!1)}chooseFile(){this.isBusy||this.fileInput.click()}finishLoad(){this.loading=!1,$.setCursorVisiblity(this.showCursor),this.refreshPrintingObjects(),this.scrubFileSize=$.fileSize,$.gcodeProcessor.updateFilePosition($.fileSize)}refreshPrintingObjects(){let e=[];this.loadedFile===this.sdCardFilePath&&this.printing_objects.length&&this.printing_objects.forEach(t=>{const i=t.polygon.map(n=>n[0]),s=t.polygon.map(n=>n[1]);e.push({cancelled:this.excluded_objects.includes(t.name),name:t.name,x:[Math.min(...i),Math.max(...i)],y:[Math.min(...s),Math.max(...s)]})}),$.buildObjects.loadObjectBoundaries(e),$.buildObjects.showObjectSelection(this.showObjectSelection)}async fileSelected(e){var i,s;const t=new FileReader;t.addEventListener("load",async n=>{if(!n||!n.target)return;const r=n.target.result;typeof r=="string"&&(this.fileSize=r.length,await $.processFile(r),this.fileData=$.fileData),this.finishLoad()}),this.tracking=!1,(i=e.target.files)!=null&&i.length&&(this.loadedFile=(s=e==null?void 0:e.target)==null?void 0:s.files[0].name,t.readAsText(e.target.files[0])),e.target.value=""}async loadFile(e){this.downloadSnackbar.status=!0,this.downloadSnackbar.speed=0,this.downloadSnackbar.filename=e.startsWith("gcodes/")?e.slice(7):e;const t=Yo.CancelToken;this.downloadSnackbar.cancelTokenSource=t.source();const i=await Yo.get(this.apiUrl+"/server/files/"+encodeURI(e),{cancelToken:this.downloadSnackbar.cancelTokenSource.token,responseType:"blob",onDownloadProgress:s=>{var n,r,o;this.downloadSnackbar.percent=((n=s.progress)!=null?n:0)*100,this.downloadSnackbar.speed=(r=s.rate)!=null?r:0,this.downloadSnackbar.total=(o=s.total)!=null?o:0}}).then(s=>s.data.text()).catch(s=>{window.console.error(s.message)});this.downloadSnackbar.status=!1,this.loadedFile=this.downloadSnackbar.filename,$.updateRenderQuality(this.renderQuality.value),await $.processFile(i),this.fileData=$.fileData,this.loadingPercent=100,this.finishLoad(),this.scrubFileSize=$.fileSize}cancelDownload(){this.downloadSnackbar.cancelTokenSource.cancel("User canceled download gcode file")}async sleep(e){await new Promise(t=>setTimeout(t,e))}async loadCurrentFile(){await this.loadFile("gcodes/"+this.sdCardFilePath),this.loadedFile=this.sdCardFilePath}async reloadViewer(){this.loading&&($.gcodeProcessor.cancelLoad=!0,await this.sleep(1e3)),this.reloadRequired=!1,this.loading=!0,this.loadingPercent=0,await $.reload(),this.fileData=$.fileData,this.loadingPercent=100,this.finishLoad()}resetCamera(){$.resetCamera()}setReloadRequiredFlag(){this.loadedFile&&this.loadedFile!=""&&(this.reloadRequired=!0)}async renderQualityChanged(e){$&&$.renderQuality!==e&&($.updateRenderQuality(e),await this.reloadViewer())}currentPositionChanged(e){if($){const t=[{axes:"X",position:e[0]},{axes:"Y",position:e[1]},{axes:"Z",position:e[2]}];$.updateToolPosition(t)}}filePositionChanged(e){if(!$)return;const t=350;e>0&&this.printerIsPrinting&&this.tracking&&e>t?($.gcodeProcessor.updateFilePosition(e-t),this.scrubPosition=e-t):$.gcodeProcessor.updateFilePosition($.fileSize)}async trackingChanged(e){$&&(e?(this.scrubPlaying=!1,$.gcodeProcessor.updateFilePosition(0),$==null||$.forceRender()):($.gcodeProcessor.setLiveTracking(!1),await this.reloadViewer()))}printerIsPrintingChanged(){this.tracking=!1}get showCursor(){var e;return(e=this.$store.state.gui.gcodeViewer.showCursor)!=null?e:!1}set showCursor(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.showCursor",value:e})}showCursorChanged(e){$==null||$.setCursorVisiblity(e)}get showTravelMoves(){var e;return(e=this.$store.state.gui.gcodeViewer.showTravelMoves)!=null?e:!1}set showTravelMoves(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.showTravelMoves",value:e})}get showGCode(){var e;return(e=this.$store.state.gui.gcodeViewer.showGCode)!=null?e:!1}set showGCode(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.showGCode",value:e}),e&&$&&(this.fileData=$.fileData),this.handleResize()}showTravelMovesChanged(e){$==null||$.toggleTravels(e)}get showObjectSelection(){var e;return(e=this.$store.state.gui.gcodeViewer.showObjectSelection)!=null?e:!1}set showObjectSelection(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.showObjectSelection",value:e})}showObjectSelectionChanged(e){$==null||$.buildObjects.showObjectSelection(e)}get hdRendering(){return this.$store.state.gui.gcodeViewer.hdRendering}set hdRendering(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.hdRendering",value:e})}async hdRenderingChanged(e){$&&($.gcodeProcessor.useHighQualityExtrusion(e),await this.reloadViewer())}get forceLineRendering(){return this.$store.state.gui.gcodeViewer.forceLineRendering}set forceLineRendering(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.forceLineRendering",value:e})}async forceLineRenderingChanged(e){$&&($.gcodeProcessor.updateForceWireMode(e||this.cncMode),await this.reloadViewer())}get transparency(){return this.$store.state.gui.gcodeViewer.transparency}set transparency(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.transparency",value:e})}async transparencyChanged(e){$&&($.gcodeProcessor.setAlpha(e),await this.reloadViewer())}get voxelMode(){return this.$store.state.gui.gcodeViewer.voxelMode}set voxelMode(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.voxelMode",value:e})}async voxelModeChanged(e){$&&($.gcodeProcessor.setVoxelMode(e),$.gcodeProcessor.voxelWidth=this.voxelWidth,$.gcodeProcessor.voxelHeight=this.voxelHeight,await this.reloadViewer())}get voxelWidth(){var e;return(e=this.$store.state.gui.gcodeViewer.voxelWidth)!=null?e:1}set voxelWidth(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.voxelWidth",value:e})}get voxelHeight(){var e;return(e=this.$store.state.gui.gcodeViewer.voxelHeight)!=null?e:1}set voxelHeight(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.voxelHeight",value:e})}get specularLighting(){return this.$store.state.gui.gcodeViewer.specularLighting}set specularLighting(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.specularLighting",value:e})}async specularLightingChanged(e){$&&$.gcodeProcessor.useSpecularColor(e)}get cncMode(){return this.$store.state.gui.gcodeViewer.cncMode}set cncMode(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.cncMode",value:e}),$.gcodeProcessor.g1AsExtrusion=e,$.gcodeProcessor.updateForceWireMode(this.forceLineRendering||e),this.reloadViewer()}get extruderColors(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.extruderColors)!=null?t:!1}loadToolColors(e){$&&e.length&&($.gcodeProcessor.resetTools(),e.forEach(t=>{$.gcodeProcessor.addTool(t,this.nozzle_diameter)}),this.setReloadRequiredFlag())}extruderColorsChanged(e){$&&e&&e.length&&(this.loadToolColors(e),this.setReloadRequiredFlag())}get colorMode(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.colorMode)!=null?t:2}set colorMode(e){this.$store.dispatch("gui/saveSetting",{name:"gcodeViewer.colorMode",value:e}),$&&$.gcodeProcessor.colorMode!==e&&($.gcodeProcessor.setColorMode(e),this.reloadViewer())}get backgroundColor(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.backgroundColor)!=null?t:"#121212"}backgroundColorChanged(e){$&&$.setBackgroundColor(e)}get gridColor(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.gridColor)!=null?t:"#B3B3B3"}gridColorChanged(e){$&&$.bed.setBedColor(e)}get showAxes(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.showAxes)!=null?t:!0}showAxesChanged(e){$&&$.axes.show(e)}get minFeed(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.minFeed)!=null?t:20}minFeedChanged(e){$&&$.gcodeProcessor.updateColorRate(e*60,this.maxFeed*60)}get maxFeed(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.maxFeed)!=null?t:100}maxFeedChanged(e){$&&$.gcodeProcessor.updateColorRate(this.minFeed*60,e*60)}get minFeedColor(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.minFeedColor)!=null?t:"#0000FF"}minFeedColorUpdated(e){$&&($.gcodeProcessor.updateMinFeedColor(e),this.setReloadRequiredFlag())}get maxFeedColor(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.maxFeedColor)!=null?t:"#FF0000"}maxFeedColorUpdated(e){$&&($.gcodeProcessor.updateMaxFeedColor(e),this.setReloadRequiredFlag())}get kinematics(){var e,t,i,s,n,r,o,l;return(l=(o=(i=(t=(e=this.$store.state.printer.configfile)==null?void 0:e.settings)==null?void 0:t.printer)==null?void 0:i.kinematics)!=null?o:(r=(n=(s=this.$store.state.gui)==null?void 0:s.gcodeViewer)==null?void 0:n.klipperCache)==null?void 0:r.kinematics)!=null?l:""}get bedMaxSize(){var e,t,i,s,n,r;return(r=(n=(e=this.$store.state.printer.toolhead)==null?void 0:e.axis_maximum)!=null?n:(s=(i=(t=this.$store.state.gui)==null?void 0:t.gcodeViewer)==null?void 0:i.klipperCache)==null?void 0:s.axis_maximum)!=null?r:null}get bedMinSize(){var e,t,i,s,n,r;return(r=(n=(e=this.$store.state.printer.toolhead)==null?void 0:e.axis_minimum)!=null?n:(s=(i=(t=this.$store.state.gui)==null?void 0:t.gcodeViewer)==null?void 0:i.klipperCache)==null?void 0:s.axis_minimum)!=null?r:null}kinematicsChanged(e){$&&e&&$.bed.setDelta(e.includes("delta"))}bedMinSizeChanged(e){$&&e&&($.bed.buildVolume.x.min=e[0],$.bed.buildVolume.y.min=e[1],$.bed.buildVolume.z.min=e[2])}bedMaxSizeChanged(e){e&&$&&($.bed.buildVolume.x.max=e[0],$.bed.buildVolume.y.max=e[1],$.bed.buildVolume.z.max=e[2])}get progressColor(){var e,t;return(t=(e=this.$store.state.gui.gcodeViewer)==null?void 0:e.progressColor)!=null?t:"#FFFFFF"}progressColorChanged(e){$==null||$.setProgressColor(e)}scrubPlayingChanged(e){e?(this.scrubInterval&&(clearInterval(this.scrubInterval),this.scrubInterval=void 0),this.scrubPlaying=!0,this.scrubPosition>=this.scrubFileSize&&(this.scrubPosition=0),$.gcodeProcessor.updateFilePosition(this.scrubPosition-3e4),this.scrubInterval=setInterval(()=>{this.scrubPosition+=100*this.scrubSpeed,$.gcodeProcessor.updateFilePosition(this.scrubPosition),$.simulateToolPosition(),(this.tracking||this.scrubPosition>=this.scrubFileSize)&&(this.scrubPlaying=!1)},200)):(this.scrubInterval&&clearInterval(this.scrubInterval),this.scrubPlaying=!1,this.scrubInterval=void 0)}get showScrubber(){return!this.tracking&&this.scrubFileSize>0}updateScrubPosition(e){this.tracking||($.gcodeProcessor.updateFilePosition(e),$.simulateToolPosition())}fastForward(){this.scrubPosition=this.scrubFileSize,$.gcodeProcessor.updateFilePosition(this.scrubPosition)}objectCallback(e){var t;(e==null?void 0:e.cancelled)===!1&&(this.excludeObject.name=(t=e.name)!=null?t:"UNKNOWN",this.excludeObject.bool=!0)}cancelObject(){this.$socket.emit("printer.gcode.script",{script:"EXCLUDE_OBJECT NAME="+this.excludeObject.name}),this.excludeObject.bool=!1}};tt([Ar({type:String,default:"",required:!1})],$e.prototype,"filename",2);tt([Ql("fileInput")],$e.prototype,"fileInput",2);tt([Ql("viewerCanvasContainer")],$e.prototype,"viewerCanvasContainer",2);tt([jl(200)],$e.prototype,"handleResize",1);tt([nt("printing_objects")],$e.prototype,"printing_objectsChanged",1);tt([nt("excluded_objects")],$e.prototype,"excluded_objectsChanged",1);tt([nt("renderQuality")],$e.prototype,"renderQualityChanged",1);tt([nt("currentPosition")],$e.prototype,"currentPositionChanged",1);tt([nt("filePosition")],$e.prototype,"filePositionChanged",1);tt([nt("tracking")],$e.prototype,"trackingChanged",1);tt([nt("printerIsPrinting")],$e.prototype,"printerIsPrintingChanged",1);tt([nt("showCursor")],$e.prototype,"showCursorChanged",1);tt([nt("showTravelMoves")],$e.prototype,"showTravelMovesChanged",1);tt([nt("showObjectSelection")],$e.prototype,"showObjectSelectionChanged",1);tt([nt("hdRendering")],$e.prototype,"hdRenderingChanged",1);tt([nt("forceLineRendering")],$e.prototype,"forceLineRenderingChanged",1);tt([nt("transparency")],$e.prototype,"transparencyChanged",1);tt([nt("voxelMode")],$e.prototype,"voxelModeChanged",1);tt([nt("specularLighting")],$e.prototype,"specularLightingChanged",1);tt([nt("extruderColors")],$e.prototype,"extruderColorsChanged",1);tt([nt("backgroundColor")],$e.prototype,"backgroundColorChanged",1);tt([nt("gridColor")],$e.prototype,"gridColorChanged",1);tt([nt("showAxes")],$e.prototype,"showAxesChanged",1);tt([nt("minFeed")],$e.prototype,"minFeedChanged",1);tt([nt("maxFeed")],$e.prototype,"maxFeedChanged",1);tt([nt("minFeedColor")],$e.prototype,"minFeedColorUpdated",1);tt([nt("maxFeedColor")],$e.prototype,"maxFeedColorUpdated",1);tt([nt("kinematics")],$e.prototype,"kinematicsChanged",1);tt([nt("bedMinSize",{deep:!0})],$e.prototype,"bedMinSizeChanged",1);tt([nt("bedMaxSize",{deep:!0})],$e.prototype,"bedMaxSizeChanged",1);tt([nt("progressColor")],$e.prototype,"progressColorChanged",1);tt([nt("scrubPlaying")],$e.prototype,"scrubPlayingChanged",1);tt([jl(200),nt("scrubPosition")],$e.prototype,"updateScrubPosition",1);$e=tt([ka({components:{Panel:Zl,CodeStream:Su}})],$e);var my=function(){var a=this,e=a.$createElement,t=a._self._c||e;return t("div",[t(Zl,{attrs:{title:a.panelTitle,icon:a.mdiVideo3d,"card-class":"gcode-viewer-panel","margin-bottom":!1},scopedSlots:a._u([{key:"buttons",fn:function(){return[t(Nt,{directives:[{name:"show",rawName:"v-show",value:a.reloadRequired,expression:"reloadRequired"}],staticClass:"ml-3",attrs:{icon:a.$vuetify.breakpoint.xs,text:a.$vuetify.breakpoint.smAndUp,tile:"",color:"info"},on:{click:a.reloadViewer}},[t("span",{staticClass:"d-none d-sm-block"},[a._v(a._s(a.$t("GCodeViewer.ReloadRequired")))]),t(Ei,{staticClass:"d-sm-none"},[a._v(a._s(a.mdiReloadAlert))])],1),t(Nt,{attrs:{icon:"",tile:""},on:{click:a.resetCamera}},[t(Ei,[a._v(a._s(a.mdiCameraRetake))])],1)]},proxy:!0}])},[t(qo,[t(Kn,{class:a.showScrubber?"withScrubber":""},[t(cs,{attrs:{cols:a.showGCode?8:12}},[t("div",{ref:"viewerCanvasContainer"})]),t(cs,{directives:[{name:"show",rawName:"v-show",value:a.showGCode,expression:"showGCode"}],attrs:{cols:"4"}},[t("div",{staticClass:"viewer"},[t(Su,{ref:"gcodestream",attrs:{shown:a.showGCode,currentline:a.scrubPosition,document:a.fileData,"is-simulating":!a.printerIsPrinting},on:{"update:currentline":function(i){a.scrubPosition=i}}})],1)])],1),t(Kn,{directives:[{name:"show",rawName:"v-show",value:a.showScrubber,expression:"showScrubber"}],staticClass:"scrubber"},[t(cs,{staticClass:"pt-0"},[t(Gu,{attrs:{hint:a.scrubPosition+"/"+a.scrubFileSize,max:a.scrubFileSize,dense:"",min:"0","persistent-hint":""},model:{value:a.scrubPosition,callback:function(i){a.scrubPosition=i},expression:"scrubPosition"}})],1),t(cs,{staticClass:"col-auto pt-0 text-center"},[t(Nt,{staticClass:"px-2 minwidth-0",attrs:{color:"primary"},on:{click:function(i){a.scrubPlaying=!a.scrubPlaying}}},[a.scrubPlaying?t(Ei,[a._v(a._s(a.mdiPause))]):t(Ei,[a._v(a._s(a.mdiPlay))])],1),t(Nt,{staticClass:"px-2 minwidth-0 mx-3",attrs:{color:"primary"},on:{click:a.fastForward}},[t(Ei,[a._v(a._s(a.mdiFastForward))])],1),t(zu,{staticClass:"mt-3 mt-sm-0",attrs:{dense:"",mandatory:"",rounded:""},model:{value:a.scrubSpeed,callback:function(i){a.scrubSpeed=i},expression:"scrubSpeed"}},[t(Nt,{attrs:{value:1}},[a._v("1x")]),t(Nt,{attrs:{value:2}},[a._v("2x")]),t(Nt,{attrs:{value:5}},[a._v("5x")]),t(Nt,{attrs:{value:10}},[a._v("10x")]),t(Nt,{attrs:{value:20}},[a._v("20x")])],1)],1)],1),t(Kn,{staticClass:"mt-0 d-flex align-top"},[t(cs,[t(Kn,[t(cs,{staticClass:"d-flex align-content-space-around justify-center flex-wrap flex-md-nowrap col-12 col-md-4",attrs:{"order-md":"2"}},[a.loadedFile===null?[a.sdCardFilePath!==""&&a.sdCardFilePath!==a.loadedFile?t(Nt,{staticClass:"mr-3",on:{click:a.loadCurrentFile}},[a._v(" "+a._s(a.$t("GCodeViewer.LoadCurrentFile"))+" ")]):a._e(),t(Nt,{on:{click:a.chooseFile}},[a._v(a._s(a.$t("GCodeViewer.LoadLocal")))])]:[a.showTrackingButton?t(Nt,{staticClass:"mr-3",on:{click:function(i){a.tracking=!a.tracking}}},[t(Ei,{staticClass:"mr-2",domProps:{innerHTML:a._s(a.tracking?a.mdiToggleSwitch:a.mdiToggleSwitchOffOutline)}}),a._v(" "+a._s(a.$t("GCodeViewer.Tracking"))+" ")],1):a._e(),t(Nt,{on:{click:a.clearLoadedFile}},[t(Ei,{attrs:{left:""}},[a._v(a._s(a.mdiBroom))]),a._v(" "+a._s(a.$t("GCodeViewer.ClearLoadedFile"))+" ")],1)]],2),t(cs,{staticClass:"col-12 col-sm-6 col-md-4"},[t($o,{attrs:{items:a.colorModes,label:a.$t("GCodeViewer.ColorMode"),"item-text":"text",dense:"","hide-details":"",outlined:""},model:{value:a.colorMode,callback:function(i){a.colorMode=i},expression:"colorMode"}})],1),t(cs,{staticClass:"col-12 col-sm-6 col-md-4 d-flex",attrs:{"order-md":"3"}},[t($o,{attrs:{items:a.renderQualities,label:a.$t("GCodeViewer.RenderQuality"),"item-text":"label",dense:"","hide-details":"",outlined:""},model:{value:a.renderQuality,callback:function(i){a.renderQuality=i},expression:"renderQuality"}}),t(Wu,{attrs:{"offset-y":!0,"offset-x":!0,top:"","close-on-content-click":!1,title:a.$t("Files.SetupCurrentList")},scopedSlots:a._u([{key:"activator",fn:function(i){var s=i.on,n=i.attrs;return[t(Nt,a._g(a._b({staticClass:"minwidth-0 px-2 ml-3"},"v-btn",n,!1),s),[t(Ei,[a._v(a._s(a.mdiCog))])],1)]}}])},[t(Xu,[t(Ni,{staticClass:"minHeight36"},[t(Ui,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.ShowToolhead")},model:{value:a.showCursor,callback:function(i){a.showCursor=i},expression:"showCursor"}})],1),t(Ni,{staticClass:"minHeight36"},[t(Ui,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.ShowTravelMoves")},model:{value:a.showTravelMoves,callback:function(i){a.showTravelMoves=i},expression:"showTravelMoves"}})],1),t(Ni,{staticClass:"minHeight36"},[t(Ui,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.ShowGCode")},model:{value:a.showGCode,callback:function(i){a.showGCode=i},expression:"showGCode"}})],1),a.loadedFile===a.sdCardFilePath&&a.printing_objects.length?t(Ni,{staticClass:"minHeight36"},[t(Ui,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.ShowObjectSelection")},model:{value:a.showObjectSelection,callback:function(i){a.showObjectSelection=i},expression:"showObjectSelection"}})],1):a._e(),t(Hu),t(Ni,{staticClass:"minHeight36"},[t(Ui,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.HDRendering")},model:{value:a.hdRendering,callback:function(i){a.hdRendering=i},expression:"hdRendering"}})],1),t(Ni,{staticClass:"minHeight36"},[t(Ui,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.ForceLineRendering")},model:{value:a.forceLineRendering,callback:function(i){a.forceLineRendering=i},expression:"forceLineRendering"}})],1),t(Ni,{staticClass:"minHeight36"},[t(Ui,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.Transparency")},model:{value:a.transparency,callback:function(i){a.transparency=i},expression:"transparency"}})],1),t(Ni,{staticClass:"minHeight36"},[t(Ui,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.VoxelMode")},model:{value:a.voxelMode,callback:function(i){a.voxelMode=i},expression:"voxelMode"}})],1),t(Ni,{staticClass:"minHeight36"},[t(Ui,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.SpecularLighting")},model:{value:a.specularLighting,callback:function(i){a.specularLighting=i},expression:"specularLighting"}})],1),t(Ni,{staticClass:"minHeight36"},[t(Ui,{staticClass:"mt-0",attrs:{"hide-details":"",label:a.$t("GCodeViewer.CNCMode")},model:{value:a.cncMode,callback:function(i){a.cncMode=i},expression:"cncMode"}})],1)],1)],1)],1)],1)],1)],1),t("input",{ref:"fileInput",attrs:{accept:".g,.gcode,.gc,.gco,.nc,.ngc,.tap",hidden:"",multiple:"",type:"file"},on:{change:a.fileSelected}})],1),t("resize-observer",{on:{notify:a.handleResize}})],1),t(jo,{attrs:{timeout:-1,value:!0,fixed:"",right:"",bottom:""},scopedSlots:a._u([{key:"action",fn:function(i){var s=i.attrs;return[t(Nt,a._b({staticStyle:{"min-width":"auto"},attrs:{color:"red",text:""},on:{click:function(n){return a.cancelRendering()}}},"v-btn",s,!1),[t(Ei,{staticClass:"0"},[a._v(a._s(a.mdiClose))])],1)]}}]),model:{value:a.loading,callback:function(i){a.loading=i},expression:"loading"}},[t("div",[a._v(" "+a._s(a.$t("GCodeViewer.Rendering"))+" - "+a._s(a.loadingPercent)+"% "),t("br"),t("strong",[a._v(a._s(a.loadedFile))])]),t($r,{staticClass:"mt-2",attrs:{value:a.loadingPercent}})],1),t(jo,{attrs:{timeout:-1,value:!0,fixed:"",right:"",bottom:""},scopedSlots:a._u([{key:"action",fn:function(i){var s=i.attrs;return[t(Nt,a._b({staticStyle:{"min-width":"auto"},attrs:{color:"red",text:""},on:{click:a.cancelDownload}},"v-btn",s,!1),[t(Ei,{staticClass:"0"},[a._v(a._s(a.mdiClose))])],1)]}}]),model:{value:a.downloadSnackbar.status,callback:function(i){a.$set(a.downloadSnackbar,"status",i)},expression:"downloadSnackbar.status"}},[a.downloadSnackbar.total>0?[t("div",[a._v(" "+a._s(a.$t("GCodeViewer.Downloading"))+" - "+a._s(Math.round(a.downloadSnackbar.percent))+" % @ "+a._s(a.formatFilesize(Math.round(a.downloadSnackbar.speed)))+"/s "),t("br"),t("strong",[a._v(a._s(a.downloadSnackbar.filename))])]),t($r,{staticClass:"mt-2",attrs:{value:a.downloadSnackbar.percent}})]:[t("div",[a._v(" "+a._s(a.$t("GCodeViewer.Downloading"))+" "),t("br"),t("strong",[a._v(a._s(a.downloadSnackbar.filename))])]),t($r,{staticClass:"mt-2",attrs:{indeterminate:""}})]],2),t(Ku,{attrs:{"max-width":"400"},model:{value:a.excludeObject.bool,callback:function(i){a.$set(a.excludeObject,"bool",i)},expression:"excludeObject.bool"}},[t(Yu,[t(qu,{attrs:{flat:"",dense:""}},[t($u,[t("span",{staticClass:"subheading"},[t(Ei,{attrs:{left:""}},[a._v(a._s(a.mdiSelectionRemove))]),a._v(" "+a._s(a.$t("Panels.StatusPanel.ExcludeObject.ExcludeObjectHeadline"))+" ")],1)])],1),t(qo,{staticClass:"mt-3"},[a._v(" "+a._s(a.$t("Panels.StatusPanel.ExcludeObject.ExcludeObjectText",{name:a.excludeObject.name}))+" ")]),t(ju,[t(Zu),t(Nt,{attrs:{text:""},on:{click:function(i){a.excludeObject.bool=!1}}},[a._v(" "+a._s(a.$t("Panels.StatusPanel.ExcludeObject.Cancel"))+" ")]),t(Nt,{attrs:{color:"primary",text:""},on:{click:a.cancelObject}},[a._v(" "+a._s(a.$t("Panels.StatusPanel.ExcludeObject.ExcludeObject"))+" ")])],1)],1)],1)],1)},vy=[];const Kl={};var xy=Va($e,my,vy,!1,by,"a01a7710",null,null);function by(a){for(let e in Kl)this[e]=Kl[e]}const Eu=function(){return xy.exports}();var yy=Object.defineProperty,Ty=Object.getOwnPropertyDescriptor,Sy=(a,e,t,i)=>{for(var s=i>1?void 0:i?Ty(e,t):e,n=a.length-1,r;n>=0;n--)(r=a[n])&&(s=(i?r(e,t,s):r(s))||s);return i&&s&&yy(e,t,s),s};let Ua=class extends ql($l){};Ua=Sy([ka({components:{Viewer:Eu}})],Ua);var Ey=function(){var a=this,e=a.$createElement,t=a._self._c||e;return t(Eu)},Iy=[];const Yl={};var Ay=Va(Ua,Ey,Iy,!1,Cy,null,null,null);function Cy(a){for(let e in Yl)this[e]=Yl[e]}const Oy=function(){return Ay.exports}();export{Oy as default};