@spiffcommerce/preview 3.6.2-rc.2 → 3.6.2-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -16,7 +16,7 @@ layout (num_views = 2) in;
16
16
  `),t+="#define USE_EXACT_SRGB_CONVERSIONS"),t}}createEffect(e,t,i,s,r,n,a,o,h,c=Ct.GLSL){var u;const f=e.vertexElement||e.vertex||e.vertexToken||e.vertexSource||e,d=e.fragmentElement||e.fragment||e.fragmentToken||e.fragmentSource||e,_=this._getGlobalDefines();let p=(u=r??t.defines)!==null&&u!==void 0?u:"";_&&(p+=_);const m=f+"+"+d+"@"+p;if(this._compiledEffects[m]){const S=this._compiledEffects[m];return a&&S.isReady()&&a(S),S}const T=new nt(e,t,i,s,this,r,n,a,o,h,m,c);return this._compiledEffects[m]=T,T}static _ConcatenateShader(e,t,i=""){return i+(t?t+`
17
17
  `:"")+e}_compileShader(e,t,i,s){return this._compileRawShader(re._ConcatenateShader(e,i,s),t)}_compileRawShader(e,t){const i=this._gl,s=i.createShader(t==="vertex"?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!s){let r=i.NO_ERROR,n=i.NO_ERROR;for(;(n=i.getError())!==i.NO_ERROR;)r=n;throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${r}, gl isContextLost=${i.isContextLost()}, _contextWasLost=${this._contextWasLost}`)}return i.shaderSource(s,e),i.compileShader(s),s}_getShaderSource(e){return this._gl.getShaderSource(e)}createRawShaderProgram(e,t,i,s,r=null){s=s||this._gl;const n=this._compileRawShader(t,"vertex"),a=this._compileRawShader(i,"fragment");return this._createShaderProgram(e,n,a,s,r)}createShaderProgram(e,t,i,s,r,n=null){r=r||this._gl;const a=this._webGLVersion>1?`#version 300 es
18
18
  #define WEBGL2
19
- `:"",o=this._compileShader(t,"vertex",s,a),h=this._compileShader(i,"fragment",s,a);return this._createShaderProgram(e,o,h,r,n)}inlineShaderCode(e){return e}createPipelineContext(e){const t=new Oh;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,i,s,r=null){const n=s.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");return s.attachShader(n,t),s.attachShader(n,i),s.linkProgram(n),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_finalizePipelineContext(e){const t=e.context,i=e.vertexShader,s=e.fragmentShader,r=e.program;if(!t.getProgramParameter(r,t.LINK_STATUS)){if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){const o=this._gl.getShaderInfoLog(i);if(o)throw e.vertexCompilationError=o,new Error("VERTEX SHADER "+o)}if(!this._gl.getShaderParameter(s,this._gl.COMPILE_STATUS)){const o=this._gl.getShaderInfoLog(s);if(o)throw e.fragmentCompilationError=o,new Error("FRAGMENT SHADER "+o)}const a=t.getProgramInfoLog(r);if(a)throw e.programLinkError=a,new Error(a)}if(this.validateShaderPrograms&&(t.validateProgram(r),!t.getProgramParameter(r,t.VALIDATE_STATUS))){const o=t.getProgramInfoLog(r);if(o)throw e.programValidationError=o,new Error(o)}t.deleteShader(i),t.deleteShader(s),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,i,s,r,n,a,o,h,c){const u=e;s?u.program=this.createRawShaderProgram(u,t,i,void 0,h):u.program=this.createShaderProgram(u,t,i,o,void 0,h),u.program.__SPECTOR_rebuildProgram=a}_isRenderingStateCompiled(e){const t=e;return this._isDisposed||t._isDisposed?!1:this._gl.getProgramParameter(t.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)?(this._finalizePipelineContext(t),!0):!1}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(!i.isParallelCompiled){t();return}const s=i.onCompiled;s?i.onCompiled=()=>{s(),t()}:i.onCompiled=t}getUniforms(e,t){const i=new Array,s=e;for(let r=0;r<t.length;r++)i.push(this._gl.getUniformLocation(s.program,t[r]));return i}getAttributes(e,t){const i=[],s=e;for(let r=0;r<t.length;r++)try{i.push(this._gl.getAttribLocation(s.program,t[r]))}catch{i.push(-1)}return i}enableEffect(e){e=e!==null&&Li.IsWrapper(e)?e.effect:e,!(!e||e===this._currentEffect)&&(this._stencilStateComposer.stencilMaterial=void 0,e=e,this.bindSamplers(e),this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setInt(e,t){return e?(this._gl.uniform1i(e,t),!0):!1}setInt2(e,t,i){return e?(this._gl.uniform2i(e,t,i),!0):!1}setInt3(e,t,i,s){return e?(this._gl.uniform3i(e,t,i,s),!0):!1}setInt4(e,t,i,s,r){return e?(this._gl.uniform4i(e,t,i,s,r),!0):!1}setIntArray(e,t){return e?(this._gl.uniform1iv(e,t),!0):!1}setIntArray2(e,t){return!e||t.length%2!==0?!1:(this._gl.uniform2iv(e,t),!0)}setIntArray3(e,t){return!e||t.length%3!==0?!1:(this._gl.uniform3iv(e,t),!0)}setIntArray4(e,t){return!e||t.length%4!==0?!1:(this._gl.uniform4iv(e,t),!0)}setUInt(e,t){return e?(this._gl.uniform1ui(e,t),!0):!1}setUInt2(e,t,i){return e?(this._gl.uniform2ui(e,t,i),!0):!1}setUInt3(e,t,i,s){return e?(this._gl.uniform3ui(e,t,i,s),!0):!1}setUInt4(e,t,i,s,r){return e?(this._gl.uniform4ui(e,t,i,s,r),!0):!1}setUIntArray(e,t){return e?(this._gl.uniform1uiv(e,t),!0):!1}setUIntArray2(e,t){return!e||t.length%2!==0?!1:(this._gl.uniform2uiv(e,t),!0)}setUIntArray3(e,t){return!e||t.length%3!==0?!1:(this._gl.uniform3uiv(e,t),!0)}setUIntArray4(e,t){return!e||t.length%4!==0?!1:(this._gl.uniform4uiv(e,t),!0)}setArray(e,t){return!e||t.length<1?!1:(this._gl.uniform1fv(e,t),!0)}setArray2(e,t){return!e||t.length%2!==0?!1:(this._gl.uniform2fv(e,t),!0)}setArray3(e,t){return!e||t.length%3!==0?!1:(this._gl.uniform3fv(e,t),!0)}setArray4(e,t){return!e||t.length%4!==0?!1:(this._gl.uniform4fv(e,t),!0)}setMatrices(e,t){return e?(this._gl.uniformMatrix4fv(e,!1,t),!0):!1}setMatrix3x3(e,t){return e?(this._gl.uniformMatrix3fv(e,!1,t),!0):!1}setMatrix2x2(e,t){return e?(this._gl.uniformMatrix2fv(e,!1,t),!0):!1}setFloat(e,t){return e?(this._gl.uniform1f(e,t),!0):!1}setFloat2(e,t,i){return e?(this._gl.uniform2f(e,t,i),!0):!1}setFloat3(e,t,i,s){return e?(this._gl.uniform3f(e,t,i,s),!0):!1}setFloat4(e,t,i,s,r){return e?(this._gl.uniform4f(e,t,i,s,r),!0):!1}applyStates(){if(this._depthCullingState.apply(this._gl),this._stencilStateComposer.apply(this._gl),this._alphaState.apply(this._gl),this._colorWriteChanged){this._colorWriteChanged=!1;const e=this._colorWrite;this._gl.colorMask(e,e,e,e)}}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}clearInternalTexturesCache(){this._internalTexturesCache.length=0}wipeCaches(e){this.preventCacheWipeBetweenFrames&&!e||(this._currentEffect=null,this._viewportCached.x=0,this._viewportCached.y=0,this._viewportCached.z=0,this._viewportCached.w=0,this._unbindVertexArrayObject(),e&&(this._currentProgram=null,this.resetTextureCache(),this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=this._gl.LEQUAL,this._alphaState.reset(),this._alphaMode=1,this._alphaEquation=0,this._colorWrite=!0,this._colorWriteChanged=!0,this._unpackFlipYCached=null,this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this._mustWipeVertexAttributes=!0,this.unbindAllAttributes()),this._resetVertexBufferBinding(),this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null,this.bindIndexBuffer(null))}_getSamplingParameters(e,t){const i=this._gl;let s=i.NEAREST,r=i.NEAREST;switch(e){case 11:s=i.LINEAR,t?r=i.LINEAR_MIPMAP_NEAREST:r=i.LINEAR;break;case 3:s=i.LINEAR,t?r=i.LINEAR_MIPMAP_LINEAR:r=i.LINEAR;break;case 8:s=i.NEAREST,t?r=i.NEAREST_MIPMAP_LINEAR:r=i.NEAREST;break;case 4:s=i.NEAREST,t?r=i.NEAREST_MIPMAP_NEAREST:r=i.NEAREST;break;case 5:s=i.NEAREST,t?r=i.LINEAR_MIPMAP_NEAREST:r=i.LINEAR;break;case 6:s=i.NEAREST,t?r=i.LINEAR_MIPMAP_LINEAR:r=i.LINEAR;break;case 7:s=i.NEAREST,r=i.LINEAR;break;case 1:s=i.NEAREST,r=i.NEAREST;break;case 9:s=i.LINEAR,t?r=i.NEAREST_MIPMAP_NEAREST:r=i.NEAREST;break;case 10:s=i.LINEAR,t?r=i.NEAREST_MIPMAP_LINEAR:r=i.NEAREST;break;case 2:s=i.LINEAR,r=i.LINEAR;break;case 12:s=i.LINEAR,r=i.NEAREST;break}return{min:r,mag:s}}_createTexture(){const e=this._gl.createTexture();if(!e)throw new Error("Unable to create texture");return e}_createHardwareTexture(){return new ro(this._createTexture(),this._gl)}_createInternalTexture(e,t,i=!0,s=Fe.Unknown){var r;let n=!1,a=0,o=3,h=5,c=!1,u=1,f;t!==void 0&&typeof t=="object"?(n=!!t.generateMipMaps,a=t.type===void 0?0:t.type,o=t.samplingMode===void 0?3:t.samplingMode,h=t.format===void 0?5:t.format,c=t.useSRGBBuffer===void 0?!1:t.useSRGBBuffer,u=(r=t.samples)!==null&&r!==void 0?r:1,f=t.label):n=!!t,c&&(c=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU)),(a===1&&!this._caps.textureFloatLinearFiltering||a===2&&!this._caps.textureHalfFloatLinearFiltering)&&(o=1),a===1&&!this._caps.textureFloat&&(a=0,F.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=this._gl,_=new ht(this,s),p=e.width||e,m=e.height||e,T=e.layers||0,S=this._getSamplingParameters(o,n),x=T!==0?d.TEXTURE_2D_ARRAY:d.TEXTURE_2D,b=this._getRGBABufferInternalSizedFormat(a,h,c),I=this._getInternalFormat(h),R=this._getWebGLTextureType(a);return this._bindTextureDirectly(x,_),T!==0?(_.is2DArray=!0,d.texImage3D(x,0,b,p,m,T,0,I,R,null)):d.texImage2D(x,0,b,p,m,0,I,R,null),d.texParameteri(x,d.TEXTURE_MAG_FILTER,S.mag),d.texParameteri(x,d.TEXTURE_MIN_FILTER,S.min),d.texParameteri(x,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(x,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(x),this._bindTextureDirectly(x,null),_._useSRGBBuffer=c,_.baseWidth=p,_.baseHeight=m,_.width=p,_.height=m,_.depth=T,_.isReady=!0,_.samples=u,_.generateMipMaps=n,_.samplingMode=o,_.type=a,_.format=h,_.label=f,this._internalTexturesCache.push(_),_}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,s,r=3,n=null,a=null,o,h,c=null,u=null,f=null,d=null,_,p,m){e=e||"";const T=e.substr(0,5)==="data:",S=e.substr(0,5)==="blob:",x=T&&e.indexOf(";base64,")!==-1,b=u||new ht(this,Fe.Url);b!==u&&(b.label=e.substring(0,60));const I=e;this._transformTextureUrl&&!x&&!u&&!c&&(e=this._transformTextureUrl(e)),I!==e&&(b._originalUrl=I);const R=e.lastIndexOf(".");let C=d||(R>-1?e.substring(R).toLowerCase():""),y=null;C.indexOf("?")>-1&&(C=C.split("?")[0]);for(const Q of re._TextureLoaders)if(Q.canLoad(C,_)){y=Q;break}s&&s.addPendingData(b),b.url=e,b.generateMipMaps=!t,b.samplingMode=r,b.invertY=i,b._useSRGBBuffer=this._getUseSRGBBuffer(!!m,t),this._doNotHandleContextLost||(b._buffer=c);let G=null;n&&!u&&(G=b.onLoadedObservable.add(n)),u||this._internalTexturesCache.push(b);const te=(Q,Te)=>{s&&s.removePendingData(b),e===I?(G&&b.onLoadedObservable.remove(G),Ee.UseFallbackTexture&&this._createTextureBase(Ee.FallbackTexture,t,b.invertY,s,r,null,a,o,h,c,b),Q=(Q||"Unknown error")+(Ee.UseFallbackTexture?" - Fallback texture was used":""),b.onErrorObservable.notifyObservers({message:Q,exception:Te}),a&&a(Q,Te)):(F.Warn(`Failed to load ${e}, falling back to ${I}`),this._createTextureBase(I,t,b.invertY,s,r,n,a,o,h,c,b,f,d,_,p,m))};if(y){const Q=Te=>{y.loadData(Te,b,(he,ve,le,be,ye,Ye)=>{Ye?te("TextureLoader failed to load data"):o(b,C,s,{width:he,height:ve},b.invertY,!le,be,()=>(ye(),!1),r)},p)};c?c instanceof ArrayBuffer?Q(new Uint8Array(c)):ArrayBuffer.isView(c)?Q(c):a&&a("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,Te=>Q(new Uint8Array(Te)),void 0,s?s.offlineProvider:void 0,!0,(Te,he)=>{te("Unable to load "+he)})}else{const Q=Te=>{S&&!this._doNotHandleContextLost&&(b._buffer=Te),o(b,C,s,Te,b.invertY,t,!1,h,r)};!T||x?c&&(typeof c.decoding=="string"||c.close)?Q(c):re._FileToolsLoadImage(e,Q,te,s?s.offlineProvider:null,_,b.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):typeof c=="string"||c instanceof ArrayBuffer||ArrayBuffer.isView(c)||c instanceof Blob?re._FileToolsLoadImage(c,Q,te,s?s.offlineProvider:null,_,b.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):c&&Q(c)}return b}createTexture(e,t,i,s,r=3,n=null,a=null,o=null,h=null,c=null,u=null,f,d,_,p){return this._createTextureBase(e,t,i,s,r,n,a,this._prepareWebGLTexture.bind(this),(m,T,S,x,b,I)=>{const R=this._gl,C=S.width===m&&S.height===T,y=c?this._getInternalFormat(c,b._useSRGBBuffer):x===".jpg"&&!b._useSRGBBuffer?R.RGB:b._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:R.RGBA;let w=c?this._getInternalFormat(c):x===".jpg"&&!b._useSRGBBuffer?R.RGB:R.RGBA;if(b._useSRGBBuffer&&this.webGLVersion===1&&(w=y),C)return R.texImage2D(R.TEXTURE_2D,0,y,w,R.UNSIGNED_BYTE,S),!1;const G=this._caps.maxTextureSize;if(S.width>G||S.height>G||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=m,this._workingCanvas.height=T,this._workingContext.drawImage(S,0,0,S.width,S.height,0,0,m,T),R.texImage2D(R.TEXTURE_2D,0,y,w,R.UNSIGNED_BYTE,this._workingCanvas),b.width=m,b.height=T),!1;{const te=new ht(this,Fe.Temp);this._bindTextureDirectly(R.TEXTURE_2D,te,!0),R.texImage2D(R.TEXTURE_2D,0,y,w,R.UNSIGNED_BYTE,S),this._rescaleTexture(te,b,s,y,()=>{this._releaseTexture(te),this._bindTextureDirectly(R.TEXTURE_2D,b,!0),I()})}return!0},o,h,c,u,f,d,p)}static _FileToolsLoadImage(e,t,i,s,r,n){throw fe("FileTools")}_rescaleTexture(e,t,i,s,r){}createRawTexture(e,t,i,s,r,n,a,o=null,h=0,c=0,u=!1){throw fe("Engine.RawTexture")}createRawCubeTexture(e,t,i,s,r,n,a,o=null){throw fe("Engine.RawTexture")}createRawTexture3D(e,t,i,s,r,n,a,o,h=null,c=0){throw fe("Engine.RawTexture")}createRawTexture2DArray(e,t,i,s,r,n,a,o,h=null,c=0){throw fe("Engine.RawTexture")}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.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 r=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&s!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_setupDepthStencilTexture(e,t,i,s,r,n=1){const a=t.width||t,o=t.height||t,h=t.layers||0;e.baseWidth=a,e.baseHeight=o,e.width=a,e.height=o,e.is2DArray=h>0,e.depth=h,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=0,e._comparisonFunction=r;const c=this._gl,u=this._getTextureTarget(e),f=this._getSamplingParameters(e.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&&(r===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,r),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,a=0){const o=this._gl;let h=o.TEXTURE_2D;if(e.isCube&&(h=o.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=o.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1;break}this._gl.compressedTexImage2D(h,a,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const a=this._gl,o=this._getWebGLTextureType(e.type),h=this._getInternalFormat(e.format),c=r===void 0?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let u=a.TEXTURE_2D;e.isCube&&(u=a.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),_=n?e.width:Math.pow(2,Math.max(f-s,0)),p=n?e.height:Math.pow(2,Math.max(d-s,0));a.texImage2D(u,s,c,_,p,0,h,o,t)}updateTextureData(e,t,i,s,r,n,a=0,o=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,_=c.TEXTURE_2D;e.isCube&&(_=c.TEXTURE_CUBE_MAP_POSITIVE_X+a,d=c.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),c.texSubImage2D(_,o,i,s,r,n,f,u,t),h&&this._gl.generateMipmap(_),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,r){const n=this._gl;if(!n)return;const a=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,a.min),!i&&!s&&n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,a,o,h=3){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?re.GetExponentOfTwo(s.width,c):s.width),f=Math.min(c,this.needPOTTextures?re.GetExponentOfTwo(s.height,c):s.height),d=this._gl;if(d){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(d.TEXTURE_2D,e,!0),this._unpackFlipY(r===void 0?!0:!!r),e.baseWidth=s.width,e.baseHeight=s.height,e.width=u,e.height=f,e.isReady=!0,!o(u,f,s,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,n,a,h)})&&this._prepareWebGLTextureContinuation(e,i,n,a,h)}}_setupFramebufferDepthAttachments(e,t,i,s,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(i,s,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let a=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(a=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,a,a,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,a=!0){const h=this._gl.createRenderbuffer();return this._updateRenderBuffer(h,e,t,i,s,r,n,a)}_updateRenderBuffer(e,t,i,s,r,n,a,o=!0){const h=this._gl;return h.bindRenderbuffer(h.RENDERBUFFER,e),s>1&&h.renderbufferStorageMultisample?h.renderbufferStorageMultisample(h.RENDERBUFFER,s,n,t,i):h.renderbufferStorage(h.RENDERBUFFER,r,t,i),h.framebufferRenderbuffer(h.FRAMEBUFFER,a,h.RENDERBUFFER,e),o&&h.bindRenderbuffer(h.RENDERBUFFER,null),e}_releaseTexture(e){var t;this._deleteTexture((t=e._hardwareTexture)===null||t===void 0?void 0:t.underlyingResource),this.unbindAllTextures();const i=this._internalTexturesCache.indexOf(e);i!==-1&&this._internalTexturesCache.splice(i,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){const t=this._renderTargetWrapperCache.indexOf(e);t!==-1&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let s=0;s<i.length;s++){const r=e.getUniform(i[s]);r&&(this._boundUniforms[s]=r)}this._currentEffect=null}_activateCurrentTexture(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)}_bindTextureDirectly(e,t,i=!1,s=!1){var r,n;let a=!1;const o=t&&t._associatedChannel>-1;if(i&&o&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw console.error(e,t),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,(n=(r=t==null?void 0:t._hardwareTexture)===null||r===void 0?void 0:r.underlyingResource)!==null&&n!==void 0?n:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(a=!0,this._activateCurrentTexture());return o&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),a}_bindTexture(e,t,i){if(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;e<this._maxSimultaneousTextures;e++)this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,s){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,r=""){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 n;s?n=t.depthStencilTexture:t.isReady()?n=t.getInternalTexture():t.isCube?n=this.emptyCubeTexture:t.is3D?n=this.emptyTexture3D:t.is2DArray?n=this.emptyTexture2DArray:n=this.emptyTexture,!i&&n&&(n._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),a=!1),this._activeChannel=e;const o=this._getTextureTarget(n);if(a&&this._bindTextureDirectly(o,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const h=t.coordinatesMode!==3&&t.coordinatesMode!==5?1:0;t.wrapU=h,t.wrapV=h}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(o,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(!(e===void 0||!t)){(!this._textureUnits||this._textureUnits.length!==i.length)&&(this._textureUnits=new Int32Array(i.length));for(let r=0;r<i.length;r++){const n=i[r].getInternalTexture();n?(this._textureUnits[r]=e+r,n._associatedChannel=e+r):this._textureUnits[r]=-1}this._gl.uniform1iv(t,this._textureUnits);for(let r=0;r<i.length;r++)this._setTexture(this._textureUnits[r],i[r],!0)}}_setAnisotropicLevel(e,t,i){const s=this._caps.textureAnisotropicFilterExtension;t.samplingMode!==11&&t.samplingMode!==3&&t.samplingMode!==2&&(i=1),s&&t._cachedAnisotropicFilteringLevel!==i&&(this._setTextureParameterFloat(e,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(i,this._caps.maxAnisotropy),t),t._cachedAnisotropicFilteringLevel=i)}_setTextureParameterFloat(e,t,i,s){this._bindTextureDirectly(e,s,!0,!0),this._gl.texParameterf(e,t,i)}_setTextureParameterInteger(e,t,i,s){s&&this._bindTextureDirectly(e,s,!0,!0),this._gl.texParameteri(e,t,i)}unbindAllAttributes(){if(this._mustWipeVertexAttributes){this._mustWipeVertexAttributes=!1;for(let e=0;e<this._caps.maxVertexAttribs;e++)this.disableAttributeByIndex(e);return}for(let e=0,t=this._vertexAttribArraysEnabled.length;e<t;e++)e>=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e;this._isDisposed=!0,this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),(e=this.releaseComputeEffects)===null||e===void 0||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},Mt()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),window.removeEventListener("resize",this._checkForMobile)),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,nt.ResetCache();for(const t of this._activeRequests)t.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const 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 r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&n===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 a=t.RGBA,o=t.UNSIGNED_BYTE,h=new Uint8Array(4);t.readPixels(0,0,1,1,a,o,h),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(r),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}_getRGBAMultiSampleBufferFormat(e,t=5){switch(e){case 1:switch(t){case 6:return this._gl.R32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;default:return this._gl.RGBA16F}}return this._gl.RGBA8}_loadFile(e,t,i,s,r,n){const a=re._FileToolsLoadFile(e,t,i,s,r,n);return this._activeRequests.push(a),a.onCompleteObservable.add(o=>{this._activeRequests.splice(this._activeRequests.indexOf(o),1)}),a}static _FileToolsLoadFile(e,t,i,s,r,n){throw fe("FileTools")}readPixels(e,t,i,s,r=!0,n=!0){const a=r?4:3,o=r?this._gl.RGBA:this._gl.RGB,h=new Uint8Array(s*i*a);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,o,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=this._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=this._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}static CeilingPOT(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}static FloorPOT(e){return e=e|e>>1,e=e|e>>2,e=e|e>>4,e=e|e>>8,e=e|e>>16,e-(e>>1)}static NearestPOT(e){const t=re.CeilingPOT(e),i=re.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let s;switch(i){case 1:s=re.FloorPOT(e);break;case 2:s=re.NearestPOT(e);break;case 3:default:s=re.CeilingPOT(e);break}return Math.min(s,t)}static QueueNewFrame(e,t){if(Mt()){const{requestPostAnimationFrame:i,requestAnimationFrame:s}=t||window;if(typeof i=="function")return i(e);if(typeof s=="function")return s(e)}else if(typeof requestAnimationFrame=="function")return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:_r()?document:null}}re.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],re._TextureLoaders=[],re.CollisionsEpsilon=.001,re._IsSupported=null,re._HasMajorPerformanceCaveat=null;class $r{static SetImmediate(e){Mt()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}const no=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class Tr extends xi{constructor(e,t){super(e,is.LoadFileError),this.name="LoadFileError",ks._setPrototypeOf(this,Tr.prototype),t instanceof wt?this.request=t:this.file=t}}class Jr extends xi{constructor(e,t){super(e,is.RequestFileError),this.request=t,this.name="RequestFileError",ks._setPrototypeOf(this,Jr.prototype)}}class yn extends xi{constructor(e,t){super(e,is.ReadFileError),this.file=t,this.name="ReadFileError",ks._setPrototypeOf(this,yn.prototype)}}const bt={DefaultRetryStrategy:fh.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:l=>l},ao=l=>(l=l.replace(/#/gm,"%23"),l),Mn=(l,e)=>{if(!(l&&l.indexOf("data:")===0)&&bt.CorsBehavior)if(typeof bt.CorsBehavior=="string"||bt.CorsBehavior instanceof String)e.crossOrigin=bt.CorsBehavior;else{const t=bt.CorsBehavior(l);t&&(e.crossOrigin=t)}},Ar=(l,e,t,i,s="",r)=>{var n;let a,o=!1;l instanceof ArrayBuffer||ArrayBuffer.isView(l)?typeof Blob<"u"&&typeof URL<"u"?(a=URL.createObjectURL(new Blob([l],{type:s})),o=!0):a=`data:${s};base64,`+eo(l):l instanceof Blob?(a=URL.createObjectURL(l),o=!0):(a=ao(l),a=bt.PreprocessUrl(l));const h=Ee.LastCreatedEngine,c=R=>{if(t){const C=a||l.toString();t(`Error while trying to load image: ${C.indexOf("http")===0||C.length<=128?C:C.slice(0,128)+"..."}`,R)}};if(typeof Image>"u"||(n=h==null?void 0:h._features.forceBitmapOverHTMLImageElement)!==null&&n!==void 0&&n)return rs(a,R=>{h.createImageBitmap(new Blob([R],{type:s}),Object.assign({premultiplyAlpha:"none"},r)).then(C=>{e(C),o&&URL.revokeObjectURL(a)}).catch(C=>{t&&t("Error while trying to load image: "+l,C)})},void 0,i||void 0,!0,(R,C)=>{c(C)}),null;const u=new Image;Mn(a,u);const f=[],d=()=>{f.forEach(R=>{R.target.addEventListener(R.name,R.handler)})},_=()=>{f.forEach(R=>{R.target.removeEventListener(R.name,R.handler)}),f.length=0},p=()=>{_(),e(u),o&&u.src&&URL.revokeObjectURL(u.src)},m=R=>{_(),c(R),o&&u.src&&URL.revokeObjectURL(u.src)},T=R=>{if(R.blockedURI!==u.src)return;_();const C=new Error(`CSP violation of policy ${R.effectiveDirective} ${R.blockedURI}. Current policy is ${R.originalPolicy}`);Ee.UseFallbackTexture=!1,c(C),o&&u.src&&URL.revokeObjectURL(u.src),u.src=""};f.push({target:u,name:"load",handler:p}),f.push({target:u,name:"error",handler:m}),f.push({target:document,name:"securitypolicyviolation",handler:T}),d();const S=a.substring(0,5)==="blob:",x=a.substring(0,5)==="data:",b=()=>{S||x?u.src=a:rs(a,(R,C,y)=>{const w=!s&&y?y:s,G=new Blob([R],{type:w}),te=URL.createObjectURL(G);o=!0,u.src=te},void 0,i||void 0,!0,(R,C)=>{c(C)})},I=()=>{i&&i.loadImage(a,u)};if(!S&&!x&&i&&i.enableTexturesOffline)i.open(I,b);else{if(a.indexOf("file:")!==-1){const R=decodeURIComponent(a.substring(5).toLowerCase());if(mr.FilesToLoad[R]&&typeof URL<"u"){try{let C;try{C=URL.createObjectURL(mr.FilesToLoad[R])}catch{C=URL.createObjectURL(mr.FilesToLoad[R])}u.src=C,o=!0}catch{u.src=""}return u}}b()}return u},vr=(l,e,t,i,s)=>{const r=new FileReader,n={onCompleteObservable:new B,abort:()=>r.abort()};return r.onloadend=()=>n.onCompleteObservable.notifyObservers(n),s&&(r.onerror=()=>{s(new yn(`Unable to read ${l.name}`,l))}),r.onload=a=>{e(a.target.result)},t&&(r.onprogress=t),i?r.readAsArrayBuffer(l):r.readAsText(l),n},rs=(l,e,t,i,s,r,n)=>{if(l.name)return vr(l,e,t,s,r?c=>{r(void 0,c)}:void 0);const a=l;if(a.indexOf("file:")!==-1){let c=decodeURIComponent(a.substring(5).toLowerCase());c.indexOf("./")===0&&(c=c.substring(2));const u=mr.FilesToLoad[c];if(u)return vr(u,e,t,s,r?f=>r(void 0,new Tr(f.message,f.file)):void 0)}const{match:o,type:h}=Nh(a);if(o){const c={onCompleteObservable:new B,abort:()=>()=>{}};try{const u=s?Sr(a):lo(a);e(u,void 0,h)}catch(u){r?r(void 0,u):F.Error(u.message||"Failed to parse the Data URL")}return $r.SetImmediate(()=>{c.onCompleteObservable.notifyObservers(c)}),c}return Pn(a,(c,u)=>{e(c,u==null?void 0:u.responseURL,u==null?void 0:u.getResponseHeader("content-type"))},t,i,s,r?c=>{r(c.request,new Tr(c.message,c.request))}:void 0,n)},Pn=(l,e,t,i,s,r,n)=>{l=ao(l),l=bt.PreprocessUrl(l);const a=bt.BaseUrl+l;let o=!1;const h={onCompleteObservable:new B,abort:()=>o=!0},c=()=>{let u=new wt,f=null,d;const _=()=>{u&&(t&&u.removeEventListener("progress",t),d&&u.removeEventListener("readystatechange",d),u.removeEventListener("loadend",p))};let p=()=>{_(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),t=void 0,d=null,p=null,r=void 0,n=void 0,e=void 0};h.abort=()=>{o=!0,p&&p(),u&&u.readyState!==(XMLHttpRequest.DONE||4)&&u.abort(),f!==null&&(clearTimeout(f),f=null),u=null};const m=S=>{const x=S.message||"Unknown error";r&&u?r(new Jr(x,u)):F.Error(x)},T=S=>{if(u){if(u.open("GET",a),n)try{n(u)}catch(x){m(x);return}s&&(u.responseType="arraybuffer"),t&&u.addEventListener("progress",t),p&&u.addEventListener("loadend",p),d=()=>{if(!(o||!u)&&u.readyState===(XMLHttpRequest.DONE||4)){if(d&&u.removeEventListener("readystatechange",d),u.status>=200&&u.status<300||u.status===0&&(!Mt()||oo())){try{e&&e(s?u.response:u.responseText,u)}catch(I){m(I)}return}const x=bt.DefaultRetryStrategy;if(x){const I=x(a,u,S);if(I!==-1){_(),u=new wt,f=setTimeout(()=>T(S+1),I);return}}const b=new Jr("Error status: "+u.status+" "+u.statusText+" - Unable to load "+a,u);r&&r(b)}},u.addEventListener("readystatechange",d),u.send()}};T(0)};if(i&&i.enableSceneOffline){const u=d=>{d&&d.status>400?r&&r(d):c()},f=()=>{i&&i.loadFile(bt.BaseUrl+l,d=>{!o&&e&&e(d),h.onCompleteObservable.notifyObservers(h)},t?d=>{!o&&t&&t(d)}:void 0,u,s)};i.open(f,u)}else c();return h},oo=()=>typeof location<"u"&&location.protocol==="file:",en=l=>no.test(l),Nh=l=>{const e=no.exec(l);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace("base64,","")}};function Sr(l){return _h(l.split(",")[1])}const lo=l=>to(l.split(",")[1]);(()=>{re._FileToolsLoadImage=Ar,re._FileToolsLoadFile=rs,Oi._FileToolsLoadFile=rs})();let Rr;((l,e,t,i,s,r,n,a,o,h)=>{Rr={DecodeBase64UrlToBinary:l,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:s,LoadFile:r,LoadImage:n,ReadFile:a,RequestFile:o,SetCorsBehavior:h},Object.defineProperty(Rr,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(c){t.DefaultRetryStrategy=c}}),Object.defineProperty(Rr,"BaseUrl",{get:function(){return t.BaseUrl},set:function(c){t.BaseUrl=c}}),Object.defineProperty(Rr,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(c){t.PreprocessUrl=c}}),Object.defineProperty(Rr,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(c){t.CorsBehavior=c}})})(Sr,lo,bt,en,oo,rs,Ar,vr,Pn,Mn);class xr{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=Ri(e);if(t)return t;F.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let r=0,n=i.length;r<n;r++)s=s[i[r]];return typeof s!="function"?null:s}}xr.RegisteredExternalClasses={};function On(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,l=>{const e=Math.random()*16|0;return(l==="x"?e:e&3|8).toString(16)})}class k{static get BaseUrl(){return bt.BaseUrl}static set BaseUrl(e){bt.BaseUrl=e}static get DefaultRetryStrategy(){return bt.DefaultRetryStrategy}static set DefaultRetryStrategy(e){bt.DefaultRetryStrategy=e}static get CorsBehavior(){return bt.CorsBehavior}static set CorsBehavior(e){bt.CorsBehavior=e}static get UseFallbackTexture(){return Ee.UseFallbackTexture}static set UseFallbackTexture(e){Ee.UseFallbackTexture=e}static get RegisteredExternalClasses(){return xr.RegisteredExternalClasses}static set RegisteredExternalClasses(e){xr.RegisteredExternalClasses=e}static get fallbackTexture(){return Ee.FallbackTexture}static set fallbackTexture(e){Ee.FallbackTexture=e}static FetchToRef(e,t,i,s,r,n){const a=Math.abs(e)*i%i|0,o=Math.abs(t)*s%s|0,h=(a+o*i)*4;n.r=r[h]/255,n.g=r[h+1]/255,n.b=r[h+2]/255,n.a=r[h+3]/255}static Mix(e,t,i){return e*(1-i)+t*i}static Instantiate(e){return xr.Instantiate(e)}static SetImmediate(e){$r.SetImmediate(e)}static IsExponentOfTwo(e){let t=1;do t*=2;while(t<e);return t===e}static FloatRound(e){return Math.fround?Math.fround(e):(k._TmpFloatArray[0]=e,k._TmpFloatArray[0])}static GetFilename(e){const t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)}static GetFolderPath(e,t=!1){const i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)}static ToDegrees(e){return e*180/Math.PI}static ToRadians(e){return e*Math.PI/180}static SmoothAngleChange(e,t,i=.9){const s=this.ToRadians(e),r=this.ToRadians(t);return this.ToDegrees(Math.atan2((1-i)*Math.sin(r)+i*Math.sin(s),(1-i)*Math.cos(r)+i*Math.cos(s)))}static MakeArray(e,t){return t!==!0&&(e===void 0||e==null)?null:Array.isArray(e)?e:[e]}static GetPointerPrefix(e){let t="pointer";return Mt()&&!window.PointerEvent&&(t="mouse"),e._badDesktopOS&&!e._badOS&&!(document&&"ontouchend"in document)&&(t="mouse"),t}static SetCorsBehavior(e,t){Mn(e,t)}static SetReferrerPolicyBehavior(e,t){t.referrerPolicy=e}static CleanUrl(e){return e=e.replace(/#/gm,"%23"),e}static get PreprocessUrl(){return bt.PreprocessUrl}static set PreprocessUrl(e){bt.PreprocessUrl=e}static LoadImage(e,t,i,s,r,n){return Ar(e,t,i,s,r,n)}static LoadFile(e,t,i,s,r,n){return rs(e,t,i,s,r,n)}static LoadFileAsync(e,t=!0){return new Promise((i,s)=>{rs(e,r=>{i(r)},void 0,void 0,t,(r,n)=>{s(n)})})}static LoadScript(e,t,i,s){if(typeof importScripts=="function"){try{importScripts(e),t()}catch(a){i==null||i(`Unable to load script '${e}' in worker`,a)}return}else if(!Mt()){i==null||i(`Cannot load script '${e}' outside of a window or a worker`);return}const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),s&&(n.id=s),n.onload=()=>{t&&t()},n.onerror=a=>{i&&i(`Unable to load script '${e}'`,a)},r.appendChild(n)}static LoadScriptAsync(e){return new Promise((t,i)=>{this.LoadScript(e,()=>{t()},(s,r)=>{i(r||new Error(s))})})}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new B,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=n=>{t(n.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,s,r){return vr(e,t,i,s,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,s){pr.DeepCopy(e,t,i,s)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){const s=t[i];e.addEventListener(s.name,s.handler,!1);try{window.parent&&window.parent.addEventListener(s.name,s.handler,!1)}catch{}}}static UnregisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){const s=t[i];e.removeEventListener(s.name,s.handler);try{e.parent&&e.parent.removeEventListener(s.name,s.handler)}catch{}}}static async DumpFramebuffer(e,t,i,s,r="image/png",n,a){throw fe("DumpTools")}static DumpData(e,t,i,s,r="image/png",n,a=!1,o=!1,h){throw fe("DumpTools")}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,a=!1,o){throw fe("DumpTools")}static _IsOffScreenCanvas(e){return e.convertToBlob!==void 0}static ToBlob(e,t,i="image/png",s){!k._IsOffScreenCanvas(e)&&!e.toBlob&&(e.toBlob=function(r,n,a){setTimeout(()=>{const o=atob(this.toDataURL(n,a).split(",")[1]),h=o.length,c=new Uint8Array(h);for(let u=0;u<h;u++)c[u]=o.charCodeAt(u);r(new Blob([c]))})}),k._IsOffScreenCanvas(e)?e.convertToBlob({type:i,quality:s}).then(r=>t(r)):e.toBlob(function(r){t(r)},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"}k.Download(e,t)}else if(e&&typeof URL<"u"){const i=URL.createObjectURL(e),s=window.open("");if(!s)return;const r=s.document.createElement("img");r.onload=function(){URL.revokeObjectURL(i)},r.src=i,s.document.body.appendChild(r)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,r){if(typeof s=="string"||!t)this.ToBlob(e,function(n){n&&k.DownloadBlob(n,s),t&&t("")},i,r);else if(t){if(k._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:r}).then(a=>{const o=new FileReader;o.readAsDataURL(a),o.onloadend=()=>{const h=o.result;t(h)}});return}const n=e.toDataURL(i,r);t(n)}}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,r="image/png",n=!1,a){throw fe("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw fe("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,a=!1,o,h=!1,c=!1,u=!0,f){throw fe("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,a,o=!1,h=!1,c=!0,u){throw fe("ScreenshotTools")}static RandomId(){return On()}static IsBase64(e){return en(e)}static DecodeBase64(e){return Sr(e)}static get errorsCount(){return F.errorsCount}static Log(e){F.Log(e)}static Warn(e){F.Warn(e)}static Error(e){F.Error(e)}static get LogCache(){return F.LogCache}static ClearLogCache(){F.ClearLogCache()}static set LogLevels(e){F.LogLevels=e}static set PerformanceLogLevel(e){if((e&k.PerformanceUserMarkLogLevel)===k.PerformanceUserMarkLogLevel){k.StartPerformanceCounter=k._StartUserMark,k.EndPerformanceCounter=k._EndUserMark;return}if((e&k.PerformanceConsoleLogLevel)===k.PerformanceConsoleLogLevel){k.StartPerformanceCounter=k._StartPerformanceConsole,k.EndPerformanceCounter=k._EndPerformanceConsole;return}k.StartPerformanceCounter=k._StartPerformanceCounterDisabled,k.EndPerformanceCounter=k._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!k._Performance){if(!Mt())return;k._Performance=window.performance}!t||!k._Performance.mark||k._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!k._Performance.mark||(k._Performance.mark(e+"-End"),k._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(k._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(k._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return ii.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 r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,s=r.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 qr()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}}k.UseCustomRequestHeaders=!1,k.CustomRequestHeaders=wt.CustomRequestHeaders,k._TmpFloatArray=new Float32Array(1),k.GetDOMTextContent=$a,k.GetAbsoluteUrl=typeof document=="object"?l=>{const e=document.createElement("a");return e.href=l,e.href}:typeof URL=="function"&&typeof location=="object"?l=>new URL(l,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},k.NoneLogLevel=F.NoneLogLevel,k.MessageLogLevel=F.MessageLogLevel,k.WarningLogLevel=F.WarningLogLevel,k.ErrorLogLevel=F.ErrorLogLevel,k.AllLogLevel=F.AllLogLevel,k.IsWindowObjectExist=Mt,k.PerformanceNoneLogLevel=0,k.PerformanceUserMarkLogLevel=1,k.PerformanceConsoleLogLevel=2,k.StartPerformanceCounter=k._StartPerformanceCounterDisabled,k.EndPerformanceCounter=k._EndPerformanceCounterDisabled;class tn{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())}breakLoop(){this._done=!0,this._successCallback()}static Run(e,t,i,s=0){const r=new tn(e,t,i,s);return r.executeNext(),r}static SyncAsyncForLoop(e,t,i,s,r,n=0){return tn.Run(Math.ceil(e/t),a=>{r&&r()?a.breakLoop():setTimeout(()=>{for(let o=0;o<t;++o){const h=a.index*t+o;if(h>=e)break;if(i(h),r&&r()){a.breakLoop();break}}a.executeNext()},n)},s)}}Ee.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";function Dn(l,e,t){try{const i=l.next();i.done?e(i):i.value?i.value.then(()=>{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function Fh(l=25){let e;return(t,i,s)=>{const r=performance.now();e===void 0||r-e>l?(e=r,setTimeout(()=>{Dn(t,i,s)},0)):Dn(t,i,s)}}function ho(l,e,t,i,s){const r=()=>{let n;const a=o=>{o.done?t(o.value):n===void 0?n=!0:r()};do n=void 0,!s||!s.aborted?e(l,a,i):i(new Error("Aborted")),n===void 0&&(n=!1);while(n)};r()}function Ln(l,e){let t;return ho(l,Dn,i=>t=i,i=>{throw i},e),t}function wh(l,e,t){return new Promise((i,s)=>{ho(l,e,i,s,t)})}function Bh(l,e){return(...t)=>Ln(l(...t),e)}class vt{constructor(e){this.length=0,this.data=new Array(e),this._id=vt._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;t<this.length;t++)e(this.data[t])}sort(e){this.data.sort(e)}reset(){this.length=0}dispose(){this.reset(),this.data&&(this.data.length=0)}concat(e){if(e.length!==0){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}}indexOf(e){const t=this.data.indexOf(e);return t>=this.length?-1:t}contains(e){return this.indexOf(e)!==-1}}vt._GlobalId=0;class gs 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;t<e.length;t++){const i=(e.data||e)[t];this.pushNoDuplicate(i)}}}}class Cr{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new Cr(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 Cr(this.x,this.y,this.width,this.height)}}class Zt{constructor(e,t,i,s){this.normal=new E(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Zt(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=Zt._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,a=this.d,o=s*i[0]+r*i[1]+n*i[2]+a*i[3],h=s*i[4]+r*i[5]+n*i[6]+a*i[7],c=s*i[8]+r*i[9]+n*i[10]+a*i[11],u=s*i[12]+r*i[13]+n*i[14]+a*i[15];return new Zt(o,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,r=t.y-e.y,n=t.z-e.z,a=i.x-e.x,o=i.y-e.y,h=i.z-e.z,c=r*h-n*o,u=n*a-s*h,f=s*o-r*a,d=Math.sqrt(c*c+u*u+f*f);let _;return d!==0?_=1/d:_=0,this.normal.x=c*_,this.normal.y=u*_,this.normal.z=f*_,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return E.Dot(this.normal,e)<=t}signedDistanceTo(e){return E.Dot(e,this.normal)+this.d}static FromArray(e){return new Zt(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new Zt(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new Zt(0,0,0,0);return t.normalize(),i.normal=t,i.d=-(t.x*e.x+t.y*e.y+t.z*e.z),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return E.Dot(i,t)+s}}Zt._TmpMatrix=M.Identity();class li{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new Zt(0,0,0,0));return li.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){li.GetNearPlaneToRef(e,t[0]),li.GetFarPlaneToRef(e,t[1]),li.GetLeftPlaneToRef(e,t[2]),li.GetRightPlaneToRef(e,t[3]),li.GetTopPlaneToRef(e,t[4]),li.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}class ie extends lt{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var e,t,i,s;let r=0,n=0;if(this.mode===ie.PERSPECTIVE_CAMERA)this.fovMode===ie.FOVMODE_VERTICAL_FIXED?(n=this.minZ*2*Math.tan(this.fov/2),r=this.getEngine().getAspectRatio(this)*n):(r=this.minZ*2*Math.tan(this.fov/2),n=r/this.getEngine().getAspectRatio(this));else{const a=this.getEngine().getRenderWidth()/2,o=this.getEngine().getRenderHeight()/2;r=((e=this.orthoRight)!==null&&e!==void 0?e:a)-((t=this.orthoLeft)!==null&&t!==void 0?t:-a),n=((i=this.orthoTop)!==null&&i!==void 0?i:o)-((s=this.orthoBottom)!==null&&s!==void 0?s:-o)}return r*n}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}constructor(e,t,i,s=!0){super(e,i),this._position=E.Zero(),this._upVector=E.Up(),this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=ie.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Cr(0,0,1,1),this.layerMask=268435455,this.fovMode=ie.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=ie.RIG_MODE_NONE,this.customRenderTargets=new Array,this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new B,this.onProjectionMatrixChangedObservable=new B,this.onAfterCheckInputsObservable=new B,this.onRestoreStateObservable=new B,this.isRigCamera=!1,this._rigCameras=new Array,this._webvrViewMatrix=M.Identity(),this._skipRendering=!1,this._projectionMatrix=new M,this._postProcesses=new Array,this._activeMeshes=new vt(256),this._globalPosition=E.Zero(),this._computedViewMatrix=M.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=M.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=K.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_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<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}applyVerticalCorrection(){const e=this.absoluteRotation.toEulerAngles();this.projectionPlaneTilt=this._scene.useRightHandedSystem?-e.x:e.x}get globalPosition(){return this._globalPosition}getActiveMeshes(){return this._activeMeshes}isActiveMesh(e){return this._activeMeshes.indexOf(e)!==-1}isReady(e=!1){if(e){for(const t of this._postProcesses)if(t&&!t.isReady())return!1}return super.isReady(e)}_initCache(){super._initCache(),this._cache.position=new E(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new E(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0}_updateCache(e){e||super._updateCache(),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)}_isSynchronized(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()}_isSynchronizedViewMatrix(){return super._isSynchronized()?this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent():!1}_isSynchronizedProjectionMatrix(){let e=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ;if(!e)return!1;const t=this.getEngine();return this.mode===ie.PERSPECTIVE_CAMERA?e=this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===t.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:e=this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===t.getRenderWidth()&&this._cache.renderHeight===t.getRenderHeight(),e}attachControl(e,t){}detachControl(e){}update(){this._checkInputs(),this.cameraRigMode!==ie.RIG_MODE_NONE&&this._updateRigCameras(),this.getViewMatrix(),this.getProjectionMatrix()}_checkInputs(){this.onAfterCheckInputsObservable.notifyObservers(this)}get rigCameras(){return this._rigCameras}get rigPostProcess(){return this._rigPostProcess}_getFirstPostProcess(){for(let e=0;e<this._postProcesses.length;e++)if(this._postProcesses[e]!==null)return this._postProcesses[e];return null}_cascadePostProcessesToRigCams(){const e=this._getFirstPostProcess();e&&e.markTextureDirty();for(let t=0,i=this._rigCameras.length;t<i;t++){const s=this._rigCameras[t],r=s._rigPostProcess;r?(r.getEffectName()==="pass"&&(s.isIntermediate=this._postProcesses.length===0),s._postProcesses=this._postProcesses.slice(0).concat(r),r.markTextureDirty()):s._postProcesses=this._postProcesses.slice(0)}}attachPostProcess(e,t=null){return!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(F.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 M.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(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 t,i,s,r,n,a,o,h;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 c=this.getEngine(),u=this.getScene(),f=c.useReverseDepthBuffer;if(this.mode===ie.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=c.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let d;u.useRightHandedSystem?d=M.PerspectiveFovRHToRef:d=M.PerspectiveFovLHToRef,d(this.fov,c.getAspectRatio(this),f?this.maxZ:this.minZ,f?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===ie.FOVMODE_VERTICAL_FIXED,c.isNDCHalfZRange,this.projectionPlaneTilt,f)}else{const d=c.getRenderWidth()/2,_=c.getRenderHeight()/2;u.useRightHandedSystem?M.OrthoOffCenterRHToRef((t=this.orthoLeft)!==null&&t!==void 0?t:-d,(i=this.orthoRight)!==null&&i!==void 0?i:d,(s=this.orthoBottom)!==null&&s!==void 0?s:-_,(r=this.orthoTop)!==null&&r!==void 0?r:_,f?this.maxZ:this.minZ,f?this.minZ:this.maxZ,this._projectionMatrix,c.isNDCHalfZRange):M.OrthoOffCenterLHToRef((n=this.orthoLeft)!==null&&n!==void 0?n:-d,(a=this.orthoRight)!==null&&a!==void 0?a:d,(o=this.orthoBottom)!==null&&o!==void 0?o:-_,(h=this.orthoTop)!==null&&h!==void 0?h:_,f?this.maxZ:this.minZ,f?this.minZ:this.maxZ,this._projectionMatrix,c.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=c.getRenderWidth(),this._cache.renderHeight=c.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?li.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=li.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let 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 fe("Ray")}getForwardRayToRef(e,t=100,i,s){throw fe("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!==ie.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let s=this._postProcesses.length;for(;--s>=0;){const r=this._postProcesses[s];r&&r.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=k.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==ie.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 M.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}_updateCameraRotationMatrix(){}_updateWebVRCameraRotationMatrix(){}_getWebVRProjectionMatrix(){return M.Identity()}_getWebVRViewMatrix(){return M.Identity()}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,e==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=k.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===ie.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)}_setupInputs(){}serialize(){const e=J.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&this.parent._serializeAsParent(e),this.inputs&&this.inputs.serialize(e),J.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}clone(e,t=null){const i=J.Clone(ie.GetConstructorFromName(this.getClassName(),e,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this);return i.name=e,i.parent=t,this.onClonedObservable.notifyObservers(i),i}getDirection(e){const t=E.Zero();return this.getDirectionToRef(e,t),t}get absoluteRotation(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation}getDirectionToRef(e,t){E.TransformNormalToRef(e,this.getWorldMatrix(),t)}static GetConstructorFromName(e,t,i,s=0,r=!0){const n=lt.Construct(e,t,i,{interaxial_distance:s,isStereoscopicSideBySide:r});return n||(()=>ie._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=ie.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=J.Parse(s,e,t);if(e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=E.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(E.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(E.FromArray(e.target)),e.cameraRigMode){const n=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,n)}if(e.animations){for(let n=0;n<e.animations.length;n++){const a=e.animations[n],o=Ri("BABYLON.Animation");o&&r.animations.push(o.Parse(a))}lt.ParseAnimationRanges(r,e,t)}return e.autoAnimate&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.isEnabled!==void 0&&r.setEnabled(e.isEnabled),r}}ie._CreateDefaultParsedCamera=(l,e)=>{throw fe("UniversalCamera")},ie.PERSPECTIVE_CAMERA=0,ie.ORTHOGRAPHIC_CAMERA=1,ie.FOVMODE_VERTICAL_FIXED=0,ie.FOVMODE_HORIZONTAL_FIXED=1,ie.RIG_MODE_NONE=0,ie.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,ie.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,ie.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,ie.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,ie.RIG_MODE_STEREOSCOPIC_INTERLACED=14,ie.RIG_MODE_VR=20,ie.RIG_MODE_WEBVR=21,ie.RIG_MODE_CUSTOM=22,ie.ForceAttachControlToAlwaysPreventDefault=!1,g([Ut("position")],ie.prototype,"_position",void 0),g([Ut("upVector")],ie.prototype,"_upVector",void 0),g([v()],ie.prototype,"orthoLeft",null),g([v()],ie.prototype,"orthoRight",null),g([v()],ie.prototype,"orthoBottom",null),g([v()],ie.prototype,"orthoTop",null),g([v()],ie.prototype,"fov",void 0),g([v()],ie.prototype,"projectionPlaneTilt",void 0),g([v()],ie.prototype,"minZ",void 0),g([v()],ie.prototype,"maxZ",void 0),g([v()],ie.prototype,"inertia",void 0),g([v()],ie.prototype,"mode",null),g([v()],ie.prototype,"layerMask",void 0),g([v()],ie.prototype,"fovMode",void 0),g([v()],ie.prototype,"cameraRigMode",void 0),g([v()],ie.prototype,"interaxialDistance",void 0),g([v()],ie.prototype,"isStereoscopicSideBySide",void 0);class co{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach((t,i)=>this.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 hi{constructor(){this.rootNodes=new Array,this.cameras=new Array,this.lights=new Array,this.meshes=new Array,this.skeletons=new Array,this.particleSystems=new Array,this.animations=[],this.animationGroups=new Array,this.multiMaterials=new Array,this.materials=new Array,this.morphTargetManagers=new Array,this.geometries=new Array,this.transformNodes=new Array,this.actionManagers=new Array,this.textures=new Array,this._environmentTexture=null,this.postProcesses=new Array}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,s){for(const r in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,r)&&this._BabylonFileParsers[r](e,t,i,s)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=new Array;return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach(t=>e=e.concat(t.bones)),e}}hi._BabylonFileParsers={},hi._IndividualBabylonFileParsers={};class Ni{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;t<this._keys.length;t++){const i=this._keys[t];if(this[i]!==e[i])return!1}return!0}cloneTo(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(let t=0;t<this._keys.length;t++){const i=this._keys[t];e[i]=this[i]}}reset(){this._keys.forEach(e=>this._setDefaultValue(e))}_setDefaultValue(e){var t,i,s,r,n;const a=(s=(i=(t=this._externalProperties)===null||t===void 0?void 0:t[e])===null||i===void 0?void 0:i.type)!==null&&s!==void 0?s:typeof this[e],o=(n=(r=this._externalProperties)===null||r===void 0?void 0:r[e])===null||n===void 0?void 0:n.default;switch(a){case"number":this[e]=o??0;break;case"string":this[e]=o??"";break;default:this[e]=o??!1;break}}toString(){let e="";for(let t=0;t<this._keys.length;t++){const i=this._keys[t],s=this[i];switch(typeof s){case"number":case"string":e+="#define "+i+" "+s+`
19
+ `:"",o=this._compileShader(t,"vertex",s,a),h=this._compileShader(i,"fragment",s,a);return this._createShaderProgram(e,o,h,r,n)}inlineShaderCode(e){return e}createPipelineContext(e){const t=new Oh;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,i,s,r=null){const n=s.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");return s.attachShader(n,t),s.attachShader(n,i),s.linkProgram(n),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_finalizePipelineContext(e){const t=e.context,i=e.vertexShader,s=e.fragmentShader,r=e.program;if(!t.getProgramParameter(r,t.LINK_STATUS)){if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){const o=this._gl.getShaderInfoLog(i);if(o)throw e.vertexCompilationError=o,new Error("VERTEX SHADER "+o)}if(!this._gl.getShaderParameter(s,this._gl.COMPILE_STATUS)){const o=this._gl.getShaderInfoLog(s);if(o)throw e.fragmentCompilationError=o,new Error("FRAGMENT SHADER "+o)}const a=t.getProgramInfoLog(r);if(a)throw e.programLinkError=a,new Error(a)}if(this.validateShaderPrograms&&(t.validateProgram(r),!t.getProgramParameter(r,t.VALIDATE_STATUS))){const o=t.getProgramInfoLog(r);if(o)throw e.programValidationError=o,new Error(o)}t.deleteShader(i),t.deleteShader(s),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,i,s,r,n,a,o,h,c){const u=e;s?u.program=this.createRawShaderProgram(u,t,i,void 0,h):u.program=this.createShaderProgram(u,t,i,o,void 0,h),u.program.__SPECTOR_rebuildProgram=a}_isRenderingStateCompiled(e){const t=e;return this._isDisposed||t._isDisposed?!1:this._gl.getProgramParameter(t.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)?(this._finalizePipelineContext(t),!0):!1}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(!i.isParallelCompiled){t();return}const s=i.onCompiled;s?i.onCompiled=()=>{s(),t()}:i.onCompiled=t}getUniforms(e,t){const i=new Array,s=e;for(let r=0;r<t.length;r++)i.push(this._gl.getUniformLocation(s.program,t[r]));return i}getAttributes(e,t){const i=[],s=e;for(let r=0;r<t.length;r++)try{i.push(this._gl.getAttribLocation(s.program,t[r]))}catch{i.push(-1)}return i}enableEffect(e){e=e!==null&&Li.IsWrapper(e)?e.effect:e,!(!e||e===this._currentEffect)&&(this._stencilStateComposer.stencilMaterial=void 0,e=e,this.bindSamplers(e),this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setInt(e,t){return e?(this._gl.uniform1i(e,t),!0):!1}setInt2(e,t,i){return e?(this._gl.uniform2i(e,t,i),!0):!1}setInt3(e,t,i,s){return e?(this._gl.uniform3i(e,t,i,s),!0):!1}setInt4(e,t,i,s,r){return e?(this._gl.uniform4i(e,t,i,s,r),!0):!1}setIntArray(e,t){return e?(this._gl.uniform1iv(e,t),!0):!1}setIntArray2(e,t){return!e||t.length%2!==0?!1:(this._gl.uniform2iv(e,t),!0)}setIntArray3(e,t){return!e||t.length%3!==0?!1:(this._gl.uniform3iv(e,t),!0)}setIntArray4(e,t){return!e||t.length%4!==0?!1:(this._gl.uniform4iv(e,t),!0)}setUInt(e,t){return e?(this._gl.uniform1ui(e,t),!0):!1}setUInt2(e,t,i){return e?(this._gl.uniform2ui(e,t,i),!0):!1}setUInt3(e,t,i,s){return e?(this._gl.uniform3ui(e,t,i,s),!0):!1}setUInt4(e,t,i,s,r){return e?(this._gl.uniform4ui(e,t,i,s,r),!0):!1}setUIntArray(e,t){return e?(this._gl.uniform1uiv(e,t),!0):!1}setUIntArray2(e,t){return!e||t.length%2!==0?!1:(this._gl.uniform2uiv(e,t),!0)}setUIntArray3(e,t){return!e||t.length%3!==0?!1:(this._gl.uniform3uiv(e,t),!0)}setUIntArray4(e,t){return!e||t.length%4!==0?!1:(this._gl.uniform4uiv(e,t),!0)}setArray(e,t){return!e||t.length<1?!1:(this._gl.uniform1fv(e,t),!0)}setArray2(e,t){return!e||t.length%2!==0?!1:(this._gl.uniform2fv(e,t),!0)}setArray3(e,t){return!e||t.length%3!==0?!1:(this._gl.uniform3fv(e,t),!0)}setArray4(e,t){return!e||t.length%4!==0?!1:(this._gl.uniform4fv(e,t),!0)}setMatrices(e,t){return e?(this._gl.uniformMatrix4fv(e,!1,t),!0):!1}setMatrix3x3(e,t){return e?(this._gl.uniformMatrix3fv(e,!1,t),!0):!1}setMatrix2x2(e,t){return e?(this._gl.uniformMatrix2fv(e,!1,t),!0):!1}setFloat(e,t){return e?(this._gl.uniform1f(e,t),!0):!1}setFloat2(e,t,i){return e?(this._gl.uniform2f(e,t,i),!0):!1}setFloat3(e,t,i,s){return e?(this._gl.uniform3f(e,t,i,s),!0):!1}setFloat4(e,t,i,s,r){return e?(this._gl.uniform4f(e,t,i,s,r),!0):!1}applyStates(){if(this._depthCullingState.apply(this._gl),this._stencilStateComposer.apply(this._gl),this._alphaState.apply(this._gl),this._colorWriteChanged){this._colorWriteChanged=!1;const e=this._colorWrite;this._gl.colorMask(e,e,e,e)}}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}clearInternalTexturesCache(){this._internalTexturesCache.length=0}wipeCaches(e){this.preventCacheWipeBetweenFrames&&!e||(this._currentEffect=null,this._viewportCached.x=0,this._viewportCached.y=0,this._viewportCached.z=0,this._viewportCached.w=0,this._unbindVertexArrayObject(),e&&(this._currentProgram=null,this.resetTextureCache(),this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=this._gl.LEQUAL,this._alphaState.reset(),this._alphaMode=1,this._alphaEquation=0,this._colorWrite=!0,this._colorWriteChanged=!0,this._unpackFlipYCached=null,this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this._mustWipeVertexAttributes=!0,this.unbindAllAttributes()),this._resetVertexBufferBinding(),this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null,this.bindIndexBuffer(null))}_getSamplingParameters(e,t){const i=this._gl;let s=i.NEAREST,r=i.NEAREST;switch(e){case 11:s=i.LINEAR,t?r=i.LINEAR_MIPMAP_NEAREST:r=i.LINEAR;break;case 3:s=i.LINEAR,t?r=i.LINEAR_MIPMAP_LINEAR:r=i.LINEAR;break;case 8:s=i.NEAREST,t?r=i.NEAREST_MIPMAP_LINEAR:r=i.NEAREST;break;case 4:s=i.NEAREST,t?r=i.NEAREST_MIPMAP_NEAREST:r=i.NEAREST;break;case 5:s=i.NEAREST,t?r=i.LINEAR_MIPMAP_NEAREST:r=i.LINEAR;break;case 6:s=i.NEAREST,t?r=i.LINEAR_MIPMAP_LINEAR:r=i.LINEAR;break;case 7:s=i.NEAREST,r=i.LINEAR;break;case 1:s=i.NEAREST,r=i.NEAREST;break;case 9:s=i.LINEAR,t?r=i.NEAREST_MIPMAP_NEAREST:r=i.NEAREST;break;case 10:s=i.LINEAR,t?r=i.NEAREST_MIPMAP_LINEAR:r=i.NEAREST;break;case 2:s=i.LINEAR,r=i.LINEAR;break;case 12:s=i.LINEAR,r=i.NEAREST;break}return{min:r,mag:s}}_createTexture(){const e=this._gl.createTexture();if(!e)throw new Error("Unable to create texture");return e}_createHardwareTexture(){return new ro(this._createTexture(),this._gl)}_createInternalTexture(e,t,i=!0,s=Fe.Unknown){var r;let n=!1,a=0,o=3,h=5,c=!1,u=1,f;t!==void 0&&typeof t=="object"?(n=!!t.generateMipMaps,a=t.type===void 0?0:t.type,o=t.samplingMode===void 0?3:t.samplingMode,h=t.format===void 0?5:t.format,c=t.useSRGBBuffer===void 0?!1:t.useSRGBBuffer,u=(r=t.samples)!==null&&r!==void 0?r:1,f=t.label):n=!!t,c&&(c=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU)),(a===1&&!this._caps.textureFloatLinearFiltering||a===2&&!this._caps.textureHalfFloatLinearFiltering)&&(o=1),a===1&&!this._caps.textureFloat&&(a=0,F.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=this._gl,_=new ht(this,s),p=e.width||e,m=e.height||e,T=e.layers||0,S=this._getSamplingParameters(o,n),x=T!==0?d.TEXTURE_2D_ARRAY:d.TEXTURE_2D,b=this._getRGBABufferInternalSizedFormat(a,h,c),I=this._getInternalFormat(h),R=this._getWebGLTextureType(a);return this._bindTextureDirectly(x,_),T!==0?(_.is2DArray=!0,d.texImage3D(x,0,b,p,m,T,0,I,R,null)):d.texImage2D(x,0,b,p,m,0,I,R,null),d.texParameteri(x,d.TEXTURE_MAG_FILTER,S.mag),d.texParameteri(x,d.TEXTURE_MIN_FILTER,S.min),d.texParameteri(x,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(x,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(x),this._bindTextureDirectly(x,null),_._useSRGBBuffer=c,_.baseWidth=p,_.baseHeight=m,_.width=p,_.height=m,_.depth=T,_.isReady=!0,_.samples=u,_.generateMipMaps=n,_.samplingMode=o,_.type=a,_.format=h,_.label=f,this._internalTexturesCache.push(_),_}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,s,r=3,n=null,a=null,o,h,c=null,u=null,f=null,d=null,_,p,m){e=e||"";const T=e.substr(0,5)==="data:",S=e.substr(0,5)==="blob:",x=T&&e.indexOf(";base64,")!==-1,b=u||new ht(this,Fe.Url);b!==u&&(b.label=e.substring(0,60));const I=e;this._transformTextureUrl&&!x&&!u&&!c&&(e=this._transformTextureUrl(e)),I!==e&&(b._originalUrl=I);const R=e.lastIndexOf(".");let C=d||(R>-1?e.substring(R).toLowerCase():""),y=null;C.indexOf("?")>-1&&(C=C.split("?")[0]);for(const Q of re._TextureLoaders)if(Q.canLoad(C,_)){y=Q;break}s&&s.addPendingData(b),b.url=e,b.generateMipMaps=!t,b.samplingMode=r,b.invertY=i,b._useSRGBBuffer=this._getUseSRGBBuffer(!!m,t),this._doNotHandleContextLost||(b._buffer=c);let G=null;n&&!u&&(G=b.onLoadedObservable.add(n)),u||this._internalTexturesCache.push(b);const te=(Q,Te)=>{s&&s.removePendingData(b),e===I?(G&&b.onLoadedObservable.remove(G),Ee.UseFallbackTexture&&this._createTextureBase(Ee.FallbackTexture,t,b.invertY,s,r,null,a,o,h,c,b),Q=(Q||"Unknown error")+(Ee.UseFallbackTexture?" - Fallback texture was used":""),b.onErrorObservable.notifyObservers({message:Q,exception:Te}),a&&a(Q,Te)):(F.Warn(`Failed to load ${e}, falling back to ${I}`),this._createTextureBase(I,t,b.invertY,s,r,n,a,o,h,c,b,f,d,_,p,m))};if(y){const Q=Te=>{y.loadData(Te,b,(he,ve,le,be,ye,Ye)=>{Ye?te("TextureLoader failed to load data"):o(b,C,s,{width:he,height:ve},b.invertY,!le,be,()=>(ye(),!1),r)},p)};c?c instanceof ArrayBuffer?Q(new Uint8Array(c)):ArrayBuffer.isView(c)?Q(c):a&&a("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,Te=>Q(new Uint8Array(Te)),void 0,s?s.offlineProvider:void 0,!0,(Te,he)=>{te("Unable to load "+(Te&&Te.responseURL,he))})}else{const Q=Te=>{S&&!this._doNotHandleContextLost&&(b._buffer=Te),o(b,C,s,Te,b.invertY,t,!1,h,r)};!T||x?c&&(typeof c.decoding=="string"||c.close)?Q(c):re._FileToolsLoadImage(e,Q,te,s?s.offlineProvider:null,_,b.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):typeof c=="string"||c instanceof ArrayBuffer||ArrayBuffer.isView(c)||c instanceof Blob?re._FileToolsLoadImage(c,Q,te,s?s.offlineProvider:null,_,b.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):c&&Q(c)}return b}createTexture(e,t,i,s,r=3,n=null,a=null,o=null,h=null,c=null,u=null,f,d,_,p){return this._createTextureBase(e,t,i,s,r,n,a,this._prepareWebGLTexture.bind(this),(m,T,S,x,b,I)=>{const R=this._gl,C=S.width===m&&S.height===T,y=c?this._getInternalFormat(c,b._useSRGBBuffer):x===".jpg"&&!b._useSRGBBuffer?R.RGB:b._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:R.RGBA;let w=c?this._getInternalFormat(c):x===".jpg"&&!b._useSRGBBuffer?R.RGB:R.RGBA;if(b._useSRGBBuffer&&this.webGLVersion===1&&(w=y),C)return R.texImage2D(R.TEXTURE_2D,0,y,w,R.UNSIGNED_BYTE,S),!1;const G=this._caps.maxTextureSize;if(S.width>G||S.height>G||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=m,this._workingCanvas.height=T,this._workingContext.drawImage(S,0,0,S.width,S.height,0,0,m,T),R.texImage2D(R.TEXTURE_2D,0,y,w,R.UNSIGNED_BYTE,this._workingCanvas),b.width=m,b.height=T),!1;{const te=new ht(this,Fe.Temp);this._bindTextureDirectly(R.TEXTURE_2D,te,!0),R.texImage2D(R.TEXTURE_2D,0,y,w,R.UNSIGNED_BYTE,S),this._rescaleTexture(te,b,s,y,()=>{this._releaseTexture(te),this._bindTextureDirectly(R.TEXTURE_2D,b,!0),I()})}return!0},o,h,c,u,f,d,p)}static _FileToolsLoadImage(e,t,i,s,r,n){throw fe("FileTools")}_rescaleTexture(e,t,i,s,r){}createRawTexture(e,t,i,s,r,n,a,o=null,h=0,c=0,u=!1){throw fe("Engine.RawTexture")}createRawCubeTexture(e,t,i,s,r,n,a,o=null){throw fe("Engine.RawTexture")}createRawTexture3D(e,t,i,s,r,n,a,o,h=null,c=0){throw fe("Engine.RawTexture")}createRawTexture2DArray(e,t,i,s,r,n,a,o,h=null,c=0){throw fe("Engine.RawTexture")}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.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 r=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&s!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_setupDepthStencilTexture(e,t,i,s,r,n=1){const a=t.width||t,o=t.height||t,h=t.layers||0;e.baseWidth=a,e.baseHeight=o,e.width=a,e.height=o,e.is2DArray=h>0,e.depth=h,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=0,e._comparisonFunction=r;const c=this._gl,u=this._getTextureTarget(e),f=this._getSamplingParameters(e.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&&(r===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,r),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,a=0){const o=this._gl;let h=o.TEXTURE_2D;if(e.isCube&&(h=o.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=o.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1;break}this._gl.compressedTexImage2D(h,a,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const a=this._gl,o=this._getWebGLTextureType(e.type),h=this._getInternalFormat(e.format),c=r===void 0?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let u=a.TEXTURE_2D;e.isCube&&(u=a.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),_=n?e.width:Math.pow(2,Math.max(f-s,0)),p=n?e.height:Math.pow(2,Math.max(d-s,0));a.texImage2D(u,s,c,_,p,0,h,o,t)}updateTextureData(e,t,i,s,r,n,a=0,o=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,_=c.TEXTURE_2D;e.isCube&&(_=c.TEXTURE_CUBE_MAP_POSITIVE_X+a,d=c.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),c.texSubImage2D(_,o,i,s,r,n,f,u,t),h&&this._gl.generateMipmap(_),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,r){const n=this._gl;if(!n)return;const a=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,a.min),!i&&!s&&n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,a,o,h=3){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?re.GetExponentOfTwo(s.width,c):s.width),f=Math.min(c,this.needPOTTextures?re.GetExponentOfTwo(s.height,c):s.height),d=this._gl;if(d){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(d.TEXTURE_2D,e,!0),this._unpackFlipY(r===void 0?!0:!!r),e.baseWidth=s.width,e.baseHeight=s.height,e.width=u,e.height=f,e.isReady=!0,!o(u,f,s,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,n,a,h)})&&this._prepareWebGLTextureContinuation(e,i,n,a,h)}}_setupFramebufferDepthAttachments(e,t,i,s,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(i,s,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let a=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(a=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,a,a,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,a=!0){const h=this._gl.createRenderbuffer();return this._updateRenderBuffer(h,e,t,i,s,r,n,a)}_updateRenderBuffer(e,t,i,s,r,n,a,o=!0){const h=this._gl;return h.bindRenderbuffer(h.RENDERBUFFER,e),s>1&&h.renderbufferStorageMultisample?h.renderbufferStorageMultisample(h.RENDERBUFFER,s,n,t,i):h.renderbufferStorage(h.RENDERBUFFER,r,t,i),h.framebufferRenderbuffer(h.FRAMEBUFFER,a,h.RENDERBUFFER,e),o&&h.bindRenderbuffer(h.RENDERBUFFER,null),e}_releaseTexture(e){var t;this._deleteTexture((t=e._hardwareTexture)===null||t===void 0?void 0:t.underlyingResource),this.unbindAllTextures();const i=this._internalTexturesCache.indexOf(e);i!==-1&&this._internalTexturesCache.splice(i,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){const t=this._renderTargetWrapperCache.indexOf(e);t!==-1&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let s=0;s<i.length;s++){const r=e.getUniform(i[s]);r&&(this._boundUniforms[s]=r)}this._currentEffect=null}_activateCurrentTexture(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)}_bindTextureDirectly(e,t,i=!1,s=!1){var r,n;let a=!1;const o=t&&t._associatedChannel>-1;if(i&&o&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw console.error(e,t),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,(n=(r=t==null?void 0:t._hardwareTexture)===null||r===void 0?void 0:r.underlyingResource)!==null&&n!==void 0?n:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(a=!0,this._activateCurrentTexture());return o&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),a}_bindTexture(e,t,i){if(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;e<this._maxSimultaneousTextures;e++)this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,s){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,r=""){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 n;s?n=t.depthStencilTexture:t.isReady()?n=t.getInternalTexture():t.isCube?n=this.emptyCubeTexture:t.is3D?n=this.emptyTexture3D:t.is2DArray?n=this.emptyTexture2DArray:n=this.emptyTexture,!i&&n&&(n._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),a=!1),this._activeChannel=e;const o=this._getTextureTarget(n);if(a&&this._bindTextureDirectly(o,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const h=t.coordinatesMode!==3&&t.coordinatesMode!==5?1:0;t.wrapU=h,t.wrapV=h}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(o,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(!(e===void 0||!t)){(!this._textureUnits||this._textureUnits.length!==i.length)&&(this._textureUnits=new Int32Array(i.length));for(let r=0;r<i.length;r++){const n=i[r].getInternalTexture();n?(this._textureUnits[r]=e+r,n._associatedChannel=e+r):this._textureUnits[r]=-1}this._gl.uniform1iv(t,this._textureUnits);for(let r=0;r<i.length;r++)this._setTexture(this._textureUnits[r],i[r],!0)}}_setAnisotropicLevel(e,t,i){const s=this._caps.textureAnisotropicFilterExtension;t.samplingMode!==11&&t.samplingMode!==3&&t.samplingMode!==2&&(i=1),s&&t._cachedAnisotropicFilteringLevel!==i&&(this._setTextureParameterFloat(e,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(i,this._caps.maxAnisotropy),t),t._cachedAnisotropicFilteringLevel=i)}_setTextureParameterFloat(e,t,i,s){this._bindTextureDirectly(e,s,!0,!0),this._gl.texParameterf(e,t,i)}_setTextureParameterInteger(e,t,i,s){s&&this._bindTextureDirectly(e,s,!0,!0),this._gl.texParameteri(e,t,i)}unbindAllAttributes(){if(this._mustWipeVertexAttributes){this._mustWipeVertexAttributes=!1;for(let e=0;e<this._caps.maxVertexAttribs;e++)this.disableAttributeByIndex(e);return}for(let e=0,t=this._vertexAttribArraysEnabled.length;e<t;e++)e>=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e;this._isDisposed=!0,this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),(e=this.releaseComputeEffects)===null||e===void 0||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},Mt()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),window.removeEventListener("resize",this._checkForMobile)),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,nt.ResetCache();for(const t of this._activeRequests)t.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const 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 r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&n===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 a=t.RGBA,o=t.UNSIGNED_BYTE,h=new Uint8Array(4);t.readPixels(0,0,1,1,a,o,h),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(r),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}_getRGBAMultiSampleBufferFormat(e,t=5){switch(e){case 1:switch(t){case 6:return this._gl.R32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;default:return this._gl.RGBA16F}}return this._gl.RGBA8}_loadFile(e,t,i,s,r,n){const a=re._FileToolsLoadFile(e,t,i,s,r,n);return this._activeRequests.push(a),a.onCompleteObservable.add(o=>{this._activeRequests.splice(this._activeRequests.indexOf(o),1)}),a}static _FileToolsLoadFile(e,t,i,s,r,n){throw fe("FileTools")}readPixels(e,t,i,s,r=!0,n=!0){const a=r?4:3,o=r?this._gl.RGBA:this._gl.RGB,h=new Uint8Array(s*i*a);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,o,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=this._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=this._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}static CeilingPOT(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}static FloorPOT(e){return e=e|e>>1,e=e|e>>2,e=e|e>>4,e=e|e>>8,e=e|e>>16,e-(e>>1)}static NearestPOT(e){const t=re.CeilingPOT(e),i=re.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let s;switch(i){case 1:s=re.FloorPOT(e);break;case 2:s=re.NearestPOT(e);break;case 3:default:s=re.CeilingPOT(e);break}return Math.min(s,t)}static QueueNewFrame(e,t){if(Mt()){const{requestPostAnimationFrame:i,requestAnimationFrame:s}=t||window;if(typeof i=="function")return i(e);if(typeof s=="function")return s(e)}else if(typeof requestAnimationFrame=="function")return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:_r()?document:null}}re.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],re._TextureLoaders=[],re.CollisionsEpsilon=.001,re._IsSupported=null,re._HasMajorPerformanceCaveat=null;class $r{static SetImmediate(e){Mt()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}const no=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class Tr extends xi{constructor(e,t){super(e,is.LoadFileError),this.name="LoadFileError",ks._setPrototypeOf(this,Tr.prototype),t instanceof wt?this.request=t:this.file=t}}class Jr extends xi{constructor(e,t){super(e,is.RequestFileError),this.request=t,this.name="RequestFileError",ks._setPrototypeOf(this,Jr.prototype)}}class yn extends xi{constructor(e,t){super(e,is.ReadFileError),this.file=t,this.name="ReadFileError",ks._setPrototypeOf(this,yn.prototype)}}const bt={DefaultRetryStrategy:fh.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:l=>l},ao=l=>(l=l.replace(/#/gm,"%23"),l),Mn=(l,e)=>{if(!(l&&l.indexOf("data:")===0)&&bt.CorsBehavior)if(typeof bt.CorsBehavior=="string"||bt.CorsBehavior instanceof String)e.crossOrigin=bt.CorsBehavior;else{const t=bt.CorsBehavior(l);t&&(e.crossOrigin=t)}},Ar=(l,e,t,i,s="",r)=>{var n;let a,o=!1;l instanceof ArrayBuffer||ArrayBuffer.isView(l)?typeof Blob<"u"&&typeof URL<"u"?(a=URL.createObjectURL(new Blob([l],{type:s})),o=!0):a=`data:${s};base64,`+eo(l):l instanceof Blob?(a=URL.createObjectURL(l),o=!0):(a=ao(l),a=bt.PreprocessUrl(l));const h=Ee.LastCreatedEngine,c=R=>{if(t){const C=a||l.toString();t(`Error while trying to load image: ${C.indexOf("http")===0||C.length<=128?C:C.slice(0,128)+"..."}`,R)}};if(typeof Image>"u"||(n=h==null?void 0:h._features.forceBitmapOverHTMLImageElement)!==null&&n!==void 0&&n)return rs(a,R=>{h.createImageBitmap(new Blob([R],{type:s}),Object.assign({premultiplyAlpha:"none"},r)).then(C=>{e(C),o&&URL.revokeObjectURL(a)}).catch(C=>{t&&t("Error while trying to load image: "+l,C)})},void 0,i||void 0,!0,(R,C)=>{c(C)}),null;const u=new Image;Mn(a,u);const f=[],d=()=>{f.forEach(R=>{R.target.addEventListener(R.name,R.handler)})},_=()=>{f.forEach(R=>{R.target.removeEventListener(R.name,R.handler)}),f.length=0},p=()=>{_(),e(u),o&&u.src&&URL.revokeObjectURL(u.src)},m=R=>{_(),c(R),o&&u.src&&URL.revokeObjectURL(u.src)},T=R=>{if(R.blockedURI!==u.src)return;_();const C=new Error(`CSP violation of policy ${R.effectiveDirective} ${R.blockedURI}. Current policy is ${R.originalPolicy}`);Ee.UseFallbackTexture=!1,c(C),o&&u.src&&URL.revokeObjectURL(u.src),u.src=""};f.push({target:u,name:"load",handler:p}),f.push({target:u,name:"error",handler:m}),f.push({target:document,name:"securitypolicyviolation",handler:T}),d();const S=a.substring(0,5)==="blob:",x=a.substring(0,5)==="data:",b=()=>{S||x?u.src=a:rs(a,(R,C,y)=>{const w=!s&&y?y:s,G=new Blob([R],{type:w}),te=URL.createObjectURL(G);o=!0,u.src=te},void 0,i||void 0,!0,(R,C)=>{c(C)})},I=()=>{i&&i.loadImage(a,u)};if(!S&&!x&&i&&i.enableTexturesOffline)i.open(I,b);else{if(a.indexOf("file:")!==-1){const R=decodeURIComponent(a.substring(5).toLowerCase());if(mr.FilesToLoad[R]&&typeof URL<"u"){try{let C;try{C=URL.createObjectURL(mr.FilesToLoad[R])}catch{C=URL.createObjectURL(mr.FilesToLoad[R])}u.src=C,o=!0}catch{u.src=""}return u}}b()}return u},vr=(l,e,t,i,s)=>{const r=new FileReader,n={onCompleteObservable:new B,abort:()=>r.abort()};return r.onloadend=()=>n.onCompleteObservable.notifyObservers(n),s&&(r.onerror=()=>{s(new yn(`Unable to read ${l.name}`,l))}),r.onload=a=>{e(a.target.result)},t&&(r.onprogress=t),i?r.readAsArrayBuffer(l):r.readAsText(l),n},rs=(l,e,t,i,s,r,n)=>{if(l.name)return vr(l,e,t,s,r?c=>{r(void 0,c)}:void 0);const a=l;if(a.indexOf("file:")!==-1){let c=decodeURIComponent(a.substring(5).toLowerCase());c.indexOf("./")===0&&(c=c.substring(2));const u=mr.FilesToLoad[c];if(u)return vr(u,e,t,s,r?f=>r(void 0,new Tr(f.message,f.file)):void 0)}const{match:o,type:h}=Nh(a);if(o){const c={onCompleteObservable:new B,abort:()=>()=>{}};try{const u=s?Sr(a):lo(a);e(u,void 0,h)}catch(u){r?r(void 0,u):F.Error(u.message||"Failed to parse the Data URL")}return $r.SetImmediate(()=>{c.onCompleteObservable.notifyObservers(c)}),c}return Pn(a,(c,u)=>{e(c,u==null?void 0:u.responseURL,u==null?void 0:u.getResponseHeader("content-type"))},t,i,s,r?c=>{r(c.request,new Tr(c.message,c.request))}:void 0,n)},Pn=(l,e,t,i,s,r,n)=>{l=ao(l),l=bt.PreprocessUrl(l);const a=bt.BaseUrl+l;let o=!1;const h={onCompleteObservable:new B,abort:()=>o=!0},c=()=>{let u=new wt,f=null,d;const _=()=>{u&&(t&&u.removeEventListener("progress",t),d&&u.removeEventListener("readystatechange",d),u.removeEventListener("loadend",p))};let p=()=>{_(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),t=void 0,d=null,p=null,r=void 0,n=void 0,e=void 0};h.abort=()=>{o=!0,p&&p(),u&&u.readyState!==(XMLHttpRequest.DONE||4)&&u.abort(),f!==null&&(clearTimeout(f),f=null),u=null};const m=S=>{const x=S.message||"Unknown error";r&&u?r(new Jr(x,u)):F.Error(x)},T=S=>{if(u){if(u.open("GET",a),n)try{n(u)}catch(x){m(x);return}s&&(u.responseType="arraybuffer"),t&&u.addEventListener("progress",t),p&&u.addEventListener("loadend",p),d=()=>{if(!(o||!u)&&u.readyState===(XMLHttpRequest.DONE||4)){if(d&&u.removeEventListener("readystatechange",d),u.status>=200&&u.status<300||u.status===0&&(!Mt()||oo())){try{e&&e(s?u.response:u.responseText,u)}catch(I){m(I)}return}const x=bt.DefaultRetryStrategy;if(x){const I=x(a,u,S);if(I!==-1){_(),u=new wt,f=setTimeout(()=>T(S+1),I);return}}const b=new Jr("Error status: "+u.status+" "+u.statusText+" - Unable to load "+a,u);r&&r(b)}},u.addEventListener("readystatechange",d),u.send()}};T(0)};if(i&&i.enableSceneOffline){const u=d=>{d&&d.status>400?r&&r(d):c()},f=()=>{i&&i.loadFile(bt.BaseUrl+l,d=>{!o&&e&&e(d),h.onCompleteObservable.notifyObservers(h)},t?d=>{!o&&t&&t(d)}:void 0,u,s)};i.open(f,u)}else c();return h},oo=()=>typeof location<"u"&&location.protocol==="file:",en=l=>no.test(l),Nh=l=>{const e=no.exec(l);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace("base64,","")}};function Sr(l){return _h(l.split(",")[1])}const lo=l=>to(l.split(",")[1]);(()=>{re._FileToolsLoadImage=Ar,re._FileToolsLoadFile=rs,Oi._FileToolsLoadFile=rs})();let Rr;((l,e,t,i,s,r,n,a,o,h)=>{Rr={DecodeBase64UrlToBinary:l,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:s,LoadFile:r,LoadImage:n,ReadFile:a,RequestFile:o,SetCorsBehavior:h},Object.defineProperty(Rr,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(c){t.DefaultRetryStrategy=c}}),Object.defineProperty(Rr,"BaseUrl",{get:function(){return t.BaseUrl},set:function(c){t.BaseUrl=c}}),Object.defineProperty(Rr,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(c){t.PreprocessUrl=c}}),Object.defineProperty(Rr,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(c){t.CorsBehavior=c}})})(Sr,lo,bt,en,oo,rs,Ar,vr,Pn,Mn);class xr{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=Ri(e);if(t)return t;F.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let r=0,n=i.length;r<n;r++)s=s[i[r]];return typeof s!="function"?null:s}}xr.RegisteredExternalClasses={};function On(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,l=>{const e=Math.random()*16|0;return(l==="x"?e:e&3|8).toString(16)})}class k{static get BaseUrl(){return bt.BaseUrl}static set BaseUrl(e){bt.BaseUrl=e}static get DefaultRetryStrategy(){return bt.DefaultRetryStrategy}static set DefaultRetryStrategy(e){bt.DefaultRetryStrategy=e}static get CorsBehavior(){return bt.CorsBehavior}static set CorsBehavior(e){bt.CorsBehavior=e}static get UseFallbackTexture(){return Ee.UseFallbackTexture}static set UseFallbackTexture(e){Ee.UseFallbackTexture=e}static get RegisteredExternalClasses(){return xr.RegisteredExternalClasses}static set RegisteredExternalClasses(e){xr.RegisteredExternalClasses=e}static get fallbackTexture(){return Ee.FallbackTexture}static set fallbackTexture(e){Ee.FallbackTexture=e}static FetchToRef(e,t,i,s,r,n){const a=Math.abs(e)*i%i|0,o=Math.abs(t)*s%s|0,h=(a+o*i)*4;n.r=r[h]/255,n.g=r[h+1]/255,n.b=r[h+2]/255,n.a=r[h+3]/255}static Mix(e,t,i){return e*(1-i)+t*i}static Instantiate(e){return xr.Instantiate(e)}static SetImmediate(e){$r.SetImmediate(e)}static IsExponentOfTwo(e){let t=1;do t*=2;while(t<e);return t===e}static FloatRound(e){return Math.fround?Math.fround(e):(k._TmpFloatArray[0]=e,k._TmpFloatArray[0])}static GetFilename(e){const t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)}static GetFolderPath(e,t=!1){const i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)}static ToDegrees(e){return e*180/Math.PI}static ToRadians(e){return e*Math.PI/180}static SmoothAngleChange(e,t,i=.9){const s=this.ToRadians(e),r=this.ToRadians(t);return this.ToDegrees(Math.atan2((1-i)*Math.sin(r)+i*Math.sin(s),(1-i)*Math.cos(r)+i*Math.cos(s)))}static MakeArray(e,t){return t!==!0&&(e===void 0||e==null)?null:Array.isArray(e)?e:[e]}static GetPointerPrefix(e){let t="pointer";return Mt()&&!window.PointerEvent&&(t="mouse"),e._badDesktopOS&&!e._badOS&&!(document&&"ontouchend"in document)&&(t="mouse"),t}static SetCorsBehavior(e,t){Mn(e,t)}static SetReferrerPolicyBehavior(e,t){t.referrerPolicy=e}static CleanUrl(e){return e=e.replace(/#/gm,"%23"),e}static get PreprocessUrl(){return bt.PreprocessUrl}static set PreprocessUrl(e){bt.PreprocessUrl=e}static LoadImage(e,t,i,s,r,n){return Ar(e,t,i,s,r,n)}static LoadFile(e,t,i,s,r,n){return rs(e,t,i,s,r,n)}static LoadFileAsync(e,t=!0){return new Promise((i,s)=>{rs(e,r=>{i(r)},void 0,void 0,t,(r,n)=>{s(n)})})}static LoadScript(e,t,i,s){if(typeof importScripts=="function"){try{importScripts(e),t()}catch(a){i==null||i(`Unable to load script '${e}' in worker`,a)}return}else if(!Mt()){i==null||i(`Cannot load script '${e}' outside of a window or a worker`);return}const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),s&&(n.id=s),n.onload=()=>{t&&t()},n.onerror=a=>{i&&i(`Unable to load script '${e}'`,a)},r.appendChild(n)}static LoadScriptAsync(e){return new Promise((t,i)=>{this.LoadScript(e,()=>{t()},(s,r)=>{i(r||new Error(s))})})}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new B,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=n=>{t(n.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,s,r){return vr(e,t,i,s,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,s){pr.DeepCopy(e,t,i,s)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){const s=t[i];e.addEventListener(s.name,s.handler,!1);try{window.parent&&window.parent.addEventListener(s.name,s.handler,!1)}catch{}}}static UnregisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){const s=t[i];e.removeEventListener(s.name,s.handler);try{e.parent&&e.parent.removeEventListener(s.name,s.handler)}catch{}}}static async DumpFramebuffer(e,t,i,s,r="image/png",n,a){throw fe("DumpTools")}static DumpData(e,t,i,s,r="image/png",n,a=!1,o=!1,h){throw fe("DumpTools")}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,a=!1,o){throw fe("DumpTools")}static _IsOffScreenCanvas(e){return e.convertToBlob!==void 0}static ToBlob(e,t,i="image/png",s){!k._IsOffScreenCanvas(e)&&!e.toBlob&&(e.toBlob=function(r,n,a){setTimeout(()=>{const o=atob(this.toDataURL(n,a).split(",")[1]),h=o.length,c=new Uint8Array(h);for(let u=0;u<h;u++)c[u]=o.charCodeAt(u);r(new Blob([c]))})}),k._IsOffScreenCanvas(e)?e.convertToBlob({type:i,quality:s}).then(r=>t(r)):e.toBlob(function(r){t(r)},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"}k.Download(e,t)}else if(e&&typeof URL<"u"){const i=URL.createObjectURL(e),s=window.open("");if(!s)return;const r=s.document.createElement("img");r.onload=function(){URL.revokeObjectURL(i)},r.src=i,s.document.body.appendChild(r)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,r){if(typeof s=="string"||!t)this.ToBlob(e,function(n){n&&k.DownloadBlob(n,s),t&&t("")},i,r);else if(t){if(k._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:r}).then(a=>{const o=new FileReader;o.readAsDataURL(a),o.onloadend=()=>{const h=o.result;t(h)}});return}const n=e.toDataURL(i,r);t(n)}}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,r="image/png",n=!1,a){throw fe("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw fe("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,a=!1,o,h=!1,c=!1,u=!0,f){throw fe("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,a,o=!1,h=!1,c=!0,u){throw fe("ScreenshotTools")}static RandomId(){return On()}static IsBase64(e){return en(e)}static DecodeBase64(e){return Sr(e)}static get errorsCount(){return F.errorsCount}static Log(e){F.Log(e)}static Warn(e){F.Warn(e)}static Error(e){F.Error(e)}static get LogCache(){return F.LogCache}static ClearLogCache(){F.ClearLogCache()}static set LogLevels(e){F.LogLevels=e}static set PerformanceLogLevel(e){if((e&k.PerformanceUserMarkLogLevel)===k.PerformanceUserMarkLogLevel){k.StartPerformanceCounter=k._StartUserMark,k.EndPerformanceCounter=k._EndUserMark;return}if((e&k.PerformanceConsoleLogLevel)===k.PerformanceConsoleLogLevel){k.StartPerformanceCounter=k._StartPerformanceConsole,k.EndPerformanceCounter=k._EndPerformanceConsole;return}k.StartPerformanceCounter=k._StartPerformanceCounterDisabled,k.EndPerformanceCounter=k._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!k._Performance){if(!Mt())return;k._Performance=window.performance}!t||!k._Performance.mark||k._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!k._Performance.mark||(k._Performance.mark(e+"-End"),k._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(k._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(k._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return ii.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 r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,s=r.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 qr()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}}k.UseCustomRequestHeaders=!1,k.CustomRequestHeaders=wt.CustomRequestHeaders,k._TmpFloatArray=new Float32Array(1),k.GetDOMTextContent=$a,k.GetAbsoluteUrl=typeof document=="object"?l=>{const e=document.createElement("a");return e.href=l,e.href}:typeof URL=="function"&&typeof location=="object"?l=>new URL(l,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},k.NoneLogLevel=F.NoneLogLevel,k.MessageLogLevel=F.MessageLogLevel,k.WarningLogLevel=F.WarningLogLevel,k.ErrorLogLevel=F.ErrorLogLevel,k.AllLogLevel=F.AllLogLevel,k.IsWindowObjectExist=Mt,k.PerformanceNoneLogLevel=0,k.PerformanceUserMarkLogLevel=1,k.PerformanceConsoleLogLevel=2,k.StartPerformanceCounter=k._StartPerformanceCounterDisabled,k.EndPerformanceCounter=k._EndPerformanceCounterDisabled;class tn{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())}breakLoop(){this._done=!0,this._successCallback()}static Run(e,t,i,s=0){const r=new tn(e,t,i,s);return r.executeNext(),r}static SyncAsyncForLoop(e,t,i,s,r,n=0){return tn.Run(Math.ceil(e/t),a=>{r&&r()?a.breakLoop():setTimeout(()=>{for(let o=0;o<t;++o){const h=a.index*t+o;if(h>=e)break;if(i(h),r&&r()){a.breakLoop();break}}a.executeNext()},n)},s)}}Ee.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";function Dn(l,e,t){try{const i=l.next();i.done?e(i):i.value?i.value.then(()=>{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function Fh(l=25){let e;return(t,i,s)=>{const r=performance.now();e===void 0||r-e>l?(e=r,setTimeout(()=>{Dn(t,i,s)},0)):Dn(t,i,s)}}function ho(l,e,t,i,s){const r=()=>{let n;const a=o=>{o.done?t(o.value):n===void 0?n=!0:r()};do n=void 0,!s||!s.aborted?e(l,a,i):i(new Error("Aborted")),n===void 0&&(n=!1);while(n)};r()}function Ln(l,e){let t;return ho(l,Dn,i=>t=i,i=>{throw i},e),t}function wh(l,e,t){return new Promise((i,s)=>{ho(l,e,i,s,t)})}function Bh(l,e){return(...t)=>Ln(l(...t),e)}class vt{constructor(e){this.length=0,this.data=new Array(e),this._id=vt._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;t<this.length;t++)e(this.data[t])}sort(e){this.data.sort(e)}reset(){this.length=0}dispose(){this.reset(),this.data&&(this.data.length=0)}concat(e){if(e.length!==0){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}}indexOf(e){const t=this.data.indexOf(e);return t>=this.length?-1:t}contains(e){return this.indexOf(e)!==-1}}vt._GlobalId=0;class gs 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;t<e.length;t++){const i=(e.data||e)[t];this.pushNoDuplicate(i)}}}}class Cr{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new Cr(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 Cr(this.x,this.y,this.width,this.height)}}class Zt{constructor(e,t,i,s){this.normal=new E(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Zt(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=Zt._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,a=this.d,o=s*i[0]+r*i[1]+n*i[2]+a*i[3],h=s*i[4]+r*i[5]+n*i[6]+a*i[7],c=s*i[8]+r*i[9]+n*i[10]+a*i[11],u=s*i[12]+r*i[13]+n*i[14]+a*i[15];return new Zt(o,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,r=t.y-e.y,n=t.z-e.z,a=i.x-e.x,o=i.y-e.y,h=i.z-e.z,c=r*h-n*o,u=n*a-s*h,f=s*o-r*a,d=Math.sqrt(c*c+u*u+f*f);let _;return d!==0?_=1/d:_=0,this.normal.x=c*_,this.normal.y=u*_,this.normal.z=f*_,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return E.Dot(this.normal,e)<=t}signedDistanceTo(e){return E.Dot(e,this.normal)+this.d}static FromArray(e){return new Zt(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new Zt(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new Zt(0,0,0,0);return t.normalize(),i.normal=t,i.d=-(t.x*e.x+t.y*e.y+t.z*e.z),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return E.Dot(i,t)+s}}Zt._TmpMatrix=M.Identity();class li{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new Zt(0,0,0,0));return li.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){li.GetNearPlaneToRef(e,t[0]),li.GetFarPlaneToRef(e,t[1]),li.GetLeftPlaneToRef(e,t[2]),li.GetRightPlaneToRef(e,t[3]),li.GetTopPlaneToRef(e,t[4]),li.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}class ie extends lt{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var e,t,i,s;let r=0,n=0;if(this.mode===ie.PERSPECTIVE_CAMERA)this.fovMode===ie.FOVMODE_VERTICAL_FIXED?(n=this.minZ*2*Math.tan(this.fov/2),r=this.getEngine().getAspectRatio(this)*n):(r=this.minZ*2*Math.tan(this.fov/2),n=r/this.getEngine().getAspectRatio(this));else{const a=this.getEngine().getRenderWidth()/2,o=this.getEngine().getRenderHeight()/2;r=((e=this.orthoRight)!==null&&e!==void 0?e:a)-((t=this.orthoLeft)!==null&&t!==void 0?t:-a),n=((i=this.orthoTop)!==null&&i!==void 0?i:o)-((s=this.orthoBottom)!==null&&s!==void 0?s:-o)}return r*n}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}constructor(e,t,i,s=!0){super(e,i),this._position=E.Zero(),this._upVector=E.Up(),this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=ie.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Cr(0,0,1,1),this.layerMask=268435455,this.fovMode=ie.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=ie.RIG_MODE_NONE,this.customRenderTargets=new Array,this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new B,this.onProjectionMatrixChangedObservable=new B,this.onAfterCheckInputsObservable=new B,this.onRestoreStateObservable=new B,this.isRigCamera=!1,this._rigCameras=new Array,this._webvrViewMatrix=M.Identity(),this._skipRendering=!1,this._projectionMatrix=new M,this._postProcesses=new Array,this._activeMeshes=new vt(256),this._globalPosition=E.Zero(),this._computedViewMatrix=M.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=M.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=K.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_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<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}applyVerticalCorrection(){const e=this.absoluteRotation.toEulerAngles();this.projectionPlaneTilt=this._scene.useRightHandedSystem?-e.x:e.x}get globalPosition(){return this._globalPosition}getActiveMeshes(){return this._activeMeshes}isActiveMesh(e){return this._activeMeshes.indexOf(e)!==-1}isReady(e=!1){if(e){for(const t of this._postProcesses)if(t&&!t.isReady())return!1}return super.isReady(e)}_initCache(){super._initCache(),this._cache.position=new E(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new E(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0}_updateCache(e){e||super._updateCache(),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)}_isSynchronized(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()}_isSynchronizedViewMatrix(){return super._isSynchronized()?this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent():!1}_isSynchronizedProjectionMatrix(){let e=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ;if(!e)return!1;const t=this.getEngine();return this.mode===ie.PERSPECTIVE_CAMERA?e=this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===t.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:e=this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===t.getRenderWidth()&&this._cache.renderHeight===t.getRenderHeight(),e}attachControl(e,t){}detachControl(e){}update(){this._checkInputs(),this.cameraRigMode!==ie.RIG_MODE_NONE&&this._updateRigCameras(),this.getViewMatrix(),this.getProjectionMatrix()}_checkInputs(){this.onAfterCheckInputsObservable.notifyObservers(this)}get rigCameras(){return this._rigCameras}get rigPostProcess(){return this._rigPostProcess}_getFirstPostProcess(){for(let e=0;e<this._postProcesses.length;e++)if(this._postProcesses[e]!==null)return this._postProcesses[e];return null}_cascadePostProcessesToRigCams(){const e=this._getFirstPostProcess();e&&e.markTextureDirty();for(let t=0,i=this._rigCameras.length;t<i;t++){const s=this._rigCameras[t],r=s._rigPostProcess;r?(r.getEffectName()==="pass"&&(s.isIntermediate=this._postProcesses.length===0),s._postProcesses=this._postProcesses.slice(0).concat(r),r.markTextureDirty()):s._postProcesses=this._postProcesses.slice(0)}}attachPostProcess(e,t=null){return!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(F.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 M.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(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 t,i,s,r,n,a,o,h;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 c=this.getEngine(),u=this.getScene(),f=c.useReverseDepthBuffer;if(this.mode===ie.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=c.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let d;u.useRightHandedSystem?d=M.PerspectiveFovRHToRef:d=M.PerspectiveFovLHToRef,d(this.fov,c.getAspectRatio(this),f?this.maxZ:this.minZ,f?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===ie.FOVMODE_VERTICAL_FIXED,c.isNDCHalfZRange,this.projectionPlaneTilt,f)}else{const d=c.getRenderWidth()/2,_=c.getRenderHeight()/2;u.useRightHandedSystem?M.OrthoOffCenterRHToRef((t=this.orthoLeft)!==null&&t!==void 0?t:-d,(i=this.orthoRight)!==null&&i!==void 0?i:d,(s=this.orthoBottom)!==null&&s!==void 0?s:-_,(r=this.orthoTop)!==null&&r!==void 0?r:_,f?this.maxZ:this.minZ,f?this.minZ:this.maxZ,this._projectionMatrix,c.isNDCHalfZRange):M.OrthoOffCenterLHToRef((n=this.orthoLeft)!==null&&n!==void 0?n:-d,(a=this.orthoRight)!==null&&a!==void 0?a:d,(o=this.orthoBottom)!==null&&o!==void 0?o:-_,(h=this.orthoTop)!==null&&h!==void 0?h:_,f?this.maxZ:this.minZ,f?this.minZ:this.maxZ,this._projectionMatrix,c.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=c.getRenderWidth(),this._cache.renderHeight=c.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?li.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=li.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let 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 fe("Ray")}getForwardRayToRef(e,t=100,i,s){throw fe("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!==ie.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let s=this._postProcesses.length;for(;--s>=0;){const r=this._postProcesses[s];r&&r.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=k.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==ie.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 M.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}_updateCameraRotationMatrix(){}_updateWebVRCameraRotationMatrix(){}_getWebVRProjectionMatrix(){return M.Identity()}_getWebVRViewMatrix(){return M.Identity()}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,e==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=k.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===ie.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)}_setupInputs(){}serialize(){const e=J.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&this.parent._serializeAsParent(e),this.inputs&&this.inputs.serialize(e),J.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}clone(e,t=null){const i=J.Clone(ie.GetConstructorFromName(this.getClassName(),e,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this);return i.name=e,i.parent=t,this.onClonedObservable.notifyObservers(i),i}getDirection(e){const t=E.Zero();return this.getDirectionToRef(e,t),t}get absoluteRotation(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation}getDirectionToRef(e,t){E.TransformNormalToRef(e,this.getWorldMatrix(),t)}static GetConstructorFromName(e,t,i,s=0,r=!0){const n=lt.Construct(e,t,i,{interaxial_distance:s,isStereoscopicSideBySide:r});return n||(()=>ie._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=ie.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=J.Parse(s,e,t);if(e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=E.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(E.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(E.FromArray(e.target)),e.cameraRigMode){const n=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,n)}if(e.animations){for(let n=0;n<e.animations.length;n++){const a=e.animations[n],o=Ri("BABYLON.Animation");o&&r.animations.push(o.Parse(a))}lt.ParseAnimationRanges(r,e,t)}return e.autoAnimate&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.isEnabled!==void 0&&r.setEnabled(e.isEnabled),r}}ie._CreateDefaultParsedCamera=(l,e)=>{throw fe("UniversalCamera")},ie.PERSPECTIVE_CAMERA=0,ie.ORTHOGRAPHIC_CAMERA=1,ie.FOVMODE_VERTICAL_FIXED=0,ie.FOVMODE_HORIZONTAL_FIXED=1,ie.RIG_MODE_NONE=0,ie.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,ie.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,ie.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,ie.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,ie.RIG_MODE_STEREOSCOPIC_INTERLACED=14,ie.RIG_MODE_VR=20,ie.RIG_MODE_WEBVR=21,ie.RIG_MODE_CUSTOM=22,ie.ForceAttachControlToAlwaysPreventDefault=!1,g([Ut("position")],ie.prototype,"_position",void 0),g([Ut("upVector")],ie.prototype,"_upVector",void 0),g([v()],ie.prototype,"orthoLeft",null),g([v()],ie.prototype,"orthoRight",null),g([v()],ie.prototype,"orthoBottom",null),g([v()],ie.prototype,"orthoTop",null),g([v()],ie.prototype,"fov",void 0),g([v()],ie.prototype,"projectionPlaneTilt",void 0),g([v()],ie.prototype,"minZ",void 0),g([v()],ie.prototype,"maxZ",void 0),g([v()],ie.prototype,"inertia",void 0),g([v()],ie.prototype,"mode",null),g([v()],ie.prototype,"layerMask",void 0),g([v()],ie.prototype,"fovMode",void 0),g([v()],ie.prototype,"cameraRigMode",void 0),g([v()],ie.prototype,"interaxialDistance",void 0),g([v()],ie.prototype,"isStereoscopicSideBySide",void 0);class co{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach((t,i)=>this.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 hi{constructor(){this.rootNodes=new Array,this.cameras=new Array,this.lights=new Array,this.meshes=new Array,this.skeletons=new Array,this.particleSystems=new Array,this.animations=[],this.animationGroups=new Array,this.multiMaterials=new Array,this.materials=new Array,this.morphTargetManagers=new Array,this.geometries=new Array,this.transformNodes=new Array,this.actionManagers=new Array,this.textures=new Array,this._environmentTexture=null,this.postProcesses=new Array}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,s){for(const r in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,r)&&this._BabylonFileParsers[r](e,t,i,s)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=new Array;return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach(t=>e=e.concat(t.bones)),e}}hi._BabylonFileParsers={},hi._IndividualBabylonFileParsers={};class Ni{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;t<this._keys.length;t++){const i=this._keys[t];if(this[i]!==e[i])return!1}return!0}cloneTo(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(let t=0;t<this._keys.length;t++){const i=this._keys[t];e[i]=this[i]}}reset(){this._keys.forEach(e=>this._setDefaultValue(e))}_setDefaultValue(e){var t,i,s,r,n;const a=(s=(i=(t=this._externalProperties)===null||t===void 0?void 0:t[e])===null||i===void 0?void 0:i.type)!==null&&s!==void 0?s:typeof this[e],o=(n=(r=this._externalProperties)===null||r===void 0?void 0:r[e])===null||n===void 0?void 0:n.default;switch(a){case"number":this[e]=o??0;break;case"string":this[e]=o??"";break;default:this[e]=o??!1;break}}toString(){let e="";for(let t=0;t<this._keys.length;t++){const i=this._keys[t],s=this[i];switch(typeof s){case"number":case"string":e+="#define "+i+" "+s+`
20
20
  `;break;default:s&&(e+="#define "+i+`
21
21
  `);break}}return e}}class Ke{constructor(){this._dirty=!0,this._tempColor=new ge(0,0,0,0),this._globalCurve=new ge(0,0,0,0),this._highlightsCurve=new ge(0,0,0,0),this._midtonesCurve=new ge(0,0,0,0),this._shadowsCurve=new ge(0,0,0,0),this._positiveCurve=new ge(0,0,0,0),this._negativeCurve=new ge(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",r="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(r,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}static PrepareUniforms(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}_getColorGradingDataToRef(e,t,i,s,r){e!=null&&(e=Ke._Clamp(e,0,360),t=Ke._Clamp(t,-100,100),i=Ke._Clamp(i,-100,100),s=Ke._Clamp(s,-100,100),t=Ke._ApplyColorGradingSliderNonlinear(t),t*=.5,s=Ke._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),Ke._FromHSBToRef(e,t,50+.25*s,r),r.scaleToRef(2,r),r.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 r=Ke._Clamp(e,0,360);const n=Ke._Clamp(t/100,0,1),a=Ke._Clamp(i/100,0,1);if(n===0)s.r=a,s.g=a,s.b=a;else{r/=60;const o=Math.floor(r),h=r-o,c=a*(1-n),u=a*(1-n*h),f=a*(1-n*(1-h));switch(o){case 0:s.r=a,s.g=f,s.b=c;break;case 1:s.r=u,s.g=a,s.b=c;break;case 2:s.r=c,s.g=a,s.b=f;break;case 3:s.r=c,s.g=u,s.b=a;break;case 4:s.r=f,s.g=c,s.b=a;break;default:s.r=a,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 J.Clone(()=>new Ke,this)}serialize(){return J.Serialize(this)}static Parse(e){return J.Parse(()=>new Ke,e,null,null)}}g([v()],Ke.prototype,"_globalHue",void 0),g([v()],Ke.prototype,"_globalDensity",void 0),g([v()],Ke.prototype,"_globalSaturation",void 0),g([v()],Ke.prototype,"_globalExposure",void 0),g([v()],Ke.prototype,"_highlightsHue",void 0),g([v()],Ke.prototype,"_highlightsDensity",void 0),g([v()],Ke.prototype,"_highlightsSaturation",void 0),g([v()],Ke.prototype,"_highlightsExposure",void 0),g([v()],Ke.prototype,"_midtonesHue",void 0),g([v()],Ke.prototype,"_midtonesDensity",void 0),g([v()],Ke.prototype,"_midtonesSaturation",void 0),g([v()],Ke.prototype,"_midtonesExposure",void 0),J._ColorCurvesParser=Ke.Parse;class Se{constructor(){this.colorCurves=new Ke,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=Se.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new ge(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=Se.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new B}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}static PrepareUniforms(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&Ke.PrepareUniforms(e),t.DITHER&&e.push("ditherIntensity")}static PrepareSamplers(e,t){t.COLORGRADING&&e.push("txColorTransform")}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}switch(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===Se._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType){case Se.TONEMAPPING_ACES:e.TONEMAPPING_ACES=!0;break;default:e.TONEMAPPING_ACES=!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&&Ke.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 r=t??s/i;let n=Math.tan(this.vignetteCameraFov*.5),a=n*r;const o=Math.sqrt(a*n);a=k.Mix(a,o,this.vignetteStretch),n=k.Mix(n,o,this.vignetteStretch),e.setFloat4("vignetteSettings1",a,n,-a*this.vignetteCenterX,-n*this.vignetteCenterY);const h=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,h)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const i=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(i-1)/i,.5/i,i,this.colorGradingTexture.level)}}clone(){return J.Clone(()=>new Se,this)}serialize(){return J.Serialize(this)}static Parse(e){const t=J.Parse(()=>new Se,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}}Se.TONEMAPPING_STANDARD=0,Se.TONEMAPPING_ACES=1,Se._VIGNETTEMODE_MULTIPLY=0,Se._VIGNETTEMODE_OPAQUE=1,g([nh()],Se.prototype,"colorCurves",void 0),g([v()],Se.prototype,"_colorCurvesEnabled",void 0),g([Me("colorGradingTexture")],Se.prototype,"_colorGradingTexture",void 0),g([v()],Se.prototype,"_colorGradingEnabled",void 0),g([v()],Se.prototype,"_colorGradingWithGreenDepth",void 0),g([v()],Se.prototype,"_colorGradingBGR",void 0),g([v()],Se.prototype,"_exposure",void 0),g([v()],Se.prototype,"_toneMappingEnabled",void 0),g([v()],Se.prototype,"_toneMappingType",void 0),g([v()],Se.prototype,"_contrast",void 0),g([v()],Se.prototype,"vignetteStretch",void 0),g([v()],Se.prototype,"vignetteCenterX",void 0),g([v()],Se.prototype,"vignetteCenterY",void 0),g([v()],Se.prototype,"vignetteWeight",void 0),g([Cn()],Se.prototype,"vignetteColor",void 0),g([v()],Se.prototype,"vignetteCameraFov",void 0),g([v()],Se.prototype,"_vignetteBlendMode",void 0),g([v()],Se.prototype,"_vignetteEnabled",void 0),g([v()],Se.prototype,"_ditheringEnabled",void 0),g([v()],Se.prototype,"_ditheringIntensity",void 0),g([v()],Se.prototype,"_skipFinalColorClamp",void 0),g([v()],Se.prototype,"_applyByPostProcess",void 0),g([v()],Se.prototype,"_isEnabled",void 0),J._ImageProcessingConfigurationParser=Se.Parse,re.prototype.createUniformBuffer=function(l){const e=this._gl.createBuffer();if(!e)throw new Error("Unable to create uniform buffer");const t=new Er(e);return this.bindUniformBuffer(t),l instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,l,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(l),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),t.references=1,t},re.prototype.createDynamicUniformBuffer=function(l){const e=this._gl.createBuffer();if(!e)throw new Error("Unable to create dynamic uniform buffer");const t=new Er(e);return this.bindUniformBuffer(t),l instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,l,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(l),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),t.references=1,t},re.prototype.updateUniformBuffer=function(l,e,t,i){this.bindUniformBuffer(l),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)},re.prototype.bindUniformBuffer=function(l){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,l?l.underlyingResource:null)},re.prototype.bindUniformBufferBase=function(l,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,l?l.underlyingResource:null)},re.prototype.bindUniformBlock=function(l,e,t){const i=l.program,s=this._gl.getUniformBlockIndex(i,e);s!==4294967295&&this._gl.uniformBlockBinding(i,s,t)};class q{constructor(e,t,i,s,r=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=i,this._name=s??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return 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 r=0;r<s;r++)this._data.push(0)}}addUniform(e,t,i=0){if(this._noUBO||this._uniformLocations[e]!==void 0)return;let s;if(i>0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},t==16)t=t*i;else{const n=(4-t)*i;t=t*i+n}s=[];for(let r=0;r<t;r++)s.push(0)}else{if(t instanceof Array)s=t,t=s.length;else{t=t,s=[];for(let r=0;r<t;r++)s.push(0)}this._fillAlignment(t)}this._uniformSizes[e]=t,this._uniformLocations[e]=this._uniformLocationPointer,this._uniformLocationPointer+=t;for(let r=0;r<t;r++)this._data.push(s[r]);this._needSync=!0}addMatrix(e,t){this.addUniform(e,Array.prototype.slice.call(t.toArray()))}addFloat2(e,t,i){const s=[t,i];this.addUniform(e,s)}addFloat3(e,t,i,s){const r=[t,i,s];this.addUniform(e,r)}addColor3(e,t){const i=[t.r,t.g,t.b];this.addUniform(e,i)}addColor4(e,t,i){const s=[t.r,t.g,t.b,i];this.addUniform(e,s)}addVector3(e,t){const i=[t.x,t.y,t.z];this.addUniform(e,i)}addMatrix3x3(e){this.addUniform(e,12)}addMatrix2x2(e){this.addUniform(e,8)}create(){this._noUBO||this._buffer||(this._fillAlignment(4),this._bufferData=new Float32Array(this._data),this._rebuild(),this._needSync=!0)}_rebuild(){this._noUBO||!this._bufferData||(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData):this._buffer=this._engine.createUniformBuffer(this._bufferData),this._engine._features.trackUbosInFrame&&(this._buffers.push([this._buffer,this._engine._features.checkUbosContentBeforeUpload?this._bufferData.slice():void 0]),this._bufferIndex=this._buffers.length-1,this._createBufferOnWrite=!1))}get _numBuffers(){return this._buffers.length}get _indexBuffer(){return this._bufferIndex}get name(){return this._name}get currentEffect(){return this._currentEffect}_buffersEqual(e,t){for(let i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0}_copyBuffer(e,t){for(let i=0;i<e.length;++i)t[i]=e[i]}update(){if(!this._noUBO){if(this.bindUniformBuffer(),!this._buffer){this.create();return}if(!this._dynamic&&!this._needSync){this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}if(this._buffers&&this._buffers.length>1&&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&&(q._UpdatedUbosInFrame[this._name]||(q._UpdatedUbosInFrame[this._name]=0),q._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}}_createNewBuffer(){this._bufferIndex+1<this._buffers.length?(this._bufferIndex++,this._buffer=this._buffers[this._bufferIndex][0],this._createBufferOnWrite=!1,this._needSync=!0):this._rebuild()}_checkNewFrame(){this._engine._features.trackUbosInFrame&&this._currentFrameId!==this._engine.frameId&&(this._currentFrameId=this._engine.frameId,this._createBufferOnWrite=!1,this._buffers&&this._buffers.length>0?(this._needSync=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){F.Error("Cannot add an uniform after UBO has been created.");return}this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let r=0;r<i;r++)this._bufferData[s+r]=t[r];else{let r=!1;for(let n=0;n<i;n++)(i===16&&!this._engine._features.uniformBufferHardCheckMatrix||this._bufferData[s+n]!==k.FloatRound(t[n]))&&(r=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[s+n]=t[n]);this._needSync=this._needSync||r}}updateUniformArray(e,t,i){this._checkNewFrame();const s=this._uniformLocations[e];if(s===void 0){F.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine.");return}this._buffer||this.create();const r=this._uniformArraySizes[e];if(this._dynamic)for(let n=0;n<i;n++)this._bufferData[s+n]=t[n];else{let n=!1,a=0,o=0;for(let h=0;h<i;h++)if(this._bufferData[s+o*4+a]!==k.FloatRound(t[h])&&(n=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[s+o*4+a]=t[h]),a++,a===r.strideSize){for(;a<4;a++)this._bufferData[s+o*4+a]=0;a=0,o++}this._needSync=this._needSync||n}}_cacheMatrix(e,t){this._checkNewFrame();const i=this._valueCache[e],s=t.updateFlag;return i!==void 0&&i===s?!1:(this._valueCache[e]=s,!0)}_updateMatrix3x3ForUniform(e,t){for(let i=0;i<3;i++)q._TempBuffer[i*4]=t[i*3],q._TempBuffer[i*4+1]=t[i*3+1],q._TempBuffer[i*4+2]=t[i*3+2],q._TempBuffer[i*4+3]=0;this.updateUniform(e,q._TempBuffer,12)}_updateMatrix3x3ForEffect(e,t){this._currentEffect.setMatrix3x3(e,t)}_updateMatrix2x2ForEffect(e,t){this._currentEffect.setMatrix2x2(e,t)}_updateMatrix2x2ForUniform(e,t){for(let i=0;i<2;i++)q._TempBuffer[i*4]=t[i*2],q._TempBuffer[i*4+1]=t[i*2+1],q._TempBuffer[i*4+2]=0,q._TempBuffer[i*4+3]=0;this.updateUniform(e,q._TempBuffer,8)}_updateFloatForEffect(e,t){this._currentEffect.setFloat(e,t)}_updateFloatForUniform(e,t){q._TempBuffer[0]=t,this.updateUniform(e,q._TempBuffer,1)}_updateFloat2ForEffect(e,t,i,s=""){this._currentEffect.setFloat2(e+s,t,i)}_updateFloat2ForUniform(e,t,i){q._TempBuffer[0]=t,q._TempBuffer[1]=i,this.updateUniform(e,q._TempBuffer,2)}_updateFloat3ForEffect(e,t,i,s,r=""){this._currentEffect.setFloat3(e+r,t,i,s)}_updateFloat3ForUniform(e,t,i,s){q._TempBuffer[0]=t,q._TempBuffer[1]=i,q._TempBuffer[2]=s,this.updateUniform(e,q._TempBuffer,3)}_updateFloat4ForEffect(e,t,i,s,r,n=""){this._currentEffect.setFloat4(e+n,t,i,s,r)}_updateFloat4ForUniform(e,t,i,s,r){q._TempBuffer[0]=t,q._TempBuffer[1]=i,q._TempBuffer[2]=s,q._TempBuffer[3]=r,this.updateUniform(e,q._TempBuffer,4)}_updateFloatArrayForEffect(e,t){this._currentEffect.setFloatArray(e,t)}_updateFloatArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateArrayForEffect(e,t){this._currentEffect.setArray(e,t)}_updateArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateIntArrayForEffect(e,t){this._currentEffect.setIntArray(e,t)}_updateIntArrayForUniform(e,t){q._TempBufferInt32View.set(t),this.updateUniformArray(e,q._TempBuffer,t.length)}_updateUIntArrayForEffect(e,t){this._currentEffect.setUIntArray(e,t)}_updateUIntArrayForUniform(e,t){q._TempBufferUInt32View.set(t),this.updateUniformArray(e,q._TempBuffer,t.length)}_updateMatrixForEffect(e,t){this._currentEffect.setMatrix(e,t)}_updateMatrixForUniform(e,t){this._cacheMatrix(e,t)&&this.updateUniform(e,t.toArray(),16)}_updateMatricesForEffect(e,t){this._currentEffect.setMatrices(e,t)}_updateMatricesForUniform(e,t){this.updateUniform(e,t,t.length)}_updateVector3ForEffect(e,t){this._currentEffect.setVector3(e,t)}_updateVector3ForUniform(e,t){q._TempBuffer[0]=t.x,q._TempBuffer[1]=t.y,q._TempBuffer[2]=t.z,this.updateUniform(e,q._TempBuffer,3)}_updateVector4ForEffect(e,t){this._currentEffect.setVector4(e,t)}_updateVector4ForUniform(e,t){q._TempBuffer[0]=t.x,q._TempBuffer[1]=t.y,q._TempBuffer[2]=t.z,q._TempBuffer[3]=t.w,this.updateUniform(e,q._TempBuffer,4)}_updateColor3ForEffect(e,t,i=""){this._currentEffect.setColor3(e+i,t)}_updateColor3ForUniform(e,t){q._TempBuffer[0]=t.r,q._TempBuffer[1]=t.g,q._TempBuffer[2]=t.b,this.updateUniform(e,q._TempBuffer,3)}_updateColor4ForEffect(e,t,i,s=""){this._currentEffect.setColor4(e+s,t,i)}_updateDirectColor4ForEffect(e,t,i=""){this._currentEffect.setDirectColor4(e+i,t)}_updateColor4ForUniform(e,t,i){q._TempBuffer[0]=t.r,q._TempBuffer[1]=t.g,q._TempBuffer[2]=t.b,q._TempBuffer[3]=i,this.updateUniform(e,q._TempBuffer,4)}_updateDirectColor4ForUniform(e,t){q._TempBuffer[0]=t.r,q._TempBuffer[1]=t.g,q._TempBuffer[2]=t.b,q._TempBuffer[3]=t.a,this.updateUniform(e,q._TempBuffer,4)}_updateIntForEffect(e,t,i=""){this._currentEffect.setInt(e+i,t)}_updateIntForUniform(e,t){q._TempBufferInt32View[0]=t,this.updateUniform(e,q._TempBuffer,1)}_updateInt2ForEffect(e,t,i,s=""){this._currentEffect.setInt2(e+s,t,i)}_updateInt2ForUniform(e,t,i){q._TempBufferInt32View[0]=t,q._TempBufferInt32View[1]=i,this.updateUniform(e,q._TempBuffer,2)}_updateInt3ForEffect(e,t,i,s,r=""){this._currentEffect.setInt3(e+r,t,i,s)}_updateInt3ForUniform(e,t,i,s){q._TempBufferInt32View[0]=t,q._TempBufferInt32View[1]=i,q._TempBufferInt32View[2]=s,this.updateUniform(e,q._TempBuffer,3)}_updateInt4ForEffect(e,t,i,s,r,n=""){this._currentEffect.setInt4(e+n,t,i,s,r)}_updateInt4ForUniform(e,t,i,s,r){q._TempBufferInt32View[0]=t,q._TempBufferInt32View[1]=i,q._TempBufferInt32View[2]=s,q._TempBufferInt32View[3]=r,this.updateUniform(e,q._TempBuffer,4)}_updateUIntForEffect(e,t,i=""){this._currentEffect.setUInt(e+i,t)}_updateUIntForUniform(e,t){q._TempBufferUInt32View[0]=t,this.updateUniform(e,q._TempBuffer,1)}_updateUInt2ForEffect(e,t,i,s=""){this._currentEffect.setUInt2(e+s,t,i)}_updateUInt2ForUniform(e,t,i){q._TempBufferUInt32View[0]=t,q._TempBufferUInt32View[1]=i,this.updateUniform(e,q._TempBuffer,2)}_updateUInt3ForEffect(e,t,i,s,r=""){this._currentEffect.setUInt3(e+r,t,i,s)}_updateUInt3ForUniform(e,t,i,s){q._TempBufferUInt32View[0]=t,q._TempBufferUInt32View[1]=i,q._TempBufferUInt32View[2]=s,this.updateUniform(e,q._TempBuffer,3)}_updateUInt4ForEffect(e,t,i,s,r,n=""){this._currentEffect.setUInt4(e+n,t,i,s,r)}_updateUInt4ForUniform(e,t,i,s,r){q._TempBufferUInt32View[0]=t,q._TempBufferUInt32View[1]=i,q._TempBufferUInt32View[2]=s,q._TempBufferUInt32View[3]=r,this.updateUniform(e,q._TempBuffer,4)}setTexture(e,t){this._currentEffect.setTexture(e,t)}updateUniformDirectly(e,t){this.updateUniform(e,t,t.length),this.update()}bindToEffect(e,t){this._currentEffect=e,this._currentEffectName=t}bindUniformBuffer(){!this._noUBO&&this._buffer&&this._currentEffect&&this._currentEffect.bindUniformBuffer(this._buffer,this._currentEffectName)}unbindEffect(){this._currentEffect=void 0,this._currentEffectName=void 0}setDataBuffer(e){if(!this._buffers)return this._buffer===e;for(let t=0;t<this._buffers.length;++t)if(this._buffers[t][0]===e)return this._bufferIndex=t,this._buffer=e,this._createBufferOnWrite=!1,this._currentEffect=void 0,!0;return!1}dispose(){if(this._noUBO)return;const e=this._engine._uniformBuffers,t=e.indexOf(this);if(t!==-1&&(e[t]=e[e.length-1],e.pop()),this._engine._features.trackUbosInFrame&&this._buffers)for(let i=0;i<this._buffers.length;++i){const s=this._buffers[i][0];this._engine._releaseBuffer(s)}else this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)}}q._UpdatedUbosInFrame={},q._MAX_UNIFORM_SIZE=256,q._TempBuffer=new Float32Array(q._MAX_UNIFORM_SIZE),q._TempBufferInt32View=new Int32Array(q._TempBuffer.buffer),q._TempBufferUInt32View=new Uint32Array(q._TempBuffer.buffer);class Gs{constructor(e,t,i,s=0,r=!1,n=!1,a=!1,o){this._isAlreadyOwned=!1,e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=n,this._divisor=o||1,t instanceof ss?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=a?s:s*Float32Array.BYTES_PER_ELEMENT,r||this.create()}createVertexBuffer(e,t,i,s,r,n=!1,a){const o=n?t:t*Float32Array.BYTES_PER_ELEMENT,h=s?n?s:s*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new A(this._engine,this,e,this._updatable,!0,h,r===void 0?this._instanced:r,o,i,void 0,void 0,!0,this._divisor||a)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data,e&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e),this._data=e):this._buffer=this._engine.createVertexBuffer(e)))}_rebuild(){this._buffer=null,this.create(this._data)}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._buffer=null,this._data=null)}}class A{get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=e!=0;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}constructor(e,t,i,s,r,n,a,o,h,c,u=!1,f=!1,d=1,_=!1){if(t instanceof Gs?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new Gs(e,t,s,n,r,a,f),this._ownsBuffer=!0),this.uniqueId=A._Counter++,this._kind=i,c==null){const m=this.getData();this.type=A.FLOAT,m instanceof Int8Array?this.type=A.BYTE:m instanceof Uint8Array?this.type=A.UNSIGNED_BYTE:m instanceof Int16Array?this.type=A.SHORT:m instanceof Uint16Array?this.type=A.UNSIGNED_SHORT:m instanceof Int32Array?this.type=A.INT:m instanceof Uint32Array&&(this.type=A.UNSIGNED_INT)}else this.type=c;const p=A.GetTypeByteLength(this.type);f?(this._size=h||(n?n/p:A.DeduceStride(i)),this.byteStride=n||this._buffer.byteStride||this._size*p,this.byteOffset=o||0):(this._size=h||n||A.DeduceStride(i),this.byteStride=n?n*p:this._buffer.byteStride||this._size*p,this.byteOffset=(o||0)*p),this.normalized=u,this._instanced=a!==void 0?a:!1,this._instanceDivisor=a?d:0,this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){this._buffer&&this._buffer._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();if(!i)return null;const s=this.getSize()*A.GetTypeByteLength(this.type),r=e*this.getSize();if(this.type!==A.FLOAT||this.byteStride!==s){const n=new Float32Array(r);return this.forEach(r,(a,o)=>n[o]=a),n}if(!(i instanceof Array||i instanceof Float32Array)||this.byteOffset!==0||i.length!==r)if(i instanceof Array){const n=this.byteOffset/4;return i.slice(n,n+r)}else{if(i instanceof ArrayBuffer)return new Float32Array(i,this.byteOffset,r);{let n=i.byteOffset+this.byteOffset;if(t){const o=new Float32Array(r),h=new Float32Array(i.buffer,n,r);return o.set(h),o}const a=n%4;return a&&(n=Math.max(0,n-a)),new Float32Array(i.buffer,n,r)}}return t?i.slice():i}getBuffer(){return this._buffer.getBuffer()}getStrideSize(){return this.byteStride/A.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/A.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*A.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e)}update(e){this._buffer.update(e)}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i)}dispose(){this._ownsBuffer&&this._buffer.dispose()}forEach(e,t){A.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}static DeduceStride(e){switch(e){case A.UVKind:case A.UV2Kind:case A.UV3Kind:case A.UV4Kind:case A.UV5Kind:case A.UV6Kind:return 2;case A.NormalKind:case A.PositionKind:return 3;case A.ColorKind:case A.MatricesIndicesKind:case A.MatricesIndicesExtraKind:case A.MatricesWeightsKind:case A.MatricesWeightsExtraKind:case A.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetTypeByteLength(e){switch(e){case A.BYTE:case A.UNSIGNED_BYTE:return 1;case A.SHORT:case A.UNSIGNED_SHORT:return 2;case A.INT:case A.UNSIGNED_INT:case A.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,s,r,n,a,o){if(e instanceof Array){let h=t/4;const c=i/4;for(let u=0;u<n;u+=s){for(let f=0;f<s;f++)o(e[h+f],u+f);h+=c}}else{const h=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),c=A.GetTypeByteLength(r);for(let u=0;u<n;u+=s){let f=t;for(let d=0;d<s;d++){const _=A._GetFloatValue(h,r,f,a);o(_,u+d),f+=c}t+=i}}}static _GetFloatValue(e,t,i,s){switch(t){case A.BYTE:{let r=e.getInt8(i);return s&&(r=Math.max(r/127,-1)),r}case A.UNSIGNED_BYTE:{let r=e.getUint8(i);return s&&(r=r/255),r}case A.SHORT:{let r=e.getInt16(i,!0);return s&&(r=Math.max(r/32767,-1)),r}case A.UNSIGNED_SHORT:{let r=e.getUint16(i,!0);return s&&(r=r/65535),r}case A.INT:return e.getInt32(i,!0);case A.UNSIGNED_INT:return e.getUint32(i,!0);case A.FLOAT:return e.getFloat32(i,!0);default:throw new Error(`Invalid component type ${t}`)}}}A._Counter=0,A.BYTE=5120,A.UNSIGNED_BYTE=5121,A.SHORT=5122,A.UNSIGNED_SHORT=5123,A.INT=5124,A.UNSIGNED_INT=5125,A.FLOAT=5126,A.PositionKind="position",A.NormalKind="normal",A.TangentKind="tangent",A.UVKind="uv",A.UV2Kind="uv2",A.UV3Kind="uv3",A.UV4Kind="uv4",A.UV5Kind="uv5",A.UV6Kind="uv6",A.ColorKind="color",A.ColorInstanceKind="instanceColor",A.MatricesIndicesKind="matricesIndices",A.MatricesWeightsKind="matricesWeights",A.MatricesIndicesExtraKind="matricesIndicesExtra",A.MatricesWeightsExtraKind="matricesWeightsExtra";class br{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(A.NormalKind))return null;let i=this.pickedMesh.getIndices();(i==null?void 0:i.length)===0&&(i=null);let s;const r=D.Vector3[0],n=D.Vector3[1],a=D.Vector3[2];if(t){const h=this.pickedMesh.getVerticesData(A.NormalKind);let c=i?E.FromArrayToRef(h,i[this.faceId*3]*3,r):r.copyFromFloats(h[this.faceId*3*3],h[this.faceId*3*3+1],h[this.faceId*3*3+2]),u=i?E.FromArrayToRef(h,i[this.faceId*3+1]*3,n):n.copyFromFloats(h[(this.faceId*3+1)*3],h[(this.faceId*3+1)*3+1],h[(this.faceId*3+1)*3+2]),f=i?E.FromArrayToRef(h,i[this.faceId*3+2]*3,a):a.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 E(c.x+u.x+f.x,c.y+u.y+f.y,c.z+u.z+f.z)}else{const h=this.pickedMesh.getVerticesData(A.PositionKind),c=i?E.FromArrayToRef(h,i[this.faceId*3]*3,r):r.copyFromFloats(h[this.faceId*3*3],h[this.faceId*3*3+1],h[this.faceId*3*3+2]),u=i?E.FromArrayToRef(h,i[this.faceId*3+1]*3,n):n.copyFromFloats(h[(this.faceId*3+1)*3],h[(this.faceId*3+1)*3+1],h[(this.faceId*3+1)*3+2]),f=i?E.FromArrayToRef(h,i[this.faceId*3+2]*3,a):a.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),_=f.subtract(u);s=E.Cross(d,_)}const o=(h,c)=>{let u=h.getWorldMatrix();h.nonUniformScaling&&(D.Matrix[0].copyFrom(u),u=D.Matrix[0],u.setTranslationFromFloats(0,0,0),u.invert(),u.transposeToRef(D.Matrix[1]),u=D.Matrix[1]),E.TransformNormalToRef(c,u,c)};if(e&&o(this.pickedMesh,s),this.ray){const h=D.Vector3[0].copyFrom(s);e||o(this.pickedMesh,h),E.Dot(h,this.ray.direction)>0&&s.negateInPlace()}return s.normalize(),s}getTextureCoordinates(e=A.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=ae.FromArray(i,t[this.faceId*3]*2),r=ae.FromArray(i,t[this.faceId*3+1]*2),n=ae.FromArray(i,t[this.faceId*3+2]*2);return s=s.scale(this.bu),r=r.scale(this.bv),n=n.scale(1-this.bu-this.bv),new ae(s.x+r.x+n.x,s.y+r.y+n.y)}}class St{constructor(e,t,i,s,r,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=r,this.additionalData=n}static CreateNew(e,t,i){const s=e.getScene();return new St(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new St(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new St(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new St(e,t.x,t.y,null,i,s)}}class Nn{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[A.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[A.PositionKind]=new A(this._scene.getEngine(),e,A.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[A.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,r=0,n=!1){var a;const o=this._scene.getEngine();for(let h=0;h<e.length;h++){h<e.length-1?e[h+1].activate(this._scene.activeCamera,t==null?void 0:t.texture):(t?o.bindFramebuffer(t,s,void 0,void 0,i,r):n||o.restoreDefaultFramebuffer(),(a=o._debugInsertMarker)===null||a===void 0||a.call(o,`post process ${e[h].name} output`));const c=e[h],u=c.apply();u&&(c.onBeforeRenderObservable.notifyObservers(u),this._prepareBuffers(),o.bindBuffers(this._vertexBuffers,this._indexBuffer,u),o.drawElementsType(0,0,6),c.onAfterRenderObservable.notifyObservers(u))}o.setDepthBuffer(!0),o.setDepthWrite(!0)}_finalizeFrame(e,t,i,s,r=!1){var n;const a=this._scene.activeCamera;if(!a||(s=s||a._postProcesses.filter(h=>h!=null),s.length===0||!this._scene.postProcessesEnabled))return;const o=this._scene.getEngine();for(let h=0,c=s.length;h<c;h++){const u=s[h];if(h<c-1?u._outputTexture=s[h+1].activate(a,t==null?void 0:t.texture):(t?(o.bindFramebuffer(t,i,void 0,void 0,r),u._outputTexture=t):(o.restoreDefaultFramebuffer(),u._outputTexture=null),(n=o._debugInsertMarker)===null||n===void 0||n.call(o,`post process ${s[h].name} output`)),e)break;const f=u.apply();f&&(u.onBeforeRenderObservable.notifyObservers(f),this._prepareBuffers(),o.bindBuffers(this._vertexBuffers,this._indexBuffer,f),o.drawElementsType(0,0,6),u.onAfterRenderObservable.notifyObservers(f))}o.setDepthBuffer(!0),o.setDepthWrite(!0),o.setAlphaMode(0)}dispose(){const e=this._vertexBuffers[A.PositionKind];e&&(e.dispose(),this._vertexBuffers[A.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)}}class mi{set opaqueSortCompareFn(e){e?this._opaqueSortCompareFn=e:this._opaqueSortCompareFn=mi.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){e?this._alphaTestSortCompareFn=e:this._alphaTestSortCompareFn=mi.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){e?this._transparentSortCompareFn=e:this._transparentSortCompareFn=mi.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,i=null,s=null,r=null){this.index=e,this._opaqueSubMeshes=new vt(256),this._transparentSubMeshes=new vt(256),this._alphaTestSubMeshes=new vt(256),this._depthOnlySubMeshes=new vt(256),this._particleSystems=new vt(256),this._spriteManagers=new vt(256),this._empty=!0,this._edgesRenderers=new gs(16),this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=s,this.transparentSortCompareFn=r}render(e,t,i,s){if(e){e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);return}const r=this._scene.getEngine();this._depthOnlySubMeshes.length!==0&&(r.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),r.setColorWrite(!0)),this._opaqueSubMeshes.length!==0&&this._renderOpaque(this._opaqueSubMeshes),this._alphaTestSubMeshes.length!==0&&this._renderAlphaTest(this._alphaTestSubMeshes);const n=r.getStencilBuffer();if(r.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(s),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),this._transparentSubMeshes.length!==0||this._scene.useOrderIndependentTransparency){if(r.setStencilBuffer(n),this._scene.useOrderIndependentTransparency){const a=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);a.length&&this._renderTransparent(a)}else this._renderTransparent(this._transparentSubMeshes);r.setAlphaMode(0)}if(r.setStencilBuffer(!1),this._edgesRenderers.length){for(let a=0;a<this._edgesRenderers.length;a++)this._edgesRenderers.data[a].render();r.setAlphaMode(0)}r.setStencilBuffer(n)}_renderOpaqueSorted(e){return mi._RenderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera,!1)}_renderAlphaTestSorted(e){return mi._RenderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera,!1)}_renderTransparentSorted(e){return mi._RenderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera,!0)}static _RenderSorted(e,t,i,s){let r=0,n;const a=i?i.globalPosition:mi._ZeroVector;if(s)for(;r<e.length;r++)n=e.data[r],n._alphaIndex=n.getMesh().alphaIndex,n._distanceToCamera=E.Distance(n.getBoundingInfo().boundingSphere.centerWorld,a);const o=e.length===e.data.length?e.data:e.data.slice(0,e.length);t&&o.sort(t);const h=o[0].getMesh().getScene();for(r=0;r<o.length;r++)if(n=o[r],!(h._activeMeshesFrozenButKeepClipping&&!n.isInFrustum(h._frustumPlanes))){if(s){const c=n.getMaterial();if(c&&c.needDepthPrePass){const u=c.getScene().getEngine();u.setColorWrite(!1),u.setAlphaMode(0),n.render(!1),u.setColorWrite(!0)}}n.render(s)}}static defaultTransparentSortCompare(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:mi.backToFrontSortCompare(e,t)}static backToFrontSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),s=t.getMesh();return i.material&&s.material?i.material.uniqueId-s.material.uniqueId:i.uniqueId-s.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){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._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;i<this._particleSystems.length;i++){const s=this._particleSystems.data[i];if((t&&t.layerMask&s.layerMask)===0)continue;const r=s.emitter;(!r.position||!e||e.indexOf(r)!==-1)&&this._scene._activeParticles.addCount(s.render(),!1)}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}_renderSprites(){if(!this._scene.spritesEnabled||this._spriteManagers.length===0)return;const e=this._scene.activeCamera;this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);for(let t=0;t<this._spriteManagers.length;t++){const i=this._spriteManagers.data[t];(e&&e.layerMask&i.layerMask)!==0&&i.render()}this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)}}mi._ZeroVector=E.Zero();class Uh{}class Pt{get maintainStateBetweenFrames(){return this._maintainStateBetweenFrames}set maintainStateBetweenFrames(e){if(e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,!this._maintainStateBetweenFrames)){for(const t of this._scene.meshes)if(t.subMeshes)for(const i of t.subMeshes)i._wasDispatched=!1;if(this._scene.spriteManagers)for(const t of this._scene.spriteManagers)t._wasDispatched=!1;for(const t of this._scene.particleSystems)t._wasDispatched=!1}}constructor(e){this._useSceneAutoClearSetup=!1,this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new Uh,this._maintainStateBetweenFrames=!1,this._scene=e;for(let t=Pt.MIN_RENDERINGGROUPS;t<Pt.MAX_RENDERINGGROUPS;t++)this._autoClearDepthStencil[t]={autoClear:!0,depth:!0,stencil:!0}}getRenderingGroup(e){const t=e||0;return this._prepareRenderingGroup(t),this._renderingGroups[t]}_clearDepthStencilBuffer(e=!0,t=!0){this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(null,!1,e,t),this._depthStencilBufferAlreadyCleaned=!0)}render(e,t,i,s){const r=this._renderingGroupInfo;if(r.scene=this._scene,r.camera=this._scene.activeCamera,this._scene.spriteManagers&&s)for(let n=0;n<this._scene.spriteManagers.length;n++){const a=this._scene.spriteManagers[n];this.dispatchSprites(a)}for(let n=Pt.MIN_RENDERINGGROUPS;n<Pt.MAX_RENDERINGGROUPS;n++){this._depthStencilBufferAlreadyCleaned=n===Pt.MIN_RENDERINGGROUPS;const a=this._renderingGroups[n];if(!a||a._empty)continue;const o=Math.pow(2,n);if(r.renderingGroupId=n,this._scene.onBeforeRenderingGroupObservable.notifyObservers(r,o),Pt.AUTOCLEAR){const h=this._useSceneAutoClearSetup?this._scene.getAutoClearDepthStencilSetup(n):this._autoClearDepthStencil[n];h&&h.autoClear&&this._clearDepthStencilBuffer(h.depth,h.stencil)}for(const h of this._scene._beforeRenderingGroupDrawStage)h.action(n);a.render(e,s,i,t);for(const h of this._scene._afterRenderingGroupDrawStage)h.action(n);this._scene.onAfterRenderingGroupObservable.notifyObservers(r,o)}}reset(){if(!this.maintainStateBetweenFrames)for(let e=Pt.MIN_RENDERINGGROUPS;e<Pt.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.prepare()}}resetSprites(){if(!this.maintainStateBetweenFrames)for(let e=Pt.MIN_RENDERINGGROUPS;e<Pt.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.prepareSprites()}}dispose(){this.freeRenderingGroups(),this._renderingGroups.length=0,this._renderingGroupInfo=null}freeRenderingGroups(){for(let e=Pt.MIN_RENDERINGGROUPS;e<Pt.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.dispose()}}_prepareRenderingGroup(e){this._renderingGroups[e]===void 0&&(this._renderingGroups[e]=new mi(e,this._scene,this._customOpaqueSortCompareFn[e],this._customAlphaTestSortCompareFn[e],this._customTransparentSortCompareFn[e]))}dispatchSprites(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchSprites(e))}dispatchParticles(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchParticles(e))}dispatch(e,t,i){t===void 0&&(t=e.getMesh()),!(this.maintainStateBetweenFrames&&e._wasDispatched)&&(e._wasDispatched=!0,this.getRenderingGroup(t.renderingGroupId).dispatch(e,t,i))}setRenderingOrder(e,t=null,i=null,s=null){if(this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=i,this._customTransparentSortCompareFn[e]=s,this._renderingGroups[e]){const r=this._renderingGroups[e];r.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],r.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],r.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._autoClearDepthStencil[e]={autoClear:t,depth:i,stencil:s}}getAutoClearDepthStencilSetup(e){return this._autoClearDepthStencil[e]}}Pt.MAX_RENDERINGGROUPS=4,Pt.MIN_RENDERINGGROUPS=0,Pt.AUTOCLEAR=!0;class ee{}ee.NAME_EFFECTLAYER="EffectLayer",ee.NAME_LAYER="Layer",ee.NAME_LENSFLARESYSTEM="LensFlareSystem",ee.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",ee.NAME_PARTICLESYSTEM="ParticleSystem",ee.NAME_GAMEPAD="Gamepad",ee.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",ee.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",ee.NAME_PREPASSRENDERER="PrePassRenderer",ee.NAME_DEPTHRENDERER="DepthRenderer",ee.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",ee.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",ee.NAME_SPRITE="Sprite",ee.NAME_SUBSURFACE="SubSurface",ee.NAME_OUTLINERENDERER="Outline",ee.NAME_PROCEDURALTEXTURE="ProceduralTexture",ee.NAME_SHADOWGENERATOR="ShadowGenerator",ee.NAME_OCTREE="Octree",ee.NAME_PHYSICSENGINE="PhysicsEngine",ee.NAME_AUDIO="Audio",ee.NAME_FLUIDRENDERER="FluidRenderer",ee.STEP_ISREADYFORMESH_EFFECTLAYER=0,ee.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,ee.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,ee.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,ee.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,ee.STEP_BEFORECAMERADRAW_PREPASS=0,ee.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,ee.STEP_BEFORECAMERADRAW_LAYER=2,ee.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,ee.STEP_BEFORERENDERTARGETDRAW_LAYER=1,ee.STEP_BEFORERENDERINGMESH_PREPASS=0,ee.STEP_BEFORERENDERINGMESH_OUTLINE=1,ee.STEP_AFTERRENDERINGMESH_PREPASS=0,ee.STEP_AFTERRENDERINGMESH_OUTLINE=1,ee.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,ee.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,ee.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,ee.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,ee.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,ee.STEP_BEFORECLEAR_PREPASS=1,ee.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,ee.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,ee.STEP_AFTERRENDERTARGETDRAW_LAYER=1,ee.STEP_AFTERCAMERADRAW_PREPASS=0,ee.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,ee.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,ee.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,ee.STEP_AFTERCAMERADRAW_LAYER=4,ee.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,ee.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,ee.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,ee.STEP_AFTERRENDER_AUDIO=0,ee.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,ee.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,ee.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,ee.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,ee.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,ee.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,ee.STEP_POINTERMOVE_SPRITE=0,ee.STEP_POINTERDOWN_SPRITE=0,ee.STEP_POINTERUP_SPRITE=0;class tt extends Array{constructor(e){super(...e)}static Create(){return Object.create(tt.prototype)}registerStep(e,t,i){let s=0,r=Number.MAX_VALUE;for(;s<this.length&&(r=this[s].index,!(e<r));s++);this.splice(s,0,{index:e,component:t,action:i.bind(t)})}clear(){this.length=0}}class ce{}ce.POINTERDOWN=1,ce.POINTERUP=2,ce.POINTERMOVE=4,ce.POINTERWHEEL=8,ce.POINTERPICK=16,ce.POINTERTAP=32,ce.POINTERDOUBLETAP=64;class uo{constructor(e,t){this.type=e,this.event=t}}class Vh extends uo{constructor(e,t,i,s){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new ae(i,s)}}class Fi extends uo{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,s=null){super(e,t),this._pickInfo=i,this._inputManager=s}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}class Qt{constructor(){this.hoverCursor="",this.actions=new Array,this.isRecursive=!1}static get HasTriggers(){for(const e in Qt.Triggers)if(Object.prototype.hasOwnProperty.call(Qt.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in Qt.Triggers)if(Object.prototype.hasOwnProperty.call(Qt.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in Qt.Triggers)if(Object.prototype.hasOwnProperty.call(Qt.Triggers,t)&&parseInt(t)===e)return!0;return!1}}Qt.Triggers={};class Hs{}Hs.KEYDOWN=1,Hs.KEYUP=2;class Fn{constructor(e,t){this.type=e,this.event=t}}class fo extends Fn{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 se;(function(l){l[l.Generic=0]="Generic",l[l.Keyboard=1]="Keyboard",l[l.Mouse=2]="Mouse",l[l.Touch=3]="Touch",l[l.DualShock=4]="DualShock",l[l.Xbox=5]="Xbox",l[l.Switch=6]="Switch",l[l.DualSense=7]="DualSense"})(se||(se={}));var de;(function(l){l[l.Horizontal=0]="Horizontal",l[l.Vertical=1]="Vertical",l[l.LeftClick=2]="LeftClick",l[l.MiddleClick=3]="MiddleClick",l[l.RightClick=4]="RightClick",l[l.BrowserBack=5]="BrowserBack",l[l.BrowserForward=6]="BrowserForward",l[l.MouseWheelX=7]="MouseWheelX",l[l.MouseWheelY=8]="MouseWheelY",l[l.MouseWheelZ=9]="MouseWheelZ",l[l.Move=12]="Move"})(de||(de={}));var sn;(function(l){l[l.Horizontal=0]="Horizontal",l[l.Vertical=1]="Vertical",l[l.LeftClick=2]="LeftClick",l[l.MiddleClick=3]="MiddleClick",l[l.RightClick=4]="RightClick",l[l.BrowserBack=5]="BrowserBack",l[l.BrowserForward=6]="BrowserForward",l[l.MouseWheelX=7]="MouseWheelX",l[l.MouseWheelY=8]="MouseWheelY",l[l.MouseWheelZ=9]="MouseWheelZ",l[l.DeltaHorizontal=10]="DeltaHorizontal",l[l.DeltaVertical=11]="DeltaVertical"})(sn||(sn={}));var _o;(function(l){l[l.Cross=0]="Cross",l[l.Circle=1]="Circle",l[l.Square=2]="Square",l[l.Triangle=3]="Triangle",l[l.L1=4]="L1",l[l.R1=5]="R1",l[l.L2=6]="L2",l[l.R2=7]="R2",l[l.Share=8]="Share",l[l.Options=9]="Options",l[l.L3=10]="L3",l[l.R3=11]="R3",l[l.DPadUp=12]="DPadUp",l[l.DPadDown=13]="DPadDown",l[l.DPadLeft=14]="DPadLeft",l[l.DPadRight=15]="DPadRight",l[l.Home=16]="Home",l[l.TouchPad=17]="TouchPad",l[l.LStickXAxis=18]="LStickXAxis",l[l.LStickYAxis=19]="LStickYAxis",l[l.RStickXAxis=20]="RStickXAxis",l[l.RStickYAxis=21]="RStickYAxis"})(_o||(_o={}));var po;(function(l){l[l.Cross=0]="Cross",l[l.Circle=1]="Circle",l[l.Square=2]="Square",l[l.Triangle=3]="Triangle",l[l.L1=4]="L1",l[l.R1=5]="R1",l[l.L2=6]="L2",l[l.R2=7]="R2",l[l.Create=8]="Create",l[l.Options=9]="Options",l[l.L3=10]="L3",l[l.R3=11]="R3",l[l.DPadUp=12]="DPadUp",l[l.DPadDown=13]="DPadDown",l[l.DPadLeft=14]="DPadLeft",l[l.DPadRight=15]="DPadRight",l[l.Home=16]="Home",l[l.TouchPad=17]="TouchPad",l[l.LStickXAxis=18]="LStickXAxis",l[l.LStickYAxis=19]="LStickYAxis",l[l.RStickXAxis=20]="RStickXAxis",l[l.RStickYAxis=21]="RStickYAxis"})(po||(po={}));var mo;(function(l){l[l.A=0]="A",l[l.B=1]="B",l[l.X=2]="X",l[l.Y=3]="Y",l[l.LB=4]="LB",l[l.RB=5]="RB",l[l.LT=6]="LT",l[l.RT=7]="RT",l[l.Back=8]="Back",l[l.Start=9]="Start",l[l.LS=10]="LS",l[l.RS=11]="RS",l[l.DPadUp=12]="DPadUp",l[l.DPadDown=13]="DPadDown",l[l.DPadLeft=14]="DPadLeft",l[l.DPadRight=15]="DPadRight",l[l.Home=16]="Home",l[l.LStickXAxis=17]="LStickXAxis",l[l.LStickYAxis=18]="LStickYAxis",l[l.RStickXAxis=19]="RStickXAxis",l[l.RStickYAxis=20]="RStickYAxis"})(mo||(mo={}));var go;(function(l){l[l.B=0]="B",l[l.A=1]="A",l[l.Y=2]="Y",l[l.X=3]="X",l[l.L=4]="L",l[l.R=5]="R",l[l.ZL=6]="ZL",l[l.ZR=7]="ZR",l[l.Minus=8]="Minus",l[l.Plus=9]="Plus",l[l.LS=10]="LS",l[l.RS=11]="RS",l[l.DPadUp=12]="DPadUp",l[l.DPadDown=13]="DPadDown",l[l.DPadLeft=14]="DPadLeft",l[l.DPadRight=15]="DPadRight",l[l.Home=16]="Home",l[l.Capture=17]="Capture",l[l.LStickXAxis=18]="LStickXAxis",l[l.LStickYAxis=19]="LStickYAxis",l[l.RStickXAxis=20]="RStickXAxis",l[l.RStickYAxis=21]="RStickYAxis"})(go||(go={}));var Eo;(function(l){l[l.PointerMove=0]="PointerMove",l[l.PointerDown=1]="PointerDown",l[l.PointerUp=2]="PointerUp"})(Eo||(Eo={}));class Ws{}Ws.DOM_DELTA_PIXEL=0,Ws.DOM_DELTA_LINE=1,Ws.DOM_DELTA_PAGE=2;class Es{static CreateDeviceEvent(e,t,i,s,r,n,a){switch(e){case se.Keyboard:return this._CreateKeyboardEvent(i,s,r,n);case se.Mouse:if(i===de.MouseWheelX||i===de.MouseWheelY||i===de.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,r,n);case se.Touch:return this._CreatePointerEvent(e,t,i,s,r,n,a);default:throw`Unable to generate event for device ${se[e]}`}}static _CreatePointerEvent(e,t,i,s,r,n,a){const o=this._CreateMouseEvent(e,t,i,s,r,n);e===se.Mouse?(o.deviceType=se.Mouse,o.pointerId=1,o.pointerType="mouse"):(o.deviceType=se.Touch,o.pointerId=a??t,o.pointerType="touch");let h=0;return h+=r.pollInput(e,t,de.LeftClick),h+=r.pollInput(e,t,de.RightClick)*2,h+=r.pollInput(e,t,de.MiddleClick)*4,o.buttons=h,i===de.Move?o.type="pointermove":i>=de.LeftClick&&i<=de.RightClick&&(o.type=s===1?"pointerdown":"pointerup",o.button=i-2),o}static _CreateWheelEvent(e,t,i,s,r,n){const a=this._CreateMouseEvent(e,t,i,s,r,n);switch(a.pointerId=1,a.type="wheel",a.deltaMode=Ws.DOM_DELTA_PIXEL,a.deltaX=0,a.deltaY=0,a.deltaZ=0,i){case de.MouseWheelX:a.deltaX=s;break;case de.MouseWheelY:a.deltaY=s;break;case de.MouseWheelZ:a.deltaZ=s;break}return a}static _CreateMouseEvent(e,t,i,s,r,n){const a=this._CreateEvent(n),o=r.pollInput(e,t,de.Horizontal),h=r.pollInput(e,t,de.Vertical);return n?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-n.getBoundingClientRect().x,a.offsetY=a.movementY-n.getBoundingClientRect().y):(a.movementX=r.pollInput(e,t,sn.DeltaHorizontal),a.movementY=r.pollInput(e,t,sn.DeltaVertical),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,r),a.clientX=o,a.clientY=h,a.x=o,a.y=h,a.deviceType=e,a.deviceSlot=t,a.inputIndex=i,a}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=se.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=t===1?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(se.Keyboard),s=i&&t.pollInput(se.Keyboard,0,18)===1,r=i&&t.pollInput(se.Keyboard,0,17)===1,n=i&&(t.pollInput(se.Keyboard,0,91)===1||t.pollInput(se.Keyboard,0,92)===1||t.pollInput(se.Keyboard,0,93)===1),a=i&&t.pollInput(se.Keyboard,0,16)===1;e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=a}static _CreateEvent(e){const t={};return t.preventDefault=()=>{},t.target=e,t}}class kh{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(s,r,n,a)=>{const o=Es.CreateDeviceEvent(s,r,n,a,this);i(s,r,o)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===se.Mouse||e===se.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const To=255,Ao=Object.keys(de).length/2;class Gh{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=k.IsSafari(),this._usingMacOS=qr()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=r=>{},this._keyboardUpEvent=r=>{},this._keyboardBlurEvent=r=>{},this._pointerMoveEvent=r=>{},this._pointerDownEvent=r=>{},this._pointerUpEvent=r=>{},this._pointerCancelEvent=r=>{},this._pointerWheelEvent=r=>{},this._pointerBlurEvent=r=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=qr()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=r=>{},this._gamepadDisconnectedEvent=r=>{},this._eventPrefix=k.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 ${se[e]}`;e>=se.DualShock&&e<=se.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(r===void 0)throw`Unable to find input ${i} for device ${se[e]} in slot ${t}`;return i===de.Move&&k.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}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||this===void 0?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,r=t[s];if(r)for(let n=0;n<r.length;n++)r[n]=0}}this._elementToAttachTo=e,this._elementToAttachTo.tabIndex=this._elementToAttachTo.tabIndex!==-1?this._elementToAttachTo.tabIndex:this._engine.canvasTabIndex,this._handleKeyActions(),this._handlePointerActions(),this._handleGamepadActions(),this._eventsAttached=!0,this._checkForConnectedDevices()}}_disableEvents(){this._elementToAttachTo&&(this._elementToAttachTo.removeEventListener("blur",this._keyboardBlurEvent),this._elementToAttachTo.removeEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.removeEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.removeEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.removeEventListener(this._wheelEventName,this._pointerWheelEvent),window.removeEventListener("gamepadconnected",this._gamepadConnectedEvent),window.removeEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)),this._pointerInputClearObserver&&this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver),this._eventsAttached=!1}_checkForConnectedDevices(){if(navigator.getGamepads){const e=navigator.getGamepads();for(const t of e)t&&this._addGamePad(t)}typeof matchMedia=="function"&&matchMedia("(pointer:fine)").matches&&this._addPointerDevice(se.Mouse,0,0,0)}_addGamePad(e){const t=this._getGamepadDeviceType(e.id),i=e.index;this._gamepads=this._gamepads||new Array(e.index+1),this._registerDevice(t,i,e.buttons.length+e.axes.length),this._gamepads[i]=t}_addPointerDevice(e,t,i,s){this._pointerActive||(this._pointerActive=!0),this._registerDevice(e,t,Ao);const r=this._inputs[e][t];r[0]=i,r[1]=s}_registerDevice(e,t,i){if(t===void 0)throw`Unable to register device ${se[e]} to undefined slot.`;if(this._inputs[e]||(this._inputs[e]={}),!this._inputs[e][t]){const s=new Array(i);s.fill(0),this._inputs[e][t]=s,this._onDeviceConnected(e,t)}}_unregisterDevice(e,t){this._inputs[e][t]&&(delete this._inputs[e][t],this._onDeviceDisconnected(e,t))}_handleKeyActions(){this._keyboardDownEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(se.Keyboard,0,To));const t=this._inputs[se.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(se.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(se.Keyboard,0,To));const t=this._inputs[se.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 r=Es.CreateDeviceEvent(se.Keyboard,0,s,0,this,this._elementToAttachTo);t[s]=0,this._onInputChanged(se.Keyboard,0,r)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(se.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[se.Keyboard][0];for(let t=0;t<e.length;t++)if(e[t]!==0){e[t]=0;const i=Es.CreateDeviceEvent(se.Keyboard,0,t,0,this,this._elementToAttachTo);this._onInputChanged(se.Keyboard,0,i)}this._usingMacOS&&this._metaKeys.splice(0,this._metaKeys.length)}},this._elementToAttachTo.addEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.addEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.addEventListener("blur",this._keyboardBlurEvent)}_handlePointerActions(){this._maxTouchPoints=qr()&&navigator.maxTouchPoints||2,this._activeTouchIds||(this._activeTouchIds=new Array(this._maxTouchPoints));for(let i=0;i<this._maxTouchPoints;i++)this._activeTouchIds[i]=-1;this._pointerMoveEvent=i=>{const s=this._getPointerType(i),r=s===se.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);this._inputs[s]||(this._inputs[s]={}),this._inputs[s][r]||this._addPointerDevice(s,r,i.clientX,i.clientY);const n=this._inputs[s][r];if(n){const a=i;a.inputIndex=de.Move,n[de.Horizontal]=i.clientX,n[de.Vertical]=i.clientY,i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(s,r,a),!this._usingSafari&&i.button!==-1&&(a.inputIndex=i.button+2,n[i.button+2]=n[i.button+2]?0:1,this._onInputChanged(s,r,a))}},this._pointerDownEvent=i=>{const s=this._getPointerType(i);let r=s===se.Mouse?0:i.pointerId;if(s===se.Touch){const a=this._activeTouchIds.indexOf(-1);if(a>=0)r=a,this._activeTouchIds[a]=i.pointerId;else{k.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[s]||(this._inputs[s]={}),this._inputs[s][r]?s===se.Touch&&this._onDeviceConnected(s,r):this._addPointerDevice(s,r,i.clientX,i.clientY);const n=this._inputs[s][r];if(n){const a=n[de.Horizontal],o=n[de.Vertical];if(s===se.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{}n[de.Horizontal]=i.clientX,n[de.Vertical]=i.clientY,n[i.button+2]=1;const h=i;h.inputIndex=i.button+2,this._onInputChanged(s,r,h),(a!==i.clientX||o!==i.clientY)&&(h.inputIndex=de.Move,this._onInputChanged(s,r,h))}},this._pointerUpEvent=i=>{var s,r,n,a,o;const h=this._getPointerType(i),c=h===se.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(h===se.Touch){if(c===-1)return;this._activeTouchIds[c]=-1}const u=(s=this._inputs[h])===null||s===void 0?void 0:s[c];if(u&&u[i.button+2]!==0){const f=u[de.Horizontal],d=u[de.Vertical];u[de.Horizontal]=i.clientX,u[de.Vertical]=i.clientY,u[i.button+2]=0;const _=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(f!==i.clientX||d!==i.clientY)&&(_.inputIndex=de.Move,this._onInputChanged(h,c,_)),_.inputIndex=i.button+2,h===se.Mouse&&this._mouseId>=0&&(!((n=(r=this._elementToAttachTo).hasPointerCapture)===null||n===void 0)&&n.call(r,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&(!((o=(a=this._elementToAttachTo).hasPointerCapture)===null||o===void 0)&&o.call(a,i.pointerId))&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(h,c,_),h===se.Touch&&this._onDeviceDisconnected(h,c)}},this._pointerCancelEvent=i=>{var s,r,n,a;if(i.pointerType==="mouse"){const o=this._inputs[se.Mouse][0];this._mouseId>=0&&(!((r=(s=this._elementToAttachTo).hasPointerCapture)===null||r===void 0)&&r.call(s,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let h=de.LeftClick;h<=de.BrowserForward;h++)if(o[h]===1){o[h]=0;const c=Es.CreateDeviceEvent(se.Mouse,0,h,0,this,this._elementToAttachTo);this._onInputChanged(se.Mouse,0,c)}}else{const o=this._activeTouchIds.indexOf(i.pointerId);!((a=(n=this._elementToAttachTo).hasPointerCapture)===null||a===void 0)&&a.call(n,i.pointerId)&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._inputs[se.Touch][o][de.LeftClick]=0;const h=Es.CreateDeviceEvent(se.Touch,o,de.LeftClick,0,this,this._elementToAttachTo,i.pointerId);this._onInputChanged(se.Touch,o,h),this._activeTouchIds[o]=-1,this._onDeviceDisconnected(se.Touch,o)}},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,r,n,a;if(this.isDeviceAvailable(se.Mouse)){const o=this._inputs[se.Mouse][0];this._mouseId>=0&&(!((s=(i=this._elementToAttachTo).hasPointerCapture)===null||s===void 0)&&s.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let h=de.LeftClick;h<=de.BrowserForward;h++)if(o[h]===1){o[h]=0;const c=Es.CreateDeviceEvent(se.Mouse,0,h,0,this,this._elementToAttachTo);this._onInputChanged(se.Mouse,0,c)}}if(this.isDeviceAvailable(se.Touch)){const o=this._inputs[se.Touch];for(let h=0;h<this._activeTouchIds.length;h++){const c=this._activeTouchIds[h];if(!((n=(r=this._elementToAttachTo).hasPointerCapture)===null||n===void 0)&&n.call(r,c)&&this._elementToAttachTo.releasePointerCapture(c),c!==-1&&((a=o[h])===null||a===void 0?void 0:a[de.LeftClick])===1){o[h][de.LeftClick]=0;const u=Es.CreateDeviceEvent(se.Touch,h,de.LeftClick,0,this,this._elementToAttachTo,c);this._onInputChanged(se.Touch,h,u),this._activeTouchIds[h]=-1,this._onDeviceDisconnected(se.Touch,h)}}}},this._pointerWheelEvent=i=>{const s=se.Mouse,r=0;this._inputs[s]||(this._inputs[s]=[]),this._inputs[s][r]||(this._pointerActive=!0,this._registerDevice(s,r,Ao));const n=this._inputs[s][r];if(n){n[de.MouseWheelX]=i.deltaX||0,n[de.MouseWheelY]=i.deltaY||i.wheelDelta||0,n[de.MouseWheelZ]=i.deltaZ||0;const a=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),n[de.MouseWheelX]!==0&&(a.inputIndex=de.MouseWheelX,this._onInputChanged(s,r,a)),n[de.MouseWheelY]!==0&&(a.inputIndex=de.MouseWheelY,this._onInputChanged(s,r,a)),n[de.MouseWheelZ]!==0&&(a.inputIndex=de.MouseWheelZ,this._onInputChanged(s,r,a))}},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(se.Mouse)){const i=this._inputs[se.Mouse][0];i[de.MouseWheelX]=0,i[de.MouseWheelY]=0,i[de.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 r=this._inputs[e][t];i>=s.buttons.length?r[i]=s.axes[i-s.buttons.length].valueOf():r[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return e.indexOf("054c")!==-1?e.indexOf("0ce6")!==-1?se.DualSense:se.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?se.Xbox:e.indexOf("057e")!==-1?se.Switch:se.Generic}_getPointerType(e){let t=se.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=se.Touch),t}}class vo{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new B,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class Hh{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=n=>{for(let a=0;a<this._devices.length;a++){const o=this._devices[a];for(const h in o){const c=+h;n._addDevice(new vo(this._deviceInputSystem,a,c))}}this._registeredManagers.push(n)},this.unregisterManager=n=>{const a=this._registeredManagers.indexOf(n);a>-1&&this._registeredManagers.splice(a,1)};const t=Object.keys(se).length/2;this._devices=new Array(t);const i=(n,a)=>{this._devices[n]||(this._devices[n]=new Array),this._devices[n][a]||(this._devices[n][a]=a);for(const o of this._registeredManagers){const h=new vo(this._deviceInputSystem,n,a);o._addDevice(h)}},s=(n,a)=>{var o;!((o=this._devices[n])===null||o===void 0)&&o[a]&&delete this._devices[n][a];for(const h of this._registeredManagers)h._removeDevice(n,a)},r=(n,a,o)=>{if(o)for(const h of this._registeredManagers)h._onInputChanged(n,a,o)};typeof _native<"u"?this._deviceInputSystem=new kh(i,s,r):this._deviceInputSystem=new Gh(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class Wh{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(se).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new Hh(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new B(i=>{for(const s of this._devices)if(s)for(const r of s)r&&this.onDeviceConnectedObservable.notifyObserver(i,r)}),this.onDeviceDisconnectedObservable=new B,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var i,s;const r=(i=this._devices[e])===null||i===void 0?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(r),!((s=this._devices[e])===null||s===void 0)&&s[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var s,r;(r=(s=this._devices[e])===null||s===void 0?void 0:s[t])===null||r===void 0||r.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case se.Keyboard:case se.Mouse:this._firstDevice[e]=0;break;case se.Touch:case se.DualSense:case se.DualShock:case se.Xbox:case se.Switch:case se.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t){for(let i=0;i<t.length;i++)if(t[i]){this._firstDevice[e]=i;break}}break}}}}class So{constructor(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}get singleClick(){return this._singleClick}get doubleClick(){return this._doubleClick}get hasSwiped(){return this._hasSwiped}get ignore(){return this._ignore}set singleClick(e){this._singleClick=e}set doubleClick(e){this._doubleClick=e}set hasSwiped(e){this._hasSwiped=e}set ignore(e){this._ignore=e}}class it{constructor(e){this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._totalPointersPressed=0,this._doubleClickOccured=!1,this._isSwiping=!1,this._swipeButtonPressed=-1,this._skipPointerTap=!1,this._isMultiTouchGesture=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new ae(0,0),this._previousStartingPointerPosition=new ae(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._movePointerInfo=null,this._cameraObserverCount=0,this._delayedClicks=[null,null,null,null,null],this._deviceSourceManager=null,this._scene=e||Ee.LastCreatedScene,this._scene}get meshUnderPointer(){return this._movePointerInfo&&(this._movePointerInfo._generatePickInfo(),this._movePointerInfo=null),this._pointerOverMesh}getMeshUnderPointerByPointerId(e){return this._meshUnderPointerId[e]||null}get unTranslatedPointer(){return new ae(this._unTranslatedPointerX,this._unTranslatedPointerY)}get pointerX(){return this._pointerX}set pointerX(e){this._pointerX=e}get pointerY(){return this._pointerY}set pointerY(e){this._pointerY=e}_updatePointerPosition(e){const t=this._scene.getEngine().getInputElementClientRect();t&&(this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)}_processPointerMove(e,t){const i=this._scene,s=i.getEngine(),r=s.getInputElement();r&&(r.tabIndex=s.canvasTabIndex,i.doNotHandleCursors||(r.style.cursor=i.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,i);for(const o of i._pointerMoveStage){e=e||this._pickMove(t);const h=!!(e!=null&&e.pickedMesh);e=o.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,h,r)}const n=t.inputIndex>=de.MouseWheelX&&t.inputIndex<=de.MouseWheelZ?ce.POINTERWHEEL:ce.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n));let a;e?(a=new Fi(n,t,e),this._setRayOnPointerInfo(e,t)):(a=new Fi(n,t,null,this),this._movePointerInfo=a),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(a,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,M.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,r=new Vh(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.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 r=i.getEngine().getInputElement();if(e!=null&&e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&r&&this._pointerOverMesh){const n=this._pointerOverMesh._getActionManagerForTrigger();n&&n.hasPointerTriggers&&(r.style.cursor=n.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=de.Move,!this._checkPrePointerObservable(e,i,ce.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,ce.POINTERDOWN)&&this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e!=null&&e.pickedMesh){this._pickedDownMesh=e.pickedMesh;const n=e.pickedMesh._getActionManagerForTrigger();if(n){if(n.hasPickTriggers)switch(n.processTrigger(5,St.CreateNew(e.pickedMesh,t)),t.button){case 0:n.processTrigger(2,St.CreateNew(e.pickedMesh,t));break;case 1:n.processTrigger(4,St.CreateNew(e.pickedMesh,t));break;case 2:n.processTrigger(3,St.CreateNew(e.pickedMesh,t));break}n.hasSpecificTrigger(8)&&window.setTimeout(()=>{const a=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,o=>o.isPickable&&o.isVisible&&o.isReady()&&o.actionManager&&o.actionManager.hasSpecificTrigger(8)&&o===this._pickedDownMesh,!1,i.cameraToUseForPointers);a!=null&&a.pickedMesh&&n&&this._totalPointersPressed!==0&&Date.now()-this._startingPointerTime>it.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,n.processTrigger(8,St.CreateNew(a.pickedMesh,t)))},it.LongPressDelay)}}else for(const n of i._pointerDownStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=ce.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new Fi(r,t,e),this._setRayOnPointerInfo(e,t)):s=new Fi(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=de.Move;const r=new So;i?r.doubleClick=!0:r.singleClick=!0,!this._checkPrePointerObservable(e,s,ce.POINTERUP)&&this._processPointerUp(e,s,r)}_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 n=ce.POINTERPICK,a=new Fi(n,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(a,n)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,St.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,St.CreateNew(e.pickedMesh,t,e));const n=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&n&&n.processTrigger(6,St.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const r=this._pickedDownMesh._getActionManagerForTrigger(16);r&&r.processTrigger(16,St.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new Fi(ce.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,ce.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,ce.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let n=0;if(i.singleClick?n=ce.POINTERTAP:i.doubleClick&&(n=ce.POINTERDOUBLETAP),n){const a=new Fi(n,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(n)&&s.onPointerObservable.notifyObservers(a,n)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const r=this._scene,n=r.getEngine();s||(s=n.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new Wh(n),this._initActionManager=a=>{if(!this._meshPickProceed){const o=r.skipPointerUpPicking||r._registeredActions===0&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers);this._currentPickResult=o,o&&(a=o.hit&&o.pickedMesh?o.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return a},this._delayedSimpleClick=(a,o,h)=>{if((Date.now()-this._previousStartingPointerTime>it.DoubleClickDelay&&!this._doubleClickOccured||a!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,o.singleClick=!0,o.ignore=!1,this._delayedClicks[a])){const c=this._delayedClicks[a].evt,u=ce.POINTERTAP,f=new Fi(u,c,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(u)&&r.onPointerObservable.notifyObservers(f,u),this._delayedClicks[a]=null}},this._initClickEvent=(a,o,h,c)=>{var u,f;const d=new So;this._currentPickResult=null;let _=null,p=a.hasSpecificMask(ce.POINTERPICK)||o.hasSpecificMask(ce.POINTERPICK)||a.hasSpecificMask(ce.POINTERTAP)||o.hasSpecificMask(ce.POINTERTAP)||a.hasSpecificMask(ce.POINTERDOUBLETAP)||o.hasSpecificMask(ce.POINTERDOUBLETAP);!p&&Qt&&(_=this._initActionManager(_,d),_&&(p=_.hasPickTriggers));let m=!1;if(p){const T=h.button;if(d.hasSwiped=this._isPointerSwiping(),!d.hasSwiped){let S=!it.ExclusiveDoubleClickMode;if(S||(S=!a.hasSpecificMask(ce.POINTERDOUBLETAP)&&!o.hasSpecificMask(ce.POINTERDOUBLETAP),S&&!Qt.HasSpecificTrigger(6)&&(_=this._initActionManager(_,d),_&&(S=!_.hasSpecificTrigger(6)))),S)(Date.now()-this._previousStartingPointerTime>it.DoubleClickDelay||T!==this._previousButtonPressed)&&(d.singleClick=!0,c(d,this._currentPickResult),m=!0);else{const b={evt:h,clickInfo:d,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,T,d,c),it.DoubleClickDelay)};this._delayedClicks[T]=b}let x=a.hasSpecificMask(ce.POINTERDOUBLETAP)||o.hasSpecificMask(ce.POINTERDOUBLETAP);!x&&Qt.HasSpecificTrigger(6)&&(_=this._initActionManager(_,d),_&&(x=_.hasSpecificTrigger(6))),x&&(T===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime<it.DoubleClickDelay&&!this._doubleClickOccured?(!d.hasSwiped&&!this._isPointerSwiping()?(this._previousStartingPointerTime=0,this._doubleClickOccured=!0,d.doubleClick=!0,d.ignore=!1,it.ExclusiveDoubleClickMode&&this._delayedClicks[T]&&(clearTimeout((u=this._delayedClicks[T])===null||u===void 0?void 0:u.timeoutId),this._delayedClicks[T]=null),c(d,this._currentPickResult)):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=T,it.ExclusiveDoubleClickMode?(this._delayedClicks[T]&&(clearTimeout((f=this._delayedClicks[T])===null||f===void 0?void 0:f.timeoutId),this._delayedClicks[T]=null),c(d,this._previousPickResult)):c(d,this._currentPickResult)),m=!0):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=T))}}m||c(d,this._currentPickResult)},this._onPointerMove=a=>{if(this._updatePointerPosition(a),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>it.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>it.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,a,a.inputIndex>=de.MouseWheelX&&a.inputIndex<=de.MouseWheelZ?ce.POINTERWHEEL:ce.POINTERMOVE)||!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking){this._processPointerMove(new br,a);return}r.pointerMovePredicate||(r.pointerMovePredicate=h=>h.isPickable&&h.isVisible&&h.isReady()&&h.isEnabled()&&(h.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||h._getActionManagerForTrigger()!==null)&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&h.layerMask)!==0));const o=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(a):null;this._processPointerMove(o,a)},this._onPointerDown=a=>{var o;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,it.ExclusiveDoubleClickMode){for(let c=0;c<this._delayedClicks.length;c++)if(this._delayedClicks[c])if(a.button===c)clearTimeout((o=this._delayedClicks[c])===null||o===void 0?void 0:o.timeoutId);else{const u=this._delayedClicks[c].clickInfo;this._doubleClickOccured=!1,u.singleClick=!0,u.ignore=!1;const f=this._delayedClicks[c].evt,d=ce.POINTERTAP,_=new Fi(d,f,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(d)&&r.onPointerObservable.notifyObservers(_,d),this._delayedClicks[c]=null}}if(this._updatePointerPosition(a),this._swipeButtonPressed===-1&&(this._swipeButtonPressed=a.button),r.preventDefaultOnPointerDown&&s&&(a.preventDefault(),s.focus()),this._startingPointerPosition.x=this._pointerX,this._startingPointerPosition.y=this._pointerY,this._startingPointerTime=Date.now(),this._checkPrePointerObservable(null,a,ce.POINTERDOWN)||!r.cameraToUseForPointers&&!r.activeCamera)return;this._pointerCaptures[a.pointerId]=!0,r.pointerDownPredicate||(r.pointerDownPredicate=c=>c.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&c.layerMask)!==0)),this._pickedDownMesh=null;let h;r.skipPointerDownPicking||r._registeredActions===0&&!this._checkForPicking()&&!r.onPointerDown?h=new br:h=r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers),this._processPointerDown(h,a)},this._onPointerUp=a=>{this._totalPointersPressed!==0&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(a),r.preventDefaultOnPointerUp&&s&&(a.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,a,(o,h)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!o.ignore)){if(this._checkPrePointerObservable(null,a,ce.POINTERUP)){this._swipeButtonPressed===a.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),a.buttons===0&&(this._pointerCaptures[a.pointerId]=!1);return}o.hasSwiped||(o.singleClick&&r.onPrePointerObservable.hasSpecificMask(ce.POINTERTAP)&&this._checkPrePointerObservable(null,a,ce.POINTERTAP)&&(this._skipPointerTap=!0),o.doubleClick&&r.onPrePointerObservable.hasSpecificMask(ce.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,a,ce.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[a.pointerId]){this._swipeButtonPressed===a.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}a.buttons===0&&(this._pointerCaptures[a.pointerId]=!1),!(!r.cameraToUseForPointers&&!r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=c=>c.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&c.layerMask)!==0)),!this._meshPickProceed&&(Qt&&Qt.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,o),h||(h=this._currentPickResult),this._processPointerUp(h,a,o),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===a.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=a=>{const o=Hs.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const h=new fo(o,a);if(r.onPreKeyboardObservable.notifyObservers(h,o),h.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const h=new Fn(o,a);r.onKeyboardObservable.notifyObservers(h,o)}r.actionManager&&r.actionManager.processTrigger(14,St.CreateNewFromScene(r,a))},this._onKeyUp=a=>{const o=Hs.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const h=new fo(o,a);if(r.onPreKeyboardObservable.notifyObservers(h,o),h.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const h=new Fn(o,a);r.onKeyboardObservable.notifyObservers(h,o)}r.actionManager&&r.actionManager.processTrigger(15,St.CreateNewFromScene(r,a))},this._deviceSourceManager.onDeviceConnectedObservable.add(a=>{a.deviceType===se.Mouse?a.onInputChangedObservable.add(o=>{o.inputIndex===de.LeftClick||o.inputIndex===de.MiddleClick||o.inputIndex===de.RightClick||o.inputIndex===de.BrowserBack||o.inputIndex===de.BrowserForward?t&&a.getInput(o.inputIndex)===1?this._onPointerDown(o):e&&a.getInput(o.inputIndex)===0&&this._onPointerUp(o):i&&(o.inputIndex===de.Move?this._onPointerMove(o):(o.inputIndex===de.MouseWheelX||o.inputIndex===de.MouseWheelY||o.inputIndex===de.MouseWheelZ)&&this._onPointerMove(o))}):a.deviceType===se.Touch?a.onInputChangedObservable.add(o=>{o.inputIndex===de.LeftClick&&(t&&a.getInput(o.inputIndex)===1?(this._onPointerDown(o),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&a.getInput(o.inputIndex)===0&&(this._onPointerUp(o),this._totalPointersPressed===0&&(this._isMultiTouchGesture=!1))),i&&o.inputIndex===de.Move&&this._onPointerMove(o)}):a.deviceType===se.Keyboard&&a.onInputChangedObservable.add(o=>{o.type==="keydown"?this._onKeyDown(o):o.type==="keyup"&&this._onKeyUp(o)})}),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 r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(10),n&&n.processTrigger(10,St.CreateNew(r,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,St.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]}}it.DragMovementThreshold=10,it.LongPressDelay=500,it.DoubleClickDelay=300,it.ExclusiveDoubleClickMode=!1;class Ci{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){Ci.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){Ci.Enabled&&(this._startMonitoringTime=ii.Now)}endMonitoring(e=!0){if(!Ci.Enabled)return;e&&this.fetchNewFrame();const t=ii.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=ii.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}Ci.Enabled=!0;class Ro{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}Ro._UniqueIdCounter=1;class Be{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}Be.FALLOFF_DEFAULT=0,Be.FALLOFF_PHYSICAL=1,Be.FALLOFF_GLTF=2,Be.FALLOFF_STANDARD=3,Be.LIGHTMAP_DEFAULT=0,Be.LIGHTMAP_SPECULAR=1,Be.LIGHTMAP_SHADOWSONLY=2,Be.INTENSITYMODE_AUTOMATIC=0,Be.INTENSITYMODE_LUMINOUSPOWER=1,Be.INTENSITYMODE_LUMINOUSINTENSITY=2,Be.INTENSITYMODE_ILLUMINANCE=3,Be.INTENSITYMODE_LUMINANCE=4,Be.LIGHTTYPEID_POINTLIGHT=0,Be.LIGHTTYPEID_DIRECTIONALLIGHT=1,Be.LIGHTTYPEID_SPOTLIGHT=2,Be.LIGHTTYPEID_HEMISPHERICLIGHT=3;class zh{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var bi;(function(l){l[l.BackwardCompatible=0]="BackwardCompatible",l[l.Intermediate=1]="Intermediate",l[l.Aggressive=2]="Aggressive"})(bi||(bi={}));class Ie extends hi{static DefaultMaterialFactory(e){throw fe("StandardMaterial")}static CollisionCoordinatorFactory(){throw fe("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 bi.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case bi.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case bi.Aggressive: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 it.DragMovementThreshold}static set DragMovementThreshold(e){it.DragMovementThreshold=e}static get LongPressDelay(){return it.LongPressDelay}static set LongPressDelay(e){it.LongPressDelay=e}static get DoubleClickDelay(){return it.DoubleClickDelay}static set DoubleClickDelay(e){it.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return it.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){it.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){var s;const r=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:(s=this.activeCamera.globalPosition)!==null&&s!==void 0?s:this.activeCamera.devicePosition,n=this.useRightHandedSystem===(this._mirroredCameraPosition!=null);return D.Vector4[0].set(r.x,r.y,r.z,n?-1:1),e&&(i?e.setFloat3(t,D.Vector4[0].x,D.Vector4[0].y,D.Vector4[0].z):e.setVector4(t,D.Vector4[0])),D.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=ja(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=Ie.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=Ie.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 it(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new ge(.2,.2,.3,1),this.ambientColor=new z(0,0,0),this.environmentIntensity=1,this._performancePriority=bi.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new B,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=new Array,this.onDisposeObservable=new B,this._onDisposeObserver=null,this.onBeforeRenderObservable=new B,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new B,this.onAfterRenderCameraObservable=new B,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new B,this.onAfterAnimationsObservable=new B,this.onBeforeDrawPhaseObservable=new B,this.onAfterDrawPhaseObservable=new B,this.onReadyObservable=new B,this.onBeforeCameraRenderObservable=new B,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new B,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new B,this.onAfterActiveMeshesEvaluationObservable=new B,this.onBeforeParticlesRenderingObservable=new B,this.onAfterParticlesRenderingObservable=new B,this.onDataLoadedObservable=new B,this.onNewCameraAddedObservable=new B,this.onCameraRemovedObservable=new B,this.onNewLightAddedObservable=new B,this.onLightRemovedObservable=new B,this.onNewGeometryAddedObservable=new B,this.onGeometryRemovedObservable=new B,this.onNewTransformNodeAddedObservable=new B,this.onTransformNodeRemovedObservable=new B,this.onNewMeshAddedObservable=new B,this.onMeshRemovedObservable=new B,this.onNewSkeletonAddedObservable=new B,this.onSkeletonRemovedObservable=new B,this.onNewMaterialAddedObservable=new B,this.onNewMultiMaterialAddedObservable=new B,this.onMaterialRemovedObservable=new B,this.onMultiMaterialRemovedObservable=new B,this.onNewTextureAddedObservable=new B,this.onTextureRemovedObservable=new B,this.onBeforeRenderTargetsRenderObservable=new B,this.onAfterRenderTargetsRenderObservable=new B,this.onBeforeStepObservable=new B,this.onAfterStepObservable=new B,this.onActiveCameraChanged=new B,this.onActiveCamerasChanged=new B,this.onBeforeRenderingGroupObservable=new B,this.onAfterRenderingGroupObservable=new B,this.onMeshImportedObservable=new B,this.onAnimationFileImportedObservable=new B,this._registeredForLateAnimationBindings=new gs(256),this._pointerPickingConfiguration=new zh,this.onPrePointerObservable=new B,this.onPointerObservable=new B,this.onPreKeyboardObservable=new B,this.onKeyboardObservable=new B,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Ie.FOGMODE_NONE,this.fogColor=new z(.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 E(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=new Array,this.importedMeshesFiles=new Array,this.probesEnabled=!0,this._meshesForIntersections=new gs(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new Ci,this._activeIndices=new Ci,this._activeParticles=new Ci,this._activeBones=new Ci,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 gs(256),this._materialsRenderTargets=new gs(256),this._activeParticleSystems=new vt(256),this._activeSkeletons=new gs(32),this._softwareSkinnedMeshes=new gs(32),this._activeAnimatables=new Array,this._transformMatrix=M.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=tt.Create(),this._beforeClearStage=tt.Create(),this._beforeRenderTargetClearStage=tt.Create(),this._gatherRenderTargetsStage=tt.Create(),this._gatherActiveCameraRenderTargetsStage=tt.Create(),this._isReadyForMeshStage=tt.Create(),this._beforeEvaluateActiveMeshStage=tt.Create(),this._evaluateSubMeshStage=tt.Create(),this._preActiveMeshStage=tt.Create(),this._cameraDrawRenderTargetStage=tt.Create(),this._beforeCameraDrawStage=tt.Create(),this._beforeRenderTargetDrawStage=tt.Create(),this._beforeRenderingGroupDrawStage=tt.Create(),this._beforeRenderingMeshStage=tt.Create(),this._afterRenderingMeshStage=tt.Create(),this._afterRenderingGroupDrawStage=tt.Create(),this._afterCameraDrawStage=tt.Create(),this._afterCameraPostProcessStage=tt.Create(),this._afterRenderTargetDrawStage=tt.Create(),this._afterRenderTargetPostProcessStage=tt.Create(),this._afterRenderStage=tt.Create(),this._pointerMoveStage=tt.Create(),this._pointerDownStage=tt.Create(),this._pointerUpStage=tt.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=new Array;const i=Object.assign({useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1},t);this._engine=e||Ee.LastCreatedEngine,i.virtual?this._engine._virtualScenes.push(this):(Ee._LastCreatedScene=this,this._engine.scenes.push(this)),this._uid=null,this._renderingManager=new Pt(this),Nn&&(this.postProcessManager=new Nn(this)),Mt()&&this.attachControl(),this._createUbo(),Se&&(this._imageProcessingConfiguration=new Se),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,(!t||!t.virtual)&&this._engine.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=this._getDefaultMeshCandidates.bind(this),this.getActiveSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this),this.getIntersectingSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this),this.getCollidingSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return 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 t,i,s;if(this._isDisposed)return!1;let r;const n=this.getEngine(),a=n.currentRenderPassId;n.currentRenderPassId=(i=(t=this.activeCamera)===null||t===void 0?void 0:t.renderPassId)!==null&&i!==void 0?i:a;let o=!0;for(this._pendingData.length>0&&(o=!1),(s=this.prePassRenderer)===null||s===void 0||s.update(),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),r=0;r<this.meshes.length;r++){const h=this.meshes[r];if(!h.subMeshes||h.subMeshes.length===0)continue;if(!h.isReady(!0)){o=!1;continue}const c=h.hasThinInstances||h.getClassName()==="InstancedMesh"||h.getClassName()==="InstancedLinesMesh"||n.getCaps().instancedArrays&&h.instances.length>0;for(const f of this._isReadyForMeshStage)f.action(h,c)||(o=!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(r=0;r<this._materialsRenderTargets.length;++r)this._materialsRenderTargets.data[r].isReadyForRendering()||(o=!1);for(r=0;r<this.geometries.length;r++)this.geometries[r].delayLoadState===2&&(o=!1);if(this.activeCameras&&this.activeCameras.length>0)for(const h of this.activeCameras)h.isReady(!0)||(o=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(o=!1));for(const h of this.particleSystems)h.isReady()||(o=!1);if(this.layers)for(const h of this.layers)h.isReady()||(o=!1);return n.areAllEffectsReady()||(o=!1),n.currentRenderPassId=a,o}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=ii.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?li.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=li.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 q(this._engine,void 0,!1,e??"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return Ro.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&&t<this.materials.length){if(t!==this.materials.length-1){const i=this.materials[this.materials.length-1];this.materials[t]=i,i._indexInSceneMaterialArray=t}e._indexInSceneMaterialArray=-1,this.materials.pop()}return this.onMaterialRemovedObservable.notifyObservers(e),t}removeActionManager(e){const t=this.actionManagers.indexOf(e);return t!==-1&&this.actionManagers.splice(t,1),t}removeTexture(e){const t=this.textures.indexOf(e);return t!==-1&&this.textures.splice(t,1),this.onTextureRemovedObservable.notifyObservers(e),t}addLight(e){if(!this._blockEntityCollection){this.lights.push(e),this.sortLightsByPriority(),e.parent||e._addToSceneRootNodes();for(const t of this.meshes)t.lightSources.indexOf(e)===-1&&(t.lightSources.push(e),t._resyncLightSources());this.onNewLightAddedObservable.notifyObservers(e)}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(Be.CompareLightsPriority)}addCamera(e){this._blockEntityCollection||(this.cameras.push(e),this.onNewCameraAddedObservable.notifyObservers(e),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),this.onNewSkeletonAddedObservable.notifyObservers(e))}addParticleSystem(e){this._blockEntityCollection||this.particleSystems.push(e)}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||this.animationGroups.push(e)}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),this.onNewMultiMaterialAddedObservable.notifyObservers(e))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneMaterialArray!==-1||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),this.onNewMaterialAddedObservable.notifyObservers(e))}addMorphTargetManager(e){this._blockEntityCollection||this.morphTargetManagers.push(e)}addGeometry(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))}addActionManager(e){this.actionManagers.push(e)}addTexture(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))}switchActiveCamera(e,t=!0){this._engine.getInputElement()&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())}setActiveCameraById(e){const t=this.getCameraById(e);return t?(this.activeCamera=t,t):null}setActiveCameraByName(e){const t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null}getAnimationGroupByName(e){for(let t=0;t<this.animationGroups.length;t++)if(this.animationGroups[t].name===e)return this.animationGroups[t];return null}_getMaterial(e,t){for(let i=0;i<this.materials.length;i++){const s=this.materials[i];if(t(s))return s}if(e)for(let i=0;i<this.multiMaterials.length;i++){const s=this.multiMaterials[i];if(t(s))return s}return null}getMaterialByUniqueID(e,t=!1){return this._getMaterial(t,i=>i.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<this.textures.length;t++)if(this.textures[t].uniqueId===e)return this.textures[t];return null}getTextureByName(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].name===e)return this.textures[t];return null}getCameraById(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null}getCameraByUniqueId(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null}getCameraByName(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null}getBoneById(e){for(let t=0;t<this.skeletons.length;t++){const i=this.skeletons[t];for(let s=0;s<i.bones.length;s++)if(i.bones[s].id===e)return i.bones[s]}return null}getBoneByName(e){for(let t=0;t<this.skeletons.length;t++){const i=this.skeletons[t];for(let s=0;s<i.bones.length;s++)if(i.bones[s].name===e)return i.bones[s]}return null}getLightByName(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null}getLightById(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null}getLightByUniqueId(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];return null}getParticleSystemById(e){for(let t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null}getGeometryById(e){for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].id===e)return this.geometries[t];return null}_getGeometryByUniqueId(e){if(this._geometriesByUniqueId){const t=this._geometriesByUniqueId[e];if(t!==void 0)return this.geometries[t]}else for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].uniqueId===e)return this.geometries[t];return null}pushGeometry(e,t){return!t&&this._getGeometryByUniqueId(e.uniqueId)?!1:(this.addGeometry(e),this.onNewGeometryAddedObservable.notifyObservers(e),!0)}removeGeometry(e){let t;if(this._geometriesByUniqueId){if(t=this._geometriesByUniqueId[e.uniqueId],t===void 0)return!1}else if(t=this.geometries.indexOf(e),t<0)return!1;if(t!==this.geometries.length-1){const i=this.geometries[this.geometries.length-1];i&&(this.geometries[t]=i,this._geometriesByUniqueId&&(this._geometriesByUniqueId[i.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0}getGeometries(){return this.geometries}getMeshById(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null}getMeshesById(e){return this.meshes.filter(function(t){return t.id===e})}getTransformNodeById(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getTransformNodeByUniqueId(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].uniqueId===e)return this.transformNodes[t];return null}getTransformNodesById(e){return this.transformNodes.filter(function(t){return t.id===e})}getMeshByUniqueId(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null}getLastMeshById(e){for(let t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const r=this.getCameraById(e);if(r)return r;const n=this.getBoneById(e);return n||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const s=this.getLightByName(e);if(s)return s;const r=this.getCameraByName(e);if(r)return r;const n=this.getBoneByName(e);return n||null}getMeshByName(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null}getTransformNodeByName(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].name===e)return this.transformNodes[t];return null}getLastSkeletonById(e){for(let t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].uniqueId===e)return this.skeletons[t];return null}getSkeletonById(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByName(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null}getMorphTargetManagerById(e){for(let t=0;t<this.morphTargetManagers.length;t++)if(this.morphTargetManagers[t].uniqueId===e)return this.morphTargetManagers[t];return null}getMorphTargetById(e){for(let t=0;t<this.morphTargetManagers.length;++t){const i=this.morphTargetManagers[t];for(let s=0;s<i.numTargets;++s){const r=i.getTarget(s);if(r.id===e)return r}}return null}getMorphTargetByName(e){for(let t=0;t<this.morphTargetManagers.length;++t){const i=this.morphTargetManagers[t];for(let s=0;s<i.numTargets;++s){const r=i.getTarget(s);if(r.name===e)return r}}return null}getPostProcessByName(e){for(let t=0;t<this.postProcesses.length;++t){const i=this.postProcesses[t];if(i.name===e)return i}return null}isActiveMesh(e){return this._activeMeshes.indexOf(e)!==-1}get uid(){return this._uid||(this._uid=k.RandomId()),this._uid}addExternalData(e,t){return this._externalData||(this._externalData=new co),this._externalData.add(e,t)}getExternalData(e){return this._externalData?this._externalData.get(e):null}getOrAddExternalDataWithFactory(e,t){return this._externalData||(this._externalData=new co),this._externalData.getOrAddWithFactory(e,t)}removeExternalData(e){return this._externalData.remove(e)}_evaluateSubMesh(e,t,i,s){if(s||e.isInFrustum(this._frustumPlanes)){for(const n of this._evaluateSubMeshStage)n.action(t,e);const r=e.getMaterial();r!=null&&(r.hasRenderTargetTextures&&r.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(r)===-1&&(this._processedMaterials.push(r),this._materialsRenderTargets.concatWithNoDuplicate(r.getRenderTargetTextures())),this._renderingManager.dispatch(e,t,r))}}freeProcessedMaterials(){this._processedMaterials.dispose()}get blockfreeActiveMeshesAndRenderingGroups(){return this._preventFreeActiveMeshesAndRenderingGroups}set blockfreeActiveMeshesAndRenderingGroups(e){this._preventFreeActiveMeshesAndRenderingGroups!==e&&(e&&(this.freeActiveMeshes(),this.freeRenderingGroups()),this._preventFreeActiveMeshesAndRenderingGroups=e)}freeActiveMeshes(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._activeMeshes.dispose(),this.activeCamera&&this.activeCamera._activeMeshes&&this.activeCamera._activeMeshes.dispose(),this.activeCameras))for(let e=0;e<this.activeCameras.length;e++){const t=this.activeCameras[e];t&&t._activeMeshes&&t._activeMeshes.dispose()}}freeRenderingGroups(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._renderingManager&&this._renderingManager.freeRenderingGroups(),this.textures))for(let e=0;e<this.textures.length;e++){const t=this.textures[e];t&&t.renderList&&t.freeRenderingGroups()}}_isInIntermediateRendering(){return this._intermediateRendering}freezeActiveMeshes(e=!1,t,i,s=!0,r=!1){return this.executeWhenReady(()=>{if(!this.activeCamera){i&&i("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,s)for(let n=0;n<this._activeMeshes.length;n++)this._activeMeshes.data[n]._freeze();t&&t()}),this}unfreezeActiveMeshes(){for(let e=0;e<this.meshes.length;e++){const t=this.meshes[e];t._internalAbstractMeshDataInfo&&(t._internalAbstractMeshDataInfo._isActive=!1)}for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._unFreeze();return this._activeMeshesFrozen=!1,this}_executeActiveContainerCleanup(e){!(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1)&&this._activeMeshesFrozen&&this._activeMeshes.length||this.onBeforeRenderObservable.addOnce(()=>e.dispose())}_evaluateActiveMeshes(){var e;if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1){this._activeMeshes.length>0&&((e=this.activeCamera)===null||e===void 0||e._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 r=0;r<s;r++)this._activeMeshes.data[r].computeWorldMatrix()}if(this._activeParticleSystems){const s=this._activeParticleSystems.length;for(let r=0;r<s;r++)this._activeParticleSystems.data[r].animate()}this._renderingManager.resetSprites();return}if(!this.activeCamera)return;this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this),this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset(),this._materialsRenderTargets.reset();for(const s of this._beforeEvaluateActiveMeshStage)s.action();const t=this.getActiveMeshCandidates(),i=t.length;for(let s=0;s<i;s++){const r=t.data[s];if(r._internalAbstractMeshDataInfo._currentLODIsUpToDate=!1,r.isBlocked||(this._totalVertices.addCount(r.getTotalVertices(),!1),!r.isReady()||!r.isEnabled()||r.scaling.hasAZeroComponent))continue;r.computeWorldMatrix(),r.actionManager&&r.actionManager.hasSpecificTriggers2(12,13)&&this._meshesForIntersections.pushNoDuplicate(r);let n=this.customLODSelector?this.customLODSelector(r,this.activeCamera):r.getLOD(this.activeCamera);if(r._internalAbstractMeshDataInfo._currentLOD=n,r._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0,n!=null&&(n!==r&&n.billboardMode!==0&&n.computeWorldMatrix(),r._preActivate(),r.isVisible&&r.visibility>0&&r.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||r.alwaysSelectAsActiveMesh||r.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(r),this.activeCamera._activeMeshes.push(r),n!==r&&n._activate(this._renderId,!1);for(const a of this._preActiveMeshStage)a.action(r);r._activate(this._renderId,!1)&&(r.isAnInstance?r._internalAbstractMeshDataInfo._actAsRegularMesh&&(n=r):n._internalAbstractMeshDataInfo._onlyForInstances=!1,n._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(r,n)),r._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let s=0;s<this.particleSystems.length;s++){const r=this.particleSystems[s];if(!r.isStarted()||!r.emitter)continue;const n=r.emitter;(!n.position||n.isEnabled())&&(this._activeParticleSystems.push(r),r.animate(),this._renderingManager.dispatchParticles(r))}this.onAfterParticlesRenderingObservable.notifyObservers(this)}}_activeMesh(e,t){this._skeletonsEnabled&&t.skeleton!==null&&t.skeleton!==void 0&&(this._activeSkeletons.pushNoDuplicate(t.skeleton)&&(t.skeleton.prepare(),this._activeBones.addCount(t.skeleton.bones.length,!1)),t.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(t));let i=e.hasInstances||e.isAnInstance||this.dispatchAllSubMeshesOfActiveMeshes||this._skipFrustumClipping||t.alwaysSelectAsActiveMesh;if(t&&t.subMeshes&&t.subMeshes.length>0){const s=this.getActiveSubMeshCandidates(t),r=s.length;i=i||r===1;for(let n=0;n<r;n++){const a=s.data[n];this._evaluateSubMesh(a,t,e,i)}}}updateTransformMatrix(e){if(this.activeCamera)if(this.activeCamera._renderingMultiview){const t=this.activeCamera._rigCameras[0],i=this.activeCamera._rigCameras[1];this.setTransformMatrix(t.getViewMatrix(),t.getProjectionMatrix(e),i.getViewMatrix(),i.getProjectionMatrix(e))}else this.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix(e))}_bindFrameBuffer(e,t=!0){e&&e._multiviewTexture?e._multiviewTexture._bindFrameBuffer():e&&e.outputRenderTarget?e.outputRenderTarget._bindFrameBuffer():this._engine._currentFrameBufferIsDefaultFrameBuffer()||this._engine.restoreDefaultFramebuffer(),t&&this._clearFrameBuffer(e)}_clearFrameBuffer(e){if(!(e&&e._multiviewTexture))if(e&&e.outputRenderTarget&&!e._renderingMultiview){const t=e.outputRenderTarget;t.onClearObservable.hasObservers()?t.onClearObservable.notifyObservers(this._engine):t.skipInitialClear||(this.autoClear&&this._engine.clear(t.clearColor||this.clearColor,!t._cleared,!0,!0),t._cleared=!0)}else this._defaultFrameBufferCleared?this._engine.clear(null,!1,!0,!0):(this._defaultFrameBufferCleared=!0,this._clear())}_renderForCamera(e,t,i=!0){var s,r,n;if(e&&e._skipRendering)return;const a=this._engine;if(this._activeCamera=e,!this.activeCamera)throw new Error("Active camera not set");if(a.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,!this.prePass&&i){let h=!0;e._renderingMultiview&&e.outputRenderTarget&&(h=e.outputRenderTarget.skipInitialClear,this.autoClear&&(this._defaultFrameBufferCleared=!1,e.outputRenderTarget.skipInitialClear=!1)),this._bindFrameBuffer(this._activeCamera),e._renderingMultiview&&e.outputRenderTarget&&(e.outputRenderTarget.skipInitialClear=h)}this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshes();for(let h=0;h<this._softwareSkinnedMeshes.length;h++){const c=this._softwareSkinnedMeshes.data[h];c.applySkeleton(c.skeleton)}this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets),e.customRenderTargets&&e.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const h of this._gatherActiveCameraRenderTargetsStage)h.action(this._renderTargets);let o=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){k.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let h=0;h<this._renderTargets.length;h++){const c=this._renderTargets.data[h];if(c._shouldRender()){this._renderId++;const u=c.activeCamera&&c.activeCamera!==this.activeCamera;c.render(u,this.dumpNextRenderTargets),o=!0}}k.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}for(const h of this._cameraDrawRenderTargetStage)o=h.action(this.activeCamera)||o;this._intermediateRendering=!1}this._engine.currentRenderPassId=(n=(r=(s=e.outputRenderTarget)===null||s===void 0?void 0:s.renderPassId)!==null&&r!==void 0?r:e.renderPassId)!==null&&n!==void 0?n:0,o&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),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),a.snapshotRendering&&a.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<e._rigCameras.length;i++)this._renderForCamera(e._rigCameras[i],e)}this._activeCamera=e,this.updateTransformMatrix(),this.onAfterRenderCameraObservable.notifyObservers(e)}_checkIntersections(){for(let e=0;e<this._meshesForIntersections.length;e++){const t=this._meshesForIntersections.data[e];if(t.actionManager)for(let i=0;t.actionManager&&i<t.actionManager.actions.length;i++){const s=t.actionManager.actions[i];if(s.trigger===12||s.trigger===13){const r=s.getTriggerParameter(),n=r.mesh?r.mesh:r,a=n.intersectsMesh(t,r.usePreciseIntersection),o=t._intersectionsInProgress.indexOf(n);a&&o===-1?s.trigger===12?(s._executeCurrent(St.CreateNew(t,void 0,n)),t._intersectionsInProgress.push(n)):s.trigger===13&&t._intersectionsInProgress.push(n):!a&&o>-1&&(s.trigger===13&&s._executeCurrent(St.CreateNew(t,void 0,n)),(!t.actionManager.hasSpecificTrigger(13,h=>{const c=h.mesh?h.mesh:h;return n===c})||s.trigger===13)&&t._intersectionsInProgress.splice(o,1))}}}}_advancePhysicsEngineStep(e){}_animate(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Ie.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Ie.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&s<n;)this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=t*i,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(t),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,s++,e-=t;this._timeAccumulator=e<0?0:e}else{const e=this.useConstantAnimationDeltaTime?16:Math.max(Ie.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Ie.MaxDeltaTime));this._animationRatio=e*(60/1e3),this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(e)}}_clear(){(this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil)}_checkCameraRenderTarget(e){var t;if(e!=null&&e.outputRenderTarget&&!(e!=null&&e.isRigCamera)&&(e.outputRenderTarget._cleared=!1),!((t=e==null?void 0:e.rigCameras)===null||t===void 0)&&t.length)for(let i=0;i<e.rigCameras.length;++i){const s=e.rigCameras[i].outputRenderTarget;s&&(s._cleared=!1)}}resetDrawCache(e){if(this.meshes)for(const t of this.meshes)t.resetDrawCache(e)}render(e=!0,t=!1){var i,s,r;if(this.isDisposed)return;this.onReadyObservable.hasObservers()&&this._executeWhenReadyTimeoutId===null&&this._checkIsReady(),this._frameId++,this._defaultFrameBufferCleared=!1,this._checkCameraRenderTarget(this.activeCamera),!((i=this.activeCameras)===null||i===void 0)&&i.length&&this.activeCameras.forEach(this._checkCameraRenderTarget),this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(11),t||this.animate();for(const o of this._beforeCameraUpdateStage)o.action();if(e){if(this.activeCameras&&this.activeCameras.length>0)for(let o=0;o<this.activeCameras.length;o++){const h=this.activeCameras[o];if(h.update(),h.cameraRigMode!==0)for(let c=0;c<h._rigCameras.length;c++)h._rigCameras[c].update()}else if(this.activeCamera&&(this.activeCamera.update(),this.activeCamera.cameraRigMode!==0))for(let o=0;o<this.activeCamera._rigCameras.length;o++)this.activeCamera._rigCameras[o].update()}this.onBeforeRenderObservable.notifyObservers(this);const n=this.getEngine();this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);const a=!((s=this.activeCameras)===null||s===void 0)&&s.length?this.activeCameras[0]:this.activeCamera;if(this.renderTargetsEnabled){k.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!0;for(let o=0;o<this.customRenderTargets.length;o++){const h=this.customRenderTargets[o];if(h._shouldRender()){if(this._renderId++,this.activeCamera=h.activeCamera||this.activeCamera,!this.activeCamera)throw new Error("Active camera not set");n.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),h.render(a!==this.activeCamera,this.dumpNextRenderTargets)}}k.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=(r=a==null?void 0:a.renderPassId)!==null&&r!==void 0?r:0,this.activeCamera=a,this._activeCamera&&this._activeCamera.cameraRigMode!==22&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const o of this._beforeClearStage)o.action();this._clearFrameBuffer(this.activeCamera);for(const o of this._gatherRenderTargetsStage)o.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let o=0;o<this.activeCameras.length;o++)this._processSubCameras(this.activeCameras[o],o>0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const o of this._afterRenderStage)o.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let o=0;o<this._toBeDisposed.length;o++){const h=this._toBeDisposed[o];h&&h.dispose()}this._toBeDisposed.length=0}this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0),this._engine.restoreDefaultFramebuffer()}freezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].freeze()}unfreezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].unfreeze()}dispose(){if(this.isDisposed)return;this.beforeRender=null,this.afterRender=null,this.metadata=null,this.skeletons.length=0,this.morphTargetManagers.length=0,this._transientComponents.length=0,this._isReadyForMeshStage.clear(),this._beforeEvaluateActiveMeshStage.clear(),this._evaluateSubMeshStage.clear(),this._preActiveMeshStage.clear(),this._cameraDrawRenderTargetStage.clear(),this._beforeCameraDrawStage.clear(),this._beforeRenderTargetDrawStage.clear(),this._beforeRenderingGroupDrawStage.clear(),this._beforeRenderingMeshStage.clear(),this._afterRenderingMeshStage.clear(),this._afterRenderingGroupDrawStage.clear(),this._afterCameraDrawStage.clear(),this._afterRenderTargetDrawStage.clear(),this._afterRenderStage.clear(),this._beforeCameraUpdateStage.clear(),this._beforeClearStage.clear(),this._gatherRenderTargetsStage.clear(),this._gatherActiveCameraRenderTargetsStage.clear(),this._pointerMoveStage.clear(),this._pointerDownStage.clear(),this._pointerUpStage.clear(),this.importedMeshesFiles=new Array,this.stopAllAnimations&&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 r of e)r.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(r){console.error("An error occurred while calling onDisposeObservable!",r)}if(this.detachControl(),this._engine.getInputElement())for(let r=0;r<this.cameras.length;r++)this.cameras[r].detachControl();this._disposeList(this.animationGroups),this._disposeList(this.lights),this._disposeList(this.meshes,r=>r.dispose(!0)),this._disposeList(this.transformNodes,r=>r.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),Ee._LastCreatedScene===this&&(this._engine.scenes.length>0?Ee._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:Ee._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??(s=>s.dispose());for(const s of i)t(s);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e<this.meshes.length;e++){const i=this.meshes[e].geometry;i&&i.clearCachedData()}}cleanCachedTextureBuffer(){for(const e of this.textures)e._buffer&&(e._buffer=null)}getWorldExtends(e){const t=new E(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new E(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return e=e||(()=>!0),this.meshes.filter(e).forEach(s=>{if(s.computeWorldMatrix(!0),!s.subMeshes||s.subMeshes.length===0||s.infiniteDistance)return;const r=s.getBoundingInfo(),n=r.boundingBox.minimumWorld,a=r.boundingBox.maximumWorld;E.CheckExtends(n,t,i),E.CheckExtends(a,t,i)}),{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw fe("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,a=!1){throw fe("Ray")}createPickingRayInCameraSpace(e,t,i){throw fe("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw fe("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,r,n){return new br}pickWithBoundingInfo(e,t,i,s,r){return new br}pickWithRay(e,t,i,s){throw fe("Ray")}multiPick(e,t,i,s,r){throw fe("Ray")}multiPickWithRay(e,t,i){throw fe("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild();this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(t===void 0)return e;const s=[];i=i||(r=>{});for(const r in e){const n=e[r];xe&&xe.MatchesQuery(n,t)&&(s.push(n),i(n))}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)}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,r,n,a){const o=rs(e,t,i,s?this.offlineProvider:void 0,r,n,a);return this._activeRequests.push(o),o.onCompleteObservable.add(h=>{this._activeRequests.splice(this._activeRequests.indexOf(h),1)}),o}_loadFileAsync(e,t,i,s,r){return new Promise((n,a)=>{this._loadFile(e,o=>{n(o)},t,i,s,(o,h)=>{a(h)},r)})}_requestFile(e,t,i,s,r,n,a){const o=Pn(e,t,i,s?this.offlineProvider:void 0,r,n,a);return this._activeRequests.push(o),o.onCompleteObservable.add(h=>{this._activeRequests.splice(this._activeRequests.indexOf(h),1)}),o}_requestFileAsync(e,t,i,s,r){return new Promise((n,a)=>{this._requestFile(e,o=>{n(o)},t,i,s,o=>{a(o)},r)})}_readFile(e,t,i,s,r){const n=vr(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add(a=>{this._activeRequests.splice(this._activeRequests.indexOf(a),1)}),n}_readFileAsync(e,t,i){return new Promise((s,r)=>{this._readFile(e,n=>{s(n)},t,i,n=>{r(n)})})}getPerfCollector(){throw fe("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)}}Ie.FOGMODE_NONE=0,Ie.FOGMODE_EXP=1,Ie.FOGMODE_EXP2=2,Ie.FOGMODE_LINEAR=3,Ie.MinDeltaTime=1,Ie.MaxDeltaTime=1e3;class me{constructor(){this._applyTo=Bh(this._applyToCoroutine.bind(this))}set(e,t){switch(e.length||F.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case A.PositionKind:this.positions=e;break;case A.NormalKind:this.normals=e;break;case A.TangentKind:this.tangents=e;break;case A.UVKind:this.uvs=e;break;case A.UV2Kind:this.uvs2=e;break;case A.UV3Kind:this.uvs3=e;break;case A.UV4Kind:this.uvs4=e;break;case A.UV5Kind:this.uvs5=e;break;case A.UV6Kind:this.uvs6=e;break;case A.ColorKind:this.colors=e;break;case A.MatricesIndicesKind:this.matricesIndices=e;break;case A.MatricesWeightsKind:this.matricesWeights=e;break;case A.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case A.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){return this.positions&&(e.setVerticesData(A.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(A.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(A.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(A.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(A.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(A.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(A.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(A.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(A.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(A.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(A.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(A.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(A.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(A.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),this}_update(e,t,i){return this.positions&&e.updateVerticesData(A.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(A.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(A.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(A.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(A.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(A.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(A.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(A.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(A.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(A.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(A.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(A.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(A.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(A.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=D.Vector3[0],n=D.Vector3[1];for(let a=i;a<i+s;a+=3)E.FromArrayToRef(e,a,r),E.TransformCoordinatesToRef(r,t,n),e[a]=n.x,e[a+1]=n.y,e[a+2]=n.z}static _TransformVector3Normals(e,t,i=0,s=e.length){const r=D.Vector3[0],n=D.Vector3[1];for(let a=i;a<i+s;a+=3)E.FromArrayToRef(e,a,r),E.TransformNormalToRef(r,t,n),e[a]=n.x,e[a+1]=n.y,e[a+2]=n.z}static _TransformVector4Normals(e,t,i=0,s=e.length){const r=D.Vector4[0],n=D.Vector4[1];for(let a=i;a<i+s;a+=4)He.FromArrayToRef(e,a,r),He.TransformNormalToRef(r,t,n),e[a]=n.x,e[a+1]=n.y,e[a+2]=n.z,e[a+3]=n.w}static _FlipFaces(e,t=0,i=e.length){for(let s=t;s<t+i;s+=3){const r=e[s+1];e[s+1]=e[s+2],e[s+2]=r}}transform(e){const t=e.determinant()<0;return this.positions&&me._TransformVector3Coordinates(this.positions,e),this.normals&&me._TransformVector3Normals(this.normals,e),this.tangents&&me._TransformVector4Normals(this.tangents,e),t&&this.indices&&me._FlipFaces(this.indices),this}merge(e,t=!1,i=!1){const s=Array.isArray(e)?e.map(r=>({vertexData:r})):[{vertexData:e}];return Ln(this._mergeCoroutine(void 0,s,t,!1,i))}*_mergeCoroutine(e,t,i=!1,s,r){var n,a,o,h;this._validate();const c=t.map(_=>_.vertexData);for(const _ of c)if(_._validate(),!this.normals!=!_.normals||!this.tangents!=!_.tangents||!this.uvs!=!_.uvs||!this.uvs2!=!_.uvs2||!this.uvs3!=!_.uvs3||!this.uvs4!=!_.uvs4||!this.uvs5!=!_.uvs5||!this.uvs6!=!_.uvs6||!this.colors!=!_.colors||!this.matricesIndices!=!_.matricesIndices||!this.matricesWeights!=!_.matricesWeights||!this.matricesIndicesExtra!=!_.matricesIndicesExtra||!this.matricesWeightsExtra!=!_.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");const u=c.reduce((_,p)=>{var m,T;return _+((T=(m=p.indices)===null||m===void 0?void 0:m.length)!==null&&T!==void 0?T:0)},(a=(n=this.indices)===null||n===void 0?void 0:n.length)!==null&&a!==void 0?a:0);let d=r||c.some(_=>_.indices===this.indices)?(o=this.indices)===null||o===void 0?void 0:o.slice():this.indices;if(u>0){let _=(h=d==null?void 0:d.length)!==null&&h!==void 0?h:0;if(d||(d=new Array(u)),d.length!==u){if(Array.isArray(d))d.length=u;else{const m=i||d instanceof Uint32Array?new Uint32Array(u):new Uint16Array(u);m.set(d),d=m}e&&e.determinant()<0&&me._FlipFaces(d,0,_)}let p=this.positions?this.positions.length/3:0;for(const{vertexData:m,transform:T}of t)if(m.indices){for(let S=0;S<m.indices.length;S++)d[_+S]=m.indices[S]+p;T&&T.determinant()<0&&me._FlipFaces(d,_,m.indices.length),p+=m.positions.length/3,_+=m.indices.length,s&&(yield)}}return this.indices=d,this.positions=me._MergeElement(A.PositionKind,this.positions,e,t.map(_=>[_.vertexData.positions,_.transform])),s&&(yield),this.normals=me._MergeElement(A.NormalKind,this.normals,e,t.map(_=>[_.vertexData.normals,_.transform])),s&&(yield),this.tangents=me._MergeElement(A.TangentKind,this.tangents,e,t.map(_=>[_.vertexData.tangents,_.transform])),s&&(yield),this.uvs=me._MergeElement(A.UVKind,this.uvs,e,t.map(_=>[_.vertexData.uvs,_.transform])),s&&(yield),this.uvs2=me._MergeElement(A.UV2Kind,this.uvs2,e,t.map(_=>[_.vertexData.uvs2,_.transform])),s&&(yield),this.uvs3=me._MergeElement(A.UV3Kind,this.uvs3,e,t.map(_=>[_.vertexData.uvs3,_.transform])),s&&(yield),this.uvs4=me._MergeElement(A.UV4Kind,this.uvs4,e,t.map(_=>[_.vertexData.uvs4,_.transform])),s&&(yield),this.uvs5=me._MergeElement(A.UV5Kind,this.uvs5,e,t.map(_=>[_.vertexData.uvs5,_.transform])),s&&(yield),this.uvs6=me._MergeElement(A.UV6Kind,this.uvs6,e,t.map(_=>[_.vertexData.uvs6,_.transform])),s&&(yield),this.colors=me._MergeElement(A.ColorKind,this.colors,e,t.map(_=>[_.vertexData.colors,_.transform])),s&&(yield),this.matricesIndices=me._MergeElement(A.MatricesIndicesKind,this.matricesIndices,e,t.map(_=>[_.vertexData.matricesIndices,_.transform])),s&&(yield),this.matricesWeights=me._MergeElement(A.MatricesWeightsKind,this.matricesWeights,e,t.map(_=>[_.vertexData.matricesWeights,_.transform])),s&&(yield),this.matricesIndicesExtra=me._MergeElement(A.MatricesIndicesExtraKind,this.matricesIndicesExtra,e,t.map(_=>[_.vertexData.matricesIndicesExtra,_.transform])),s&&(yield),this.matricesWeightsExtra=me._MergeElement(A.MatricesWeightsExtraKind,this.matricesWeightsExtra,e,t.map(_=>[_.vertexData.matricesWeightsExtra,_.transform])),this}static _MergeElement(e,t,i,s){const r=s.filter(o=>o[0]!==null&&o[0]!==void 0);if(!t&&r.length==0)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const n=r.reduce((o,h)=>o+h[0].length,t.length),a=e===A.PositionKind?me._TransformVector3Coordinates:e===A.NormalKind?me._TransformVector3Normals:e===A.TangentKind?me._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const o=new Float32Array(n);o.set(t),i&&a(o,i,0,t.length);let h=t.length;for(const[c,u]of r)o.set(c,h),u&&a(o,u,h,c.length),h+=c.length;return o}else{const o=new Array(n);for(let c=0;c<t.length;c++)o[c]=t[c];i&&a(o,i,0,t.length);let h=t.length;for(const[c,u]of r){for(let f=0;f<c.length;f++)o[h+f]=c[f];u&&a(o,u,h,c.length),h+=c.length}return o}}_validate(){if(!this.positions)throw new xi("Positions are required",is.MeshInvalidPositionsError);const e=(s,r)=>{const n=A.DeduceStride(s);if(r.length%n!==0)throw new Error("The "+s+"s array count must be a multiple of "+n);return r.length/n},t=e(A.PositionKind,this.positions),i=(s,r)=>{const n=e(s,r);if(n!==t)throw new Error("The "+s+"s element count ("+n+") does not match the positions count ("+t+")")};this.normals&&i(A.NormalKind,this.normals),this.tangents&&i(A.TangentKind,this.tangents),this.uvs&&i(A.UVKind,this.uvs),this.uvs2&&i(A.UV2Kind,this.uvs2),this.uvs3&&i(A.UV3Kind,this.uvs3),this.uvs4&&i(A.UV4Kind,this.uvs4),this.uvs5&&i(A.UV5Kind,this.uvs5),this.uvs6&&i(A.UV6Kind,this.uvs6),this.colors&&i(A.ColorKind,this.colors),this.matricesIndices&&i(A.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(A.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(A.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(A.MatricesWeightsExtraKind,this.matricesWeightsExtra)}serialize(){const e={};return this.positions&&(e.positions=this.positions),this.normals&&(e.normals=this.normals),this.tangents&&(e.tangents=this.tangents),this.uvs&&(e.uvs=this.uvs),this.uvs2&&(e.uvs2=this.uvs2),this.uvs3&&(e.uvs3=this.uvs3),this.uvs4&&(e.uvs4=this.uvs4),this.uvs5&&(e.uvs5=this.uvs5),this.uvs6&&(e.uvs6=this.uvs6),this.colors&&(e.colors=this.colors),this.matricesIndices&&(e.matricesIndices=this.matricesIndices,e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=this.matricesWeights),this.matricesIndicesExtra&&(e.matricesIndicesExtra=this.matricesIndicesExtra,e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=this.matricesWeightsExtra),e.indices=this.indices,e}static ExtractFromMesh(e,t,i){return me._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return me._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new me;return e.isVerticesDataPresent(A.PositionKind)&&(s.positions=e.getVerticesData(A.PositionKind,t,i)),e.isVerticesDataPresent(A.NormalKind)&&(s.normals=e.getVerticesData(A.NormalKind,t,i)),e.isVerticesDataPresent(A.TangentKind)&&(s.tangents=e.getVerticesData(A.TangentKind,t,i)),e.isVerticesDataPresent(A.UVKind)&&(s.uvs=e.getVerticesData(A.UVKind,t,i)),e.isVerticesDataPresent(A.UV2Kind)&&(s.uvs2=e.getVerticesData(A.UV2Kind,t,i)),e.isVerticesDataPresent(A.UV3Kind)&&(s.uvs3=e.getVerticesData(A.UV3Kind,t,i)),e.isVerticesDataPresent(A.UV4Kind)&&(s.uvs4=e.getVerticesData(A.UV4Kind,t,i)),e.isVerticesDataPresent(A.UV5Kind)&&(s.uvs5=e.getVerticesData(A.UV5Kind,t,i)),e.isVerticesDataPresent(A.UV6Kind)&&(s.uvs6=e.getVerticesData(A.UV6Kind,t,i)),e.isVerticesDataPresent(A.ColorKind)&&(s.colors=e.getVerticesData(A.ColorKind,t,i)),e.isVerticesDataPresent(A.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(A.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(A.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(A.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(A.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(A.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(A.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(A.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw fe("ribbonBuilder")}static CreateBox(e){throw fe("boxBuilder")}static CreateTiledBox(e){throw fe("tiledBoxBuilder")}static CreateTiledPlane(e){throw fe("tiledPlaneBuilder")}static CreateSphere(e){throw fe("sphereBuilder")}static CreateCylinder(e){throw fe("cylinderBuilder")}static CreateTorus(e){throw fe("torusBuilder")}static CreateLineSystem(e){throw fe("linesBuilder")}static CreateDashedLines(e){throw fe("linesBuilder")}static CreateGround(e){throw fe("groundBuilder")}static CreateTiledGround(e){throw fe("groundBuilder")}static CreateGroundFromHeightMap(e){throw fe("groundBuilder")}static CreatePlane(e){throw fe("planeBuilder")}static CreateDisc(e){throw fe("discBuilder")}static CreatePolygon(e,t,i,s,r,n,a){throw fe("polygonBuilder")}static CreateIcoSphere(e){throw fe("icoSphereBuilder")}static CreatePolyhedron(e){throw fe("polyhedronBuilder")}static CreateCapsule(e={orientation:E.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw fe("capsuleBuilder")}static CreateTorusKnot(e){throw fe("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let r=0,n=0,a=0,o=0,h=0,c=0,u=0,f=0,d=0,_=0,p=0,m=0,T=0,S=0,x=0,b=0,I=0,R=0,C=0,y=0,w=!1,G=!1,te=!1,Q=!1,Te=1,he=0,ve=null;s&&(w=!!s.facetNormals,G=!!s.facetPositions,te=!!s.facetPartitioning,Te=s.useRightHandedSystem===!0?-1:1,he=s.ratio||0,Q=!!s.depthSort,ve=s.distanceTo,Q&&ve===void 0&&(ve=E.Zero()));let le=0,be=0,ye=0,Ye=0;for(te&&s&&s.bbSize&&(le=s.subDiv.X*he/s.bbSize.x,be=s.subDiv.Y*he/s.bbSize.y,ye=s.subDiv.Z*he/s.bbSize.z,Ye=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),r=0;r<e.length;r++)i[r]=0;const et=t.length/3|0;for(r=0;r<et;r++){if(m=t[r*3]*3,T=m+1,S=m+2,x=t[r*3+1]*3,b=x+1,I=x+2,R=t[r*3+2]*3,C=R+1,y=R+2,n=e[m]-e[x],a=e[T]-e[b],o=e[S]-e[I],h=e[R]-e[x],c=e[C]-e[b],u=e[y]-e[I],f=Te*(a*u-o*c),d=Te*(o*h-n*u),_=Te*(n*c-a*h),p=Math.sqrt(f*f+d*d+_*_),p=p===0?1:p,f/=p,d/=p,_/=p,w&&s&&(s.facetNormals[r].x=f,s.facetNormals[r].y=d,s.facetNormals[r].z=_),G&&s&&(s.facetPositions[r].x=(e[m]+e[x]+e[R])/3,s.facetPositions[r].y=(e[T]+e[b]+e[C])/3,s.facetPositions[r].z=(e[S]+e[I]+e[y])/3),te&&s){const Ne=Math.floor((s.facetPositions[r].x-s.bInfo.minimum.x*he)*le),pt=Math.floor((s.facetPositions[r].y-s.bInfo.minimum.y*he)*be),Si=Math.floor((s.facetPositions[r].z-s.bInfo.minimum.z*he)*ye),Os=Math.floor((e[m]-s.bInfo.minimum.x*he)*le),ur=Math.floor((e[T]-s.bInfo.minimum.y*he)*be),ot=Math.floor((e[S]-s.bInfo.minimum.z*he)*ye),Ds=Math.floor((e[x]-s.bInfo.minimum.x*he)*le),Ls=Math.floor((e[b]-s.bInfo.minimum.y*he)*be),Ns=Math.floor((e[I]-s.bInfo.minimum.z*he)*ye),Fs=Math.floor((e[R]-s.bInfo.minimum.x*he)*le),za=Math.floor((e[C]-s.bInfo.minimum.y*he)*be),Xa=Math.floor((e[y]-s.bInfo.minimum.z*he)*ye),qi=Os+s.subDiv.max*ur+Ye*ot,Zi=Ds+s.subDiv.max*Ls+Ye*Ns,Qi=Fs+s.subDiv.max*za+Ye*Xa,$i=Ne+s.subDiv.max*pt+Ye*Si;s.facetPartitioning[$i]=s.facetPartitioning[$i]?s.facetPartitioning[$i]:new Array,s.facetPartitioning[qi]=s.facetPartitioning[qi]?s.facetPartitioning[qi]:new Array,s.facetPartitioning[Zi]=s.facetPartitioning[Zi]?s.facetPartitioning[Zi]:new Array,s.facetPartitioning[Qi]=s.facetPartitioning[Qi]?s.facetPartitioning[Qi]:new Array,s.facetPartitioning[qi].push(r),Zi!=qi&&s.facetPartitioning[Zi].push(r),Qi==Zi||Qi==qi||s.facetPartitioning[Qi].push(r),$i==qi||$i==Zi||$i==Qi||s.facetPartitioning[$i].push(r)}if(Q&&s&&s.facetPositions){const Ne=s.depthSortedFacets[r];Ne.ind=r*3,Ne.sqDistance=E.DistanceSquared(s.facetPositions[r],ve)}i[m]+=f,i[T]+=d,i[S]+=_,i[x]+=f,i[b]+=d,i[I]+=_,i[R]+=f,i[C]+=d,i[y]+=_}for(r=0;r<i.length/3;r++)f=i[r*3],d=i[r*3+1],_=i[r*3+2],p=Math.sqrt(f*f+d*d+_*_),p=p===0?1:p,f/=p,d/=p,_/=p,i[r*3]=f,i[r*3+1]=d,i[r*3+2]=_}static _ComputeSides(e,t,i,s,r,n,a){const o=i.length,h=s.length;let c,u;switch(e=e||me.DEFAULTSIDE,e){case me.FRONTSIDE:break;case me.BACKSIDE:for(c=0;c<o;c+=3){const f=i[c];i[c]=i[c+2],i[c+2]=f}for(u=0;u<h;u++)s[u]=-s[u];break;case me.DOUBLESIDE:{const f=t.length,d=f/3;for(let m=0;m<f;m++)t[f+m]=t[m];for(c=0;c<o;c+=3)i[c+o]=i[c+2]+d,i[c+1+o]=i[c+1]+d,i[c+2+o]=i[c]+d;for(u=0;u<h;u++)s[h+u]=-s[u];const _=r.length;let p=0;for(p=0;p<_;p++)r[p+_]=r[p];for(n=n||new He(0,0,1,1),a=a||new He(0,0,1,1),p=0,c=0;c<_/2;c++)r[p]=n.x+(n.z-n.x)*r[p],r[p+1]=n.y+(n.w-n.y)*r[p+1],r[p+_]=a.x+(a.z-a.x)*r[p+_],r[p+_+1]=a.y+(a.w-a.y)*r[p+_+1],p+=2;break}}}static ImportVertexData(e,t){const i=new me,s=e.positions;s&&i.set(s,A.PositionKind);const r=e.normals;r&&i.set(r,A.NormalKind);const n=e.tangents;n&&i.set(n,A.TangentKind);const a=e.uvs;a&&i.set(a,A.UVKind);const o=e.uv2s;o&&i.set(o,A.UV2Kind);const h=e.uv3s;h&&i.set(h,A.UV3Kind);const c=e.uv4s;c&&i.set(c,A.UV4Kind);const u=e.uv5s;u&&i.set(u,A.UV5Kind);const f=e.uv6s;f&&i.set(f,A.UV6Kind);const d=e.colors;d&&i.set(ge.CheckColors4(d,s.length/3),A.ColorKind);const _=e.matricesIndices;_&&i.set(_,A.MatricesIndicesKind);const p=e.matricesWeights;p&&i.set(p,A.MatricesWeightsKind);const m=e.indices;m&&(i.indices=m),t.setAllVerticesData(i,e.updatable)}}me.FRONTSIDE=0,me.BACKSIDE=1,me.DOUBLESIDE=2,me.DEFAULTSIDE=0,g([ts.filter((...[l])=>!Array.isArray(l))],me,"_TransformVector3Coordinates",null),g([ts.filter((...[l])=>!Array.isArray(l))],me,"_TransformVector3Normals",null),g([ts.filter((...[l])=>!Array.isArray(l))],me,"_TransformVector4Normals",null),g([ts.filter((...[l])=>!Array.isArray(l))],me,"_FlipFaces",null);class xo{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class wi{constructor(e,t,i){this.vectors=At.BuildArray(8,E.Zero),this.center=E.Zero(),this.centerWorld=E.Zero(),this.extendSize=E.Zero(),this.extendSizeWorld=E.Zero(),this.directions=At.BuildArray(3,E.Zero),this.vectorsWorld=At.BuildArray(8,E.Zero),this.minimumWorld=E.Zero(),this.maximumWorld=E.Zero(),this.minimum=E.Zero(),this.maximum=E.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,r=e.y,n=e.z,a=t.x,o=t.y,h=t.z,c=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(a,o,h),c[0].copyFromFloats(s,r,n),c[1].copyFromFloats(a,o,h),c[2].copyFromFloats(a,r,n),c[3].copyFromFloats(s,o,n),c[4].copyFromFloats(s,r,h),c[5].copyFromFloats(a,o,n),c[6].copyFromFloats(s,o,h),c[7].copyFromFloats(a,r,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||M.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=wi._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(r*.5),a=this.center.subtractToRef(n,t[1]),o=this.center.addToRef(n,t[2]);return this.reConstruct(a,o,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let a=0;a<8;++a)r[a].copyFrom(n[a]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let a=0;a<8;++a){const o=r[a];E.TransformCoordinatesToRef(n[a],e,o),t.minimizeInPlace(o),i.maximizeInPlace(o)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}E.FromArrayToRef(e.m,0,s[0]),E.FromArrayToRef(e.m,4,s[1]),E.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return wi.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return wi.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,a=i.x,o=i.y,h=i.z,c=e.x,u=e.y,f=e.z,d=-ke;return!(a-c<d||d>c-s||o-u<d||d>u-r||h-f<d||d>f-n)}intersectsSphere(e){return wi.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,r=i.x,n=i.y,a=i.z,o=s.x,h=s.y,c=s.z,u=e.x,f=e.y,d=e.z,_=t.x,p=t.y,m=t.z;return!(o<u||r>_||h<f||n>p||c<d||a>m)}dispose(){var e,t;(e=this._drawWrapperFront)===null||e===void 0||e.dispose(),(t=this._drawWrapperBack)===null||t===void 0||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const r=wi._TmpVector3[0];return E.ClampToRef(i,e,t,r),E.DistanceSquared(i,r)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let r=0;r<8;++r)if(s.dotCoordinate(e[r])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const r=t[i];for(let n=0;n<8;++n)if(r.dotCoordinate(e[n])>=0){s=!1;break}if(s)return!1}return!0}}wi._TmpVector3=At.BuildArray(3,E.Zero);class Ts{constructor(e,t,i){this.center=E.Zero(),this.centerWorld=E.Zero(),this.minimum=E.Zero(),this.maximum=E.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=E.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=s*.5,this._update(i||M.IdentityReadOnly)}scale(e){const t=this.radius*e,i=Ts._TmpVector3,s=i[0].setAll(t),r=this.center.subtractToRef(s,i[1]),n=this.center.addToRef(s,i[2]);return this.reConstruct(r,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{E.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=Ts._TmpVector3[0];E.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=E.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld<t)}static Intersects(e,t){const i=E.DistanceSquared(e.centerWorld,t.centerWorld),s=e.radiusWorld+t.radiusWorld;return!(s*s<i)}static CreateFromCenterAndRadius(e,t,i){this._TmpVector3[0].copyFrom(e),this._TmpVector3[1].copyFromFloats(0,0,t),this._TmpVector3[2].copyFrom(e),this._TmpVector3[0].addInPlace(this._TmpVector3[1]),this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);const s=new Ts(this._TmpVector3[0],this._TmpVector3[2]);return i?s._worldMatrix=i:s._worldMatrix=M.Identity(),s}}Ts._TmpVector3=At.BuildArray(3,E.Zero);const wn={min:0,max:0},Bn={min:0,max:0},Co=(l,e,t)=>{const i=E.Dot(e.centerWorld,l),s=Math.abs(E.Dot(e.directions[0],l))*e.extendSize.x,r=Math.abs(E.Dot(e.directions[1],l))*e.extendSize.y,n=Math.abs(E.Dot(e.directions[2],l))*e.extendSize.z,a=s+r+n;t.min=i-a,t.max=i+a},Ht=(l,e,t)=>(Co(l,e,wn),Co(l,t,Bn),!(wn.min>Bn.max||Bn.min>wn.max));class $t{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new wi(e,t,i),this.boundingSphere=new Ts(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=$t._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=$t._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=E.Minimize(this.minimum,e),i=E.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=D.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=D.Vector3[0];return E.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),E.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,$t._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(!Ts.Intersects(this.boundingSphere,e.boundingSphere)||!wi.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!(!Ht(i.directions[0],i,s)||!Ht(i.directions[1],i,s)||!Ht(i.directions[2],i,s)||!Ht(s.directions[0],i,s)||!Ht(s.directions[1],i,s)||!Ht(s.directions[2],i,s)||!Ht(E.Cross(i.directions[0],s.directions[0]),i,s)||!Ht(E.Cross(i.directions[0],s.directions[1]),i,s)||!Ht(E.Cross(i.directions[0],s.directions[2]),i,s)||!Ht(E.Cross(i.directions[1],s.directions[0]),i,s)||!Ht(E.Cross(i.directions[1],s.directions[1]),i,s)||!Ht(E.Cross(i.directions[1],s.directions[2]),i,s)||!Ht(E.Cross(i.directions[2],s.directions[0]),i,s)||!Ht(E.Cross(i.directions[2],s.directions[1]),i,s)||!Ht(E.Cross(i.directions[2],s.directions[2]),i,s))}}$t._TmpVector3=At.BuildArray(2,E.Zero);class rn{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let a=i;a<i+s;a++){const o=t[a]*3,h=e[o],c=e[o+1],u=e[o+2];r.minimizeInPlaceFromFloats(h,c,u),n.maximizeInPlaceFromFloats(h,c,u)}}static extractMinAndMax(e,t,i,s,r,n){for(let a=t,o=t*s;a<t+i;a++,o+=s){const h=e[o],c=e[o+1],u=e[o+2];r.minimizeInPlaceFromFloats(h,c,u),n.maximizeInPlaceFromFloats(h,c,u)}}}g([ts.filter((...[l,e])=>!Array.isArray(l)&&!Array.isArray(e))],rn,"extractMinAndMaxIndexed",null),g([ts.filter((...[l])=>!Array.isArray(l))],rn,"extractMinAndMax",null);function Xh(l,e,t,i,s=null){const r=new E(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new E(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return rn.extractMinAndMaxIndexed(l,e,t,i,r,n),s&&(r.x-=r.x*s.x+s.y,r.y-=r.y*s.x+s.y,r.z-=r.z*s.x+s.y,n.x+=n.x*s.x+s.y,n.y+=n.y*s.x+s.y,n.z+=n.z*s.x+s.y),{minimum:r,maximum:n}}function bo(l,e,t,i=null,s){const r=new E(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new E(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return s||(s=3),rn.extractMinAndMax(l,e,t,s,r,n),i&&(r.x-=r.x*i.x+i.y,r.y-=r.y*i.x+i.y,r.z-=r.z*i.x+i.y,n.x+=n.x*i.x+i.y,n.y+=n.y*i.x+i.y,n.z+=n.z*i.x+i.y),{minimum:r,maximum:n}}class ci{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:(e=this._getDrawWrapper())===null||e===void 0?void 0:e.defines}set materialDefines(e){var t;const i=(t=this._mainDrawWrapperOverride)!==null&&t!==void 0?t:this._getDrawWrapper(void 0,!0);i.defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new Li(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&((i=this._drawWrappers[e])===null||i===void 0||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:(t=(e=this._getDrawWrapper())===null||e===void 0?void 0:e.effect)!==null&&t!==void 0?t:null}get _drawWrapper(){var e;return(e=this._mainDrawWrapperOverride)!==null&&e!==void 0?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const r=this._drawWrapper;r.setEffect(e,t,s),i!==void 0&&(r.materialContext=i),e||(r.defines=null,r.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,r,n,a,o=!0){return new ci(e,t,i,s,r,n,a,o)}constructor(e,t,i,s,r,n,a,o=!0,h=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=r,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=a||n,h&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,o&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return this.verticesStart===0&&this.verticesCount===this._mesh.getTotalVertices()&&this.indexStart===0&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){const e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){var t;const i=(t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))!==null&&t!==void 0?t:this._renderingMesh.material;if(i){if(this._isMultiMaterial(i)){const s=i.getSubMaterial(this.materialIndex);return this._currentMaterial!==s&&(this._currentMaterial=s,this.resetDrawCache()),s}}else return e?this._mesh.getScene().defaultMaterial:null;return i}_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(A.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=Xh(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new $t(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;s<this.indexStart+this.indexCount;s+=3)i.push(e[s],e[s+1],e[s+1],e[s+2],e[s+2],e[s]);this._linesIndexBuffer=t.createIndexBuffer(i),this._linesIndexCount=i.length}return this._linesIndexBuffer}canIntersects(e){const t=this.getBoundingInfo();return t?e.intersectsBox(t.boundingBox):!1}intersects(e,t,i,s,r){const n=this.getMaterial();if(!n)return null;let a=3,o=!1;switch(n.fillMode){case 3:case 5:case 6:case 8:return null;case 7:a=1,o=!0;break}return n.fillMode===4?i.length?this._intersectLines(e,t,i,this._mesh.intersectionThreshold,s):this._intersectUnIndexedLines(e,t,i,this._mesh.intersectionThreshold,s):!i.length&&this._mesh._unIndexed?this._intersectUnIndexedTriangles(e,t,i,s,r):this._intersectTriangles(e,t,i,a,o,s,r)}_intersectLines(e,t,i,s,r){let n=null;for(let a=this.indexStart;a<this.indexStart+this.indexCount;a+=2){const o=t[i[a]],h=t[i[a+1]],c=e.intersectionSegment(o,h,s);if(!(c<0)&&(r||!n||c<n.distance)&&(n=new xo(null,null,c),n.faceId=a/2,r))break}return n}_intersectUnIndexedLines(e,t,i,s,r){let n=null;for(let a=this.verticesStart;a<this.verticesStart+this.verticesCount;a+=2){const o=t[a],h=t[a+1],c=e.intersectionSegment(o,h,s);if(!(c<0)&&(r||!n||c<n.distance)&&(n=new xo(null,null,c),n.faceId=a/2,r))break}return n}_intersectTriangles(e,t,i,s,r,n,a){let o=null,h=-1;for(let c=this.indexStart;c<this.indexStart+this.indexCount-(3-s);c+=s){h++;const u=i[c],f=i[c+1],d=i[c+2];if(r&&d===4294967295){c+=2;continue}const _=t[u],p=t[f],m=t[d];if(!_||!p||!m||a&&!a(_,p,m,e,u,f,d))continue;const T=e.intersectsTriangle(_,p,m);if(T){if(T.distance<0)continue;if((n||!o||T.distance<o.distance)&&(o=T,o.faceId=h,n))break}}return o}_intersectUnIndexedTriangles(e,t,i,s,r){let n=null;for(let a=this.verticesStart;a<this.verticesStart+this.verticesCount;a+=3){const o=t[a],h=t[a+1],c=t[a+2];if(r&&!r(o,h,c,e,-1,-1,-1))continue;const u=e.intersectsTriangle(o,h,c);if(u){if(u.distance<0)continue;if((s||!n||u.distance<n.distance)&&(n=u,n.faceId=a/3,s))break}}return n}_rebuild(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)}clone(e,t){const i=new ci(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,e,t,!1);if(!this.IsGlobal){const s=this.getBoundingInfo();if(!s)return i;i._boundingInfo=new $t(s.minimum,s.maximum)}return i}dispose(){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);const e=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(e,1),this.resetDrawCache()}getClassName(){return"SubMesh"}static CreateFromIndices(e,t,i,s,r,n=!0){let a=Number.MAX_VALUE,o=-Number.MAX_VALUE;const c=(r||s).getIndices();for(let u=t;u<t+i;u++){const f=c[u];f<a&&(a=f),f>o&&(o=f)}return new ci(e,a,o-a+1,t,i,s,r,n)}}class ct{static get ForceFullSceneLoadingForIncremental(){return ct._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){ct._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return ct._ShowLoadingScreen}static set ShowLoadingScreen(e){ct._ShowLoadingScreen=e}static get loggingLevel(){return ct._LoggingLevel}static set loggingLevel(e){ct._LoggingLevel=e}static get CleanBoneMatrixWeights(){return ct._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){ct._CleanBoneMatrixWeights=e}}ct._ForceFullSceneLoadingForIncremental=!1,ct._ShowLoadingScreen=!0,ct._CleanBoneMatrixWeights=!1,ct._LoggingLevel=0;class si{}si.UseOpenGLOrientationForUV=!1;class Bt{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 Bt(Bt.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,r=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||Ee.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=s,i?this.setAllVerticesData(i,s):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return this.delayLoadState===1||this.delayLoadState===0}get doNotSerialize(){for(let e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0}_rebuild(){this._vertexArrayObjects&&(this._vertexArrayObjects={}),this._meshes.length!==0&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable));for(const e in this._vertexBuffers)this._vertexBuffers[e]._rebuild()}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,s){i&&Array.isArray(t)&&(t=new Float32Array(t));const r=new A(this._engine,t,e,i,this._meshes.length===0,s);this.setVerticesBuffer(r)}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 r=this._meshes,n=r.length;if(s===A.PositionKind){const a=e.getData();t!=null?this._totalVertices=t:a!=null&&(this._totalVertices=a.length/(e.type===A.BYTE?e.byteStride:e.byteStride/4)),this._updateExtend(a),this._resetPointsArrayCache();for(let o=0;o<n;o++){const h=r[o];h.buildBoundingInfo(this._extend.minimum,this._extend.maximum),h._createGlobalSubMesh(h.isUnIndexed),h.computeWorldMatrix(!0),h.synchronizeInstances()}}this._notifyUpdate(s)}updateVerticesDataDirectly(e,t,i,s=!1){const r=this.getVertexBuffer(e);r&&(r.updateDirectly(t,i,s),this._notifyUpdate(e))}updateVerticesData(e,t,i=!1){const s=this.getVertexBuffer(e);s&&(s.update(t),e===A.PositionKind&&this._updateBoundingInfo(i,t),this._notifyUpdate(e))}_updateBoundingInfo(e,t){if(e&&this._updateExtend(t),this._resetPointsArrayCache(),e){const i=this._meshes;for(const s of i){s.hasBoundingInfo?s.getBoundingInfo().reConstruct(this._extend.minimum,this._extend.maximum):s.buildBoundingInfo(this._extend.minimum,this._extend.maximum);const r=s.subMeshes;for(const n of r)n.refreshBoundingInfo()}}}_bind(e,t,i,s){if(!e)return;t===void 0&&(t=this._indexBuffer);const r=this.getVertexBuffers();if(!r)return;if(t!=this._indexBuffer||!this._vertexArrayObjects&&!s){this._engine.bindBuffers(r,t,e,i);return}const n=s||this._vertexArrayObjects;n[e.key]||(n[e.key]=this._engine.recordVertexArrayObject(r,t,e,i)),this._engine.bindVertexArrayObject(n[e.key],t)}getTotalVertices(){return this.isReady()?this._totalVertices:0}getVerticesData(e,t,i){const s=this.getVertexBuffer(e);return s?s.getFloatData(this._totalVertices,i||t&&this._meshes.length!==1):null}isVertexBufferUpdatable(e){const t=this._vertexBuffers[e];return t?t.isUpdatable():!1}getVertexBuffer(e){return this.isReady()?this._vertexBuffers[e]:null}getVertexBuffers(){return this.isReady()?this._vertexBuffers:null}isVerticesDataPresent(e){return this._vertexBuffers?this._vertexBuffers[e]!==void 0:this._delayInfo?this._delayInfo.indexOf(e)!==-1:!1}getVerticesDataKinds(){const e=[];let t;if(!this._vertexBuffers&&this._delayInfo)for(t in this._delayInfo)e.push(t);else for(t in this._vertexBuffers)e.push(t);return e}updateIndices(e,t,i=!1){if(this._indexBuffer)if(!this._indexBufferIsUpdatable)this.setIndices(e,null,!0);else{const s=e.length!==this._indices.length;if(i||(this._indices=e.slice()),this._engine.updateDynamicIndexBuffer(this._indexBuffer,e,t),s)for(const r of this._meshes)r._createGlobalSubMesh(!0)}}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)),t!=null&&(this._totalVertices=t);for(const s of this._meshes)s._createGlobalSubMesh(!0),s.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?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(A.PositionKind),!e))return;this._extend=bo(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===A.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)),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,r=s.length;for(let n=0;n<r;n++)this._applyToMesh(s[n]);t&&t()},void 0,!0))}toLeftHanded(){const e=this.getIndices(!1);if(e!=null&&e.length>0){for(let s=0;s<e.length;s+=3){const r=e[s+0];e[s+0]=e[s+2],e[s+2]=r}this.setIndices(e)}const t=this.getVerticesData(A.PositionKind,!1);if(t!=null&&t.length>0){for(let s=0;s<t.length;s+=3)t[s+2]=-t[s+2];this.setVerticesData(A.PositionKind,t,!1)}const i=this.getVerticesData(A.NormalKind,!1);if(i!=null&&i.length>0){for(let s=0;s<i.length;s+=3)i[s+2]=-i[s+2];this.setVerticesData(A.NormalKind,i,!1)}}_resetPointsArrayCache(){this._positions=null}_generatePointsArray(){if(this._positions)return!0;const e=this.getVerticesData(A.PositionKind);if(!e||e.length===0)return!1;for(let t=this._positionsCache.length*3,i=this._positionsCache.length;t<e.length;t+=3,++i)this._positionsCache[i]=E.FromArray(e,t);for(let t=0,i=0;t<e.length;t+=3,++i)this._positionsCache[i].set(e[0+t],e[1+t],e[2+t]);return this._positionsCache.length=e.length/3,this._positions=this._positionsCache,!0}isDisposed(){return this._isDisposed}_disposeVertexArrayObjects(){if(this._vertexArrayObjects){for(const i in this._vertexArrayObjects)this._engine.releaseVertexArrayObject(this._vertexArrayObjects[i]);this._vertexArrayObjects={};const e=this._meshes,t=e.length;for(let i=0;i<t;i++)e[i]._invalidateInstanceVertexArrayObject()}}dispose(){const e=this._meshes,t=e.length;let i;for(i=0;i<t;i++)this.releaseForMesh(e[i]);this._meshes.length=0,this._disposeVertexArrayObjects();for(const s in this._vertexBuffers)this._vertexBuffers[s].dispose();if(this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=0,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._parentContainer){const s=this._parentContainer.geometries.indexOf(this);s>-1&&this._parentContainer.geometries.splice(s,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new me;t.indices=[];const i=this.getIndices();if(i)for(let o=0;o<i.length;o++)t.indices.push(i[o]);let s=!1,r=!1,n;for(n in this._vertexBuffers){const o=this.getVerticesData(n);if(o&&(o instanceof Float32Array?t.set(new Float32Array(o),n):t.set(o.slice(0),n),!r)){const h=this.getVertexBuffer(n);h&&(s=h.isUpdatable(),r=!s)}}const a=new Bt(e,this._scene,t,s);a.delayLoadState=this.delayLoadState,a.delayLoadingFile=this.delayLoadingFile,a._delayLoadingFunction=this._delayLoadingFunction;for(n in this._delayInfo)a._delayInfo=a._delayInfo||[],a._delayInfo.push(n);return a._boundingInfo=new $t(this._extend.minimum,this._extend.maximum),a}serialize(){const e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,xe&&xe.HasTags(this)&&(e.tags=xe.GetTags(this)),e}_toNumberArray(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)}clearCachedData(){this._indices=[],this._resetPointsArrayCache();for(const e in this._vertexBuffers)Object.prototype.hasOwnProperty.call(this._vertexBuffers,e)&&(this._vertexBuffers[e]._buffer._data=null)}serializeVerticeData(){const e=this.serialize();return this.isVerticesDataPresent(A.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(A.PositionKind)),this.isVertexBufferUpdatable(A.PositionKind)&&(e.positions._updatable=!0)),this.isVerticesDataPresent(A.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(A.NormalKind)),this.isVertexBufferUpdatable(A.NormalKind)&&(e.normals._updatable=!0)),this.isVerticesDataPresent(A.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(A.TangentKind)),this.isVertexBufferUpdatable(A.TangentKind)&&(e.tangents._updatable=!0)),this.isVerticesDataPresent(A.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(A.UVKind)),this.isVertexBufferUpdatable(A.UVKind)&&(e.uvs._updatable=!0)),this.isVerticesDataPresent(A.UV2Kind)&&(e.uv2s=this._toNumberArray(this.getVerticesData(A.UV2Kind)),this.isVertexBufferUpdatable(A.UV2Kind)&&(e.uv2s._updatable=!0)),this.isVerticesDataPresent(A.UV3Kind)&&(e.uv3s=this._toNumberArray(this.getVerticesData(A.UV3Kind)),this.isVertexBufferUpdatable(A.UV3Kind)&&(e.uv3s._updatable=!0)),this.isVerticesDataPresent(A.UV4Kind)&&(e.uv4s=this._toNumberArray(this.getVerticesData(A.UV4Kind)),this.isVertexBufferUpdatable(A.UV4Kind)&&(e.uv4s._updatable=!0)),this.isVerticesDataPresent(A.UV5Kind)&&(e.uv5s=this._toNumberArray(this.getVerticesData(A.UV5Kind)),this.isVertexBufferUpdatable(A.UV5Kind)&&(e.uv5s._updatable=!0)),this.isVerticesDataPresent(A.UV6Kind)&&(e.uv6s=this._toNumberArray(this.getVerticesData(A.UV6Kind)),this.isVertexBufferUpdatable(A.UV6Kind)&&(e.uv6s._updatable=!0)),this.isVerticesDataPresent(A.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(A.ColorKind)),this.isVertexBufferUpdatable(A.ColorKind)&&(e.colors._updatable=!0)),this.isVerticesDataPresent(A.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(A.MatricesIndicesKind)),e.matricesIndices._isExpanded=!0,this.isVertexBufferUpdatable(A.MatricesIndicesKind)&&(e.matricesIndices._updatable=!0)),this.isVerticesDataPresent(A.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(A.MatricesWeightsKind)),this.isVertexBufferUpdatable(A.MatricesWeightsKind)&&(e.matricesWeights._updatable=!0)),e.indices=this._toNumberArray(this.getIndices()),e}static ExtractFromMesh(e,t){const i=e._geometry;return i?i.copy(t):null}static RandomId(){return k.RandomId()}static _GetGeometryByLoadedUniqueId(e,t){for(let i=0;i<t.geometries.length;i++)if(t.geometries[i]._loadedUniqueId===e)return t.geometries[i];return null}static _ImportGeometry(e,t){const i=t.getScene(),s=e.geometryUniqueId,r=e.geometryId;if(s||r){const n=s?this._GetGeometryByLoadedUniqueId(s,i):i.getGeometryById(r);n&&n.applyToMesh(t)}else if(e instanceof ArrayBuffer){const n=t._binaryInfo;if(n.positionsAttrDesc&&n.positionsAttrDesc.count>0){const a=new Float32Array(e,n.positionsAttrDesc.offset,n.positionsAttrDesc.count);t.setVerticesData(A.PositionKind,a,!1)}if(n.normalsAttrDesc&&n.normalsAttrDesc.count>0){const a=new Float32Array(e,n.normalsAttrDesc.offset,n.normalsAttrDesc.count);t.setVerticesData(A.NormalKind,a,!1)}if(n.tangetsAttrDesc&&n.tangetsAttrDesc.count>0){const a=new Float32Array(e,n.tangetsAttrDesc.offset,n.tangetsAttrDesc.count);t.setVerticesData(A.TangentKind,a,!1)}if(n.uvsAttrDesc&&n.uvsAttrDesc.count>0){const a=new Float32Array(e,n.uvsAttrDesc.offset,n.uvsAttrDesc.count);if(si.UseOpenGLOrientationForUV)for(let o=1;o<a.length;o+=2)a[o]=1-a[o];t.setVerticesData(A.UVKind,a,!1)}if(n.uvs2AttrDesc&&n.uvs2AttrDesc.count>0){const a=new Float32Array(e,n.uvs2AttrDesc.offset,n.uvs2AttrDesc.count);if(si.UseOpenGLOrientationForUV)for(let o=1;o<a.length;o+=2)a[o]=1-a[o];t.setVerticesData(A.UV2Kind,a,!1)}if(n.uvs3AttrDesc&&n.uvs3AttrDesc.count>0){const a=new Float32Array(e,n.uvs3AttrDesc.offset,n.uvs3AttrDesc.count);if(si.UseOpenGLOrientationForUV)for(let o=1;o<a.length;o+=2)a[o]=1-a[o];t.setVerticesData(A.UV3Kind,a,!1)}if(n.uvs4AttrDesc&&n.uvs4AttrDesc.count>0){const a=new Float32Array(e,n.uvs4AttrDesc.offset,n.uvs4AttrDesc.count);if(si.UseOpenGLOrientationForUV)for(let o=1;o<a.length;o+=2)a[o]=1-a[o];t.setVerticesData(A.UV4Kind,a,!1)}if(n.uvs5AttrDesc&&n.uvs5AttrDesc.count>0){const a=new Float32Array(e,n.uvs5AttrDesc.offset,n.uvs5AttrDesc.count);if(si.UseOpenGLOrientationForUV)for(let o=1;o<a.length;o+=2)a[o]=1-a[o];t.setVerticesData(A.UV5Kind,a,!1)}if(n.uvs6AttrDesc&&n.uvs6AttrDesc.count>0){const a=new Float32Array(e,n.uvs6AttrDesc.offset,n.uvs6AttrDesc.count);if(si.UseOpenGLOrientationForUV)for(let o=1;o<a.length;o+=2)a[o]=1-a[o];t.setVerticesData(A.UV6Kind,a,!1)}if(n.colorsAttrDesc&&n.colorsAttrDesc.count>0){const a=new Float32Array(e,n.colorsAttrDesc.offset,n.colorsAttrDesc.count);t.setVerticesData(A.ColorKind,a,!1,n.colorsAttrDesc.stride)}if(n.matricesIndicesAttrDesc&&n.matricesIndicesAttrDesc.count>0){const a=new Int32Array(e,n.matricesIndicesAttrDesc.offset,n.matricesIndicesAttrDesc.count),o=[];for(let h=0;h<a.length;h++){const c=a[h];o.push(c&255),o.push((c&65280)>>8),o.push((c&16711680)>>16),o.push(c>>24&255)}t.setVerticesData(A.MatricesIndicesKind,o,!1)}if(n.matricesIndicesExtraAttrDesc&&n.matricesIndicesExtraAttrDesc.count>0){const a=new Int32Array(e,n.matricesIndicesExtraAttrDesc.offset,n.matricesIndicesExtraAttrDesc.count),o=[];for(let h=0;h<a.length;h++){const c=a[h];o.push(c&255),o.push((c&65280)>>8),o.push((c&16711680)>>16),o.push(c>>24&255)}t.setVerticesData(A.MatricesIndicesExtraKind,o,!1)}if(n.matricesWeightsAttrDesc&&n.matricesWeightsAttrDesc.count>0){const a=new Float32Array(e,n.matricesWeightsAttrDesc.offset,n.matricesWeightsAttrDesc.count);t.setVerticesData(A.MatricesWeightsKind,a,!1)}if(n.indicesAttrDesc&&n.indicesAttrDesc.count>0){const a=new Int32Array(e,n.indicesAttrDesc.offset,n.indicesAttrDesc.count);t.setIndices(a,null)}if(n.subMeshesAttrDesc&&n.subMeshesAttrDesc.count>0){const a=new Int32Array(e,n.subMeshesAttrDesc.offset,n.subMeshesAttrDesc.count*5);t.subMeshes=[];for(let o=0;o<n.subMeshesAttrDesc.count;o++){const h=a[o*5+0],c=a[o*5+1],u=a[o*5+2],f=a[o*5+3],d=a[o*5+4];ci.AddToMesh(h,c,u,f,d,t)}}}else if(e.positions&&e.normals&&e.indices){if(t.setVerticesData(A.PositionKind,e.positions,e.positions._updatable),t.setVerticesData(A.NormalKind,e.normals,e.normals._updatable),e.tangents&&t.setVerticesData(A.TangentKind,e.tangents,e.tangents._updatable),e.uvs&&t.setVerticesData(A.UVKind,e.uvs,e.uvs._updatable),e.uvs2&&t.setVerticesData(A.UV2Kind,e.uvs2,e.uvs2._updatable),e.uvs3&&t.setVerticesData(A.UV3Kind,e.uvs3,e.uvs3._updatable),e.uvs4&&t.setVerticesData(A.UV4Kind,e.uvs4,e.uvs4._updatable),e.uvs5&&t.setVerticesData(A.UV5Kind,e.uvs5,e.uvs5._updatable),e.uvs6&&t.setVerticesData(A.UV6Kind,e.uvs6,e.uvs6._updatable),e.colors&&t.setVerticesData(A.ColorKind,ge.CheckColors4(e.colors,e.positions.length/3),e.colors._updatable),e.matricesIndices)if(e.matricesIndices._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(A.MatricesIndicesKind,e.matricesIndices,e.matricesIndices._updatable);else{const n=[];for(let a=0;a<e.matricesIndices.length;a++){const o=e.matricesIndices[a];n.push(o&255),n.push((o&65280)>>8),n.push((o&16711680)>>16),n.push(o>>24&255)}t.setVerticesData(A.MatricesIndicesKind,n,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(A.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const n=[];for(let a=0;a<e.matricesIndicesExtra.length;a++){const o=e.matricesIndicesExtra[a];n.push(o&255),n.push((o&65280)>>8),n.push((o&16711680)>>16),n.push(o>>24&255)}t.setVerticesData(A.MatricesIndicesExtraKind,n,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(Bt._CleanMatricesWeights(e,t),t.setVerticesData(A.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(A.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let n=0;n<e.subMeshes.length;n++){const a=e.subMeshes[n];ci.AddToMesh(a.materialIndex,a.verticesStart,a.verticesCount,a.indexStart,a.indexCount,t)}}t._shouldGenerateFlatShading&&(t.convertToFlatShadedMesh(),t._shouldGenerateFlatShading=!1),t.computeWorldMatrix(!0),i.onMeshImportedObservable.notifyObservers(t)}static _CleanMatricesWeights(e,t){if(!ct.CleanBoneMatrixWeights)return;let s=0;if(e.skeletonId>-1){const u=t.getScene().getLastSkeletonById(e.skeletonId);if(!u)return;s=u.bones.length}else return;const r=t.getVerticesData(A.MatricesIndicesKind),n=t.getVerticesData(A.MatricesIndicesExtraKind),a=e.matricesWeights,o=e.matricesWeightsExtra,h=e.numBoneInfluencer,c=a.length;for(let u=0;u<c;u+=4){let f=0,d=-1;for(let _=0;_<4;_++){const p=a[u+_];f+=p,p<.001&&d<0&&(d=_)}if(o)for(let _=0;_<4;_++){const p=o[u+_];f+=p,p<.001&&d<0&&(d=_+4)}if((d<0||d>h-1)&&(d=h-1),f>.001){const _=1/f;for(let p=0;p<4;p++)a[u+p]*=_;if(o)for(let p=0;p<4;p++)o[u+p]*=_}else d>=4?(o[u+d-4]=1-f,n[u+d-4]=s):(a[u+d]=1-f,r[u+d]=s)}t.setVerticesData(A.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(A.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new Bt(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,xe&&xe.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new $t(E.FromArray(e.boundingBoxMinimum),E.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(A.UVKind),e.hasUVs2&&s._delayInfo.push(A.UV2Kind),e.hasUVs3&&s._delayInfo.push(A.UV3Kind),e.hasUVs4&&s._delayInfo.push(A.UV4Kind),e.hasUVs5&&s._delayInfo.push(A.UV5Kind),e.hasUVs6&&s._delayInfo.push(A.UV6Kind),e.hasColors&&s._delayInfo.push(A.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(A.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(A.MatricesWeightsKind),s._delayLoadingFunction=me.ImportVertexData):me.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class Yh{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new Kh(e)}sampleFrame(e=ii.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 Kh{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}}re.prototype.setAlphaConstants=function(l,e,t,i){this._alphaState.setAlphaBlendConstants(l,e,t,i)},re.prototype.setAlphaMode=function(l,e=!1){if(this._alphaMode===l){if(!e){const t=l===0;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(l){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=l===0),this._alphaMode=l},re.prototype.getAlphaMode=function(){return this._alphaMode},re.prototype.setAlphaEquation=function(l){if(this._alphaEquation!==l){switch(l){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=l}},re.prototype.getAlphaEquation=function(){return this._alphaEquation};function jh(l,e,t=!1,i){switch(l){case 3:{const r=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e);return i&&r.set(new Int8Array(i)),r}case 0:{const r=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&r.set(new Uint8Array(i)),r}case 4:{const r=e instanceof ArrayBuffer?new Int16Array(e):new Int16Array(t?e/2:e);return i&&r.set(new Int16Array(i)),r}case 5:case 8:case 9:case 10:case 2:{const r=e instanceof ArrayBuffer?new Uint16Array(e):new Uint16Array(t?e/2:e);return i&&r.set(new Uint16Array(i)),r}case 6:{const r=e instanceof ArrayBuffer?new Int32Array(e):new Int32Array(t?e/4:e);return i&&r.set(new Int32Array(i)),r}case 7:case 11:case 12:case 13:case 14:case 15:{const r=e instanceof ArrayBuffer?new Uint32Array(e):new Uint32Array(t?e/4:e);return i&&r.set(new Uint32Array(i)),r}case 1:{const r=e instanceof ArrayBuffer?new Float32Array(e):new Float32Array(t?e/4:e);return i&&r.set(new Float32Array(i)),r}}const s=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&s.set(new Uint8Array(i)),s}re.prototype._readTexturePixelsSync=function(l,e,t,i=-1,s=0,r=null,n=!0,a=!1,o=0,h=0){var c,u;const f=this._gl;if(!f)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const _=f.createFramebuffer();if(!_)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=_}f.bindFramebuffer(f.FRAMEBUFFER,this._dummyFramebuffer),i>-1?f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_CUBE_MAP_POSITIVE_X+i,(c=l._hardwareTexture)===null||c===void 0?void 0:c.underlyingResource,s):f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,(u=l._hardwareTexture)===null||u===void 0?void 0:u.underlyingResource,s);let d=l.type!==void 0?this._getWebGLTextureType(l.type):f.UNSIGNED_BYTE;if(a)r||(r=jh(l.type,4*e*t));else switch(d){case f.UNSIGNED_BYTE:r||(r=new Uint8Array(4*e*t)),d=f.UNSIGNED_BYTE;break;default:r||(r=new Float32Array(4*e*t)),d=f.FLOAT;break}return n&&this.flushFramebuffer(),f.readPixels(o,h,e,t,f.RGBA,d,r),f.bindFramebuffer(f.FRAMEBUFFER,this._currentFramebuffer),r},re.prototype._readTexturePixels=function(l,e,t,i=-1,s=0,r=null,n=!0,a=!1,o=0,h=0){return Promise.resolve(this._readTexturePixelsSync(l,e,t,i,s,r,n,a,o,h))},re.prototype.updateDynamicIndexBuffer=function(l,e,t=0){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(l);let i;l.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()},re.prototype.updateDynamicVertexBuffer=function(l,e,t,i){this.bindArrayBuffer(l),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()};class L extends re{static get NpmPackage(){return re.NpmPackage}static get Version(){return re.Version}static get Instances(){return Ee.Instances}static get LastCreatedEngine(){return Ee.LastCreatedEngine}static get LastCreatedScene(){return Ee.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise((s,r)=>{const n=new Image;n.onload=()=>{n.decode().then(()=>{this.createImageBitmap(n,t).then(a=>{s(a)})})},n.onerror=()=>{r(`Error loading image ${n.src}`)},n.src=e})}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){const r=this.createCanvas(t,i).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(e,0,0),r.getImageData(0,0,t,i).data}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i<L.Instances.length;i++){const s=L.Instances[i];for(let r=0;r<s.scenes.length;r++)s.scenes[r].markAllMaterialsAsDirty(e,t)}}static DefaultLoadingScreenFactory(e){throw fe("LoadingScreen")}get _supportsHardwareTextureRescaling(){return!!L._RescalePostProcessFactory}get performanceMonitor(){return this._performanceMonitor}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=!0}getInputElement(){return this._renderingCanvas}constructor(e,t,i,s=!1){if(super(e,t,i,s),this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.scenes=new Array,this._virtualScenes=new Array,this.onNewSceneAddedObservable=new B,this.postProcesses=new Array,this.isPointerLock=!1,this.onResizeObservable=new B,this.onCanvasBlurObservable=new B,this.onCanvasFocusObservable=new B,this.onCanvasPointerOutObservable=new B,this.onBeginFrameObservable=new B,this.customAnimationFrameRequester=null,this.onEndFrameObservable=new B,this.onBeforeShaderCompilationObservable=new B,this.onAfterShaderCompilationObservable=new B,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this._fps=60,this._deltaTime=0,this._drawCalls=new Ci,this.canvasTabIndex=1,this.disablePerformanceMonitorInBackground=!1,this._performanceMonitor=new Yh,this._compatibilityMode=!0,this.currentRenderPassId=0,this._renderPassNames=["main"],L.Instances.push(this),!!e){if(this._features.supportRenderPasses=!0,i=this._creationOptions,e.getContext){const r=e;this._sharedInit(r),this._connectVREvents()}this._prepareVRComponent(),i.autoEnableWebVR&&this.initWebVR()}}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),this._onCanvasFocus=()=>{this.onCanvasFocusObservable.notifyObservers(this)},this._onCanvasBlur=()=>{this.onCanvasBlurObservable.notifyObservers(this)},this._onCanvasContextMenu=i=>{this.disableContextMenu&&i.preventDefault()},e.addEventListener("focus",this._onCanvasFocus),e.addEventListener("blur",this._onCanvasBlur),e.addEventListener("contextmenu",this._onCanvasContextMenu),this._onBlur=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.disable(),this._windowIsBackground=!0},this._onFocus=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.enable(),this._windowIsBackground=!1},this._onCanvasPointerOut=i=>{document.elementFromPoint(i.clientX,i.clientY)!==e&&this.onCanvasPointerOutObservable.notifyObservers(i)};const t=this.getHostWindow();t&&typeof t.addEventListener=="function"&&(t.addEventListener("blur",this._onBlur),t.addEventListener("focus",this._onFocus)),e.addEventListener("pointerout",this._onCanvasPointerOut),this._creationOptions.doNotHandleTouchAction||this._disableTouchAction(),!L.audioEngine&&this._creationOptions.audioEngine&&L.AudioEngineFactory&&(L.audioEngine=L.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),_r()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&L._RequestPointerlock(e)},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=()=>{this.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1)),this.enableOfflineSupport=L.OfflineProviderFactory!==void 0,this._deterministicLockstep=!!this._creationOptions.deterministicLockstep,this._lockstepMaxSteps=this._creationOptions.lockstepMaxSteps||0,this._timeStep=this._creationOptions.timeStep||1/60}_verifyPointerLock(){var e;(e=this._onPointerLockChange)===null||e===void 0||e.call(this)}getAspectRatio(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)}getScreenAspectRatio(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)}getRenderingCanvasClientRect(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null}getInputElementClientRect(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return this._timeStep*1e3}generateMipMapsForCubemap(e,t=!0){if(e.generateMipMaps){const i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}}getDepthWrite(){return this._depthCullingState.depthMask}setDepthWrite(e){this._depthCullingState.depthMask=e}getStencilBuffer(){return this._stencilState.stencilTest}setStencilBuffer(e){this._stencilState.stencilTest=e}getStencilMask(){return this._stencilState.stencilMask}setStencilMask(e){this._stencilState.stencilMask=e}getStencilFunction(){return this._stencilState.stencilFunc}getStencilFunctionReference(){return this._stencilState.stencilFuncRef}getStencilFunctionMask(){return this._stencilState.stencilFuncMask}setStencilFunction(e){this._stencilState.stencilFunc=e}setStencilFunctionReference(e){this._stencilState.stencilFuncRef=e}setStencilFunctionMask(e){this._stencilState.stencilFuncMask=e}getStencilOperationFail(){return this._stencilState.stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilState.stencilOpDepthFail}getStencilOperationPass(){return this._stencilState.stencilOpStencilDepthPass}setStencilOperationFail(e){this._stencilState.stencilOpStencilFail=e}setStencilOperationDepthFail(e){this._stencilState.stencilOpDepthFail=e}setStencilOperationPass(e){this._stencilState.stencilOpStencilDepthPass=e}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}getDepthFunction(){return this._depthCullingState.depthFunc}setDepthFunction(e){this._depthCullingState.depthFunc=e}setDepthFunctionToGreater(){this.setDepthFunction(516)}setDepthFunctionToGreaterOrEqual(){this.setDepthFunction(518)}setDepthFunctionToLess(){this.setDepthFunction(513)}setDepthFunctionToLessOrEqual(){this.setDepthFunction(515)}cacheStencilState(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()}restoreStencilState(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)}setDirectViewport(e,t,i,s){const r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,s),r}scissorClear(e,t,i,s,r){this.enableScissor(e,t,i,s),this.clear(r,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,s){const r=this._gl;r.enable(r.SCISSOR_TEST),r.scissor(e,t,i,s)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}initWebVR(){throw fe("WebVRCamera")}_prepareVRComponent(){}_connectVREvents(e,t){}_submitVRFrame(){}disableVR(){}isVRPresenting(){return!1}_requestVRFrame(){}_loadFileAsync(e,t,i){return new Promise((s,r)=>{this._loadFile(e,n=>{s(n)},void 0,t,i,(n,a)=>{r(a)})})}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,s){e!==void 0&&(t&&(this._boundUniforms[e]=t),!i||!i.depthStencilTexture?this._setTexture(e,null,void 0,void 0,s):this._setTexture(e,i,!1,!0,s))}setTextureFromPostProcess(e,t,i){var s;let r=null;t&&(t._forcedOutputTexture?r=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(r=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,(s=r==null?void 0:r.texture)!==null&&s!==void 0?s:null,i)}setTextureFromPostProcessOutput(e,t,i){var s,r;this._bindTexture(e,(r=(s=t==null?void 0:t._outputTexture)===null||s===void 0?void 0:s.texture)!==null&&r!==void 0?r:null,i)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();super._rebuildBuffers()}_renderFrame(){for(let e=0;e<this._activeRenderLoops.length;e++){const t=this._activeRenderLoops[e];t()}}_renderLoop(){if(!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.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this.isVRPresenting()?this._requestVRFrame():this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&L._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&L._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&L._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){L._ExitPointerlock()}beginFrame(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),super.beginFrame()}endFrame(){super.endFrame(),this._submitVRFrame(),this.onEndFrameObservable.notifyObservers(this)}resize(e=!1){this.isVRPresenting()||super.resize(e)}setSize(e,t,i=!1){if(!this._renderingCanvas||!super.setSize(e,t,i))return!1;if(this.scenes){for(let s=0;s<this.scenes.length;s++){const r=this.scenes[s];for(let n=0;n<r.cameras.length;n++){const a=r.cameras[n];a._currentRenderId=0}}this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this)}return!0}_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,r,n=null){r=r||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const a=super.createShaderProgram(e,t,i,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),a}_createShaderProgram(e,t,i,s,r=null){const n=s.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");if(s.attachShader(n,t),s.attachShader(n,i),this.webGLVersion>1&&r){const a=this.createTransformFeedback();this.bindTransformFeedback(a),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=a}return s.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_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)})})})}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){const t=++L._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t<this.scenes.length;++t){const i=this.scenes[t];for(let s=0;s<i.meshes.length;++s){const r=i.meshes[s];if(r.subMeshes)for(let n=0;n<r.subMeshes.length;++n)r.subMeshes[n]._removeDrawWrapper(e)}}}_rescaleTexture(e,t,i,s,r){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&L._RescalePostProcessFactory&&(this._rescalePostProcess=L._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled(()=>{this._rescalePostProcess.onApply=function(o){o._bindTexture("textureSampler",e)};let a=i;a||(a=this.scenes[this.scenes.length-1]),a.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()}))}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}wrapWebGLTexture(e,t=!1,i=3){const s=new ro(e,this._gl),r=new ht(this,Fe.Unknown,!0);return r._hardwareTexture=s,r.isReady=!0,r.useMipMaps=t,this.updateTextureSamplingMode(i,r),r}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,a),h=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(h,e,!0),this._unpackFlipY(e.invertY);let c=r.TEXTURE_2D;e.isCube&&(c=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(c,s,o,a,n,t),this._bindTextureDirectly(h,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){F.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 Er(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((r,n)=>{const a=()=>{const o=s.clientWaitSync(e,t,0);if(o==s.WAIT_FAILED){n();return}if(o==s.TIMEOUT_EXPIRED){setTimeout(a,i);return}r()};a()})}_readPixelsAsync(e,t,i,s,r,n,a){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const o=this._gl,h=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,h),o.bufferData(o.PIXEL_PACK_BUFFER,a.byteLength,o.STREAM_READ),o.readPixels(e,t,i,s,r,n,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);const c=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return c?(o.flush(),this._clientWaitAsync(c,0,10).then(()=>(o.deleteSync(c),o.bindBuffer(o.PIXEL_PACK_BUFFER,h),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,a),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(h),a))):null}dispose(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();Ee.Instances.length===1&&L.audioEngine&&(L.audioEngine.dispose(),L.audioEngine=null),this.disableVR();const e=this.getHostWindow();e&&typeof e.removeEventListener=="function"&&(e.removeEventListener("blur",this._onBlur),e.removeEventListener("focus",this._onFocus)),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._renderingCanvas.removeEventListener("contextmenu",this._onCanvasContextMenu)),_r()&&(document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)),super.dispose();const t=Ee.Instances.indexOf(this);t>=0&&Ee.Instances.splice(t,1),L.Instances.length||Ee.OnEnginesDisposedObservable.notifyObservers(this),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}_disableTouchAction(){!this._renderingCanvas||!this._renderingCanvas.setAttribute||(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.webkitTapHighlightColor="transparent")}displayLoadingUI(){if(!Mt())return;const e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!Mt())return;const e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=L.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen}set loadingScreen(e){this._loadingScreen=e}set loadingUIText(e){this.loadingScreen.loadingUIText=e}set loadingUIBackgroundColor(e){this.loadingScreen.loadingUIBackgroundColor=e}createVideoElement(e){return document.createElement("video")}static _RequestPointerlock(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then(()=>{e.focus()}).catch(()=>{}):e.focus()}}static _ExitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}static _RequestFullscreen(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}static _ExitFullscreen(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}getFontOffset(e){const t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style",`font: ${e} !important`);const i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";const s=document.createElement("div");s.style.whiteSpace="nowrap",s.appendChild(t),s.appendChild(i),document.body.appendChild(s);let r=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",r=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(s)}return{ascent:r,height:n,descent:n-r}}}L.ALPHA_DISABLE=0,L.ALPHA_ADD=1,L.ALPHA_COMBINE=2,L.ALPHA_SUBTRACT=3,L.ALPHA_MULTIPLY=4,L.ALPHA_MAXIMIZED=5,L.ALPHA_ONEONE=6,L.ALPHA_PREMULTIPLIED=7,L.ALPHA_PREMULTIPLIED_PORTERDUFF=8,L.ALPHA_INTERPOLATE=9,L.ALPHA_SCREENMODE=10,L.DELAYLOADSTATE_NONE=0,L.DELAYLOADSTATE_LOADED=1,L.DELAYLOADSTATE_LOADING=2,L.DELAYLOADSTATE_NOTLOADED=4,L.NEVER=512,L.ALWAYS=519,L.LESS=513,L.EQUAL=514,L.LEQUAL=515,L.GREATER=516,L.GEQUAL=518,L.NOTEQUAL=517,L.KEEP=7680,L.REPLACE=7681,L.INCR=7682,L.DECR=7683,L.INVERT=5386,L.INCR_WRAP=34055,L.DECR_WRAP=34056,L.TEXTURE_CLAMP_ADDRESSMODE=0,L.TEXTURE_WRAP_ADDRESSMODE=1,L.TEXTURE_MIRROR_ADDRESSMODE=2,L.TEXTUREFORMAT_ALPHA=0,L.TEXTUREFORMAT_LUMINANCE=1,L.TEXTUREFORMAT_LUMINANCE_ALPHA=2,L.TEXTUREFORMAT_RGB=4,L.TEXTUREFORMAT_RGBA=5,L.TEXTUREFORMAT_RED=6,L.TEXTUREFORMAT_R=6,L.TEXTUREFORMAT_RG=7,L.TEXTUREFORMAT_RED_INTEGER=8,L.TEXTUREFORMAT_R_INTEGER=8,L.TEXTUREFORMAT_RG_INTEGER=9,L.TEXTUREFORMAT_RGB_INTEGER=10,L.TEXTUREFORMAT_RGBA_INTEGER=11,L.TEXTURETYPE_UNSIGNED_BYTE=0,L.TEXTURETYPE_UNSIGNED_INT=0,L.TEXTURETYPE_FLOAT=1,L.TEXTURETYPE_HALF_FLOAT=2,L.TEXTURETYPE_BYTE=3,L.TEXTURETYPE_SHORT=4,L.TEXTURETYPE_UNSIGNED_SHORT=5,L.TEXTURETYPE_INT=6,L.TEXTURETYPE_UNSIGNED_INTEGER=7,L.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,L.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,L.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,L.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,L.TEXTURETYPE_UNSIGNED_INT_24_8=12,L.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,L.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,L.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,L.TEXTURE_NEAREST_SAMPLINGMODE=1,L.TEXTURE_BILINEAR_SAMPLINGMODE=2,L.TEXTURE_TRILINEAR_SAMPLINGMODE=3,L.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,L.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,L.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,L.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,L.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,L.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,L.TEXTURE_NEAREST_LINEAR=7,L.TEXTURE_NEAREST_NEAREST=1,L.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,L.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,L.TEXTURE_LINEAR_LINEAR=2,L.TEXTURE_LINEAR_NEAREST=12,L.TEXTURE_EXPLICIT_MODE=0,L.TEXTURE_SPHERICAL_MODE=1,L.TEXTURE_PLANAR_MODE=2,L.TEXTURE_CUBIC_MODE=3,L.TEXTURE_PROJECTION_MODE=4,L.TEXTURE_SKYBOX_MODE=5,L.TEXTURE_INVCUBIC_MODE=6,L.TEXTURE_EQUIRECTANGULAR_MODE=7,L.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,L.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,L.SCALEMODE_FLOOR=1,L.SCALEMODE_NEAREST=2,L.SCALEMODE_CEILING=3,L._RescalePostProcessFactory=null,L._RenderPassIdCounter=0;var we;(function(l){l[l.LOCAL=0]="LOCAL",l[l.WORLD=1]="WORLD",l[l.BONE=2]="BONE"})(we||(we={}));class As{}As.X=new E(1,0,0),As.Y=new E(0,1,0),As.Z=new E(0,0,1);var vs;(function(l){l[l.X=0]="X",l[l.Y=1]="Y",l[l.Z=2]="Z"})(vs||(vs={}));const qh=M.Compose(E.One(),K.FromEulerAngles(0,Math.PI,0),E.Zero());class pe extends lt{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&pe.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!==pe.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t),this._forward=new E(0,0,1),this._up=new E(0,1,0),this._right=new E(1,0,0),this._position=E.Zero(),this._rotation=E.Zero(),this._rotationQuaternion=null,this._scaling=E.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=pe.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=M.Zero(),this._usePivotMatrix=!1,this._absolutePosition=E.Zero(),this._absoluteScaling=E.Zero(),this._absoluteRotationQuaternion=K.Identity(),this._pivotMatrix=M.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new B,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return E.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return E.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return E.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=M.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==pe.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=M.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 r of this.getChildTransformNodes(!0))r.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||K.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,s;if(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 r=D.Matrix[0];this.parent.getWorldMatrix().invertToRef(r),E.TransformCoordinatesFromFloatsToRef(t,i,s,r,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=E.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=D.Matrix[0];return this._localMatrix.invertToRef(e),E.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=E.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=we.LOCAL){const n=pe._LookAtVectorCache,a=r===we.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,n),this.setDirection(n,t,i,s),r===we.WORLD&&this.parent)if(this.rotationQuaternion){const o=D.Matrix[0];this.rotationQuaternion.toRotationMatrix(o);const h=D.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(h),h.invert(),o.multiplyToRef(h,o),this.rotationQuaternion.fromRotationMatrix(o)}else{const o=D.Quaternion[0];K.FromEulerVectorToRef(this.rotation,o);const h=D.Matrix[0];o.toRotationMatrix(h);const c=D.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),h.multiplyToRef(c,h),o.fromRotationMatrix(h),o.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=E.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return E.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,n);return this.rotationQuaternion?K.RotationYawPitchRollToRef(r+t,a+i,s,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=we.LOCAL){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==we.WORLD){const s=D.Matrix[0];i.invertToRef(s),e=E.TransformCoordinates(e,s)}return this.setPivotMatrix(M.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=E.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=E.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),E.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=D.Quaternion[0],r=D.Vector3[0],n=D.Vector3[1],a=D.Matrix[1];M.IdentityToRef(a);const o=D.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=pe._TmpRotation,K.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),M.ComposeToRef(this.scaling,h,this.position,o),this.parent&&o.multiplyToRef(this.parent.computeWorldMatrix(!0),o),e&&(e.computeWorldMatrix(!0).invertToRef(a),o.multiplyToRef(a,o)),o.decompose(n,s,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(r),this.parent=e,i&&this.setPivotMatrix(M.Identity()),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(),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===we.LOCAL)s=K.RotationAxisToRef(e,t,pe._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);else{if(this.parent){const r=D.Matrix[0];this.parent.getWorldMatrix().invertToRef(r),e=E.TransformNormal(e,r)}s=K.RotationAxisToRef(e,t,pe._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=K.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=D.Vector3[0],r=D.Vector3[1],n=D.Vector3[2],a=D.Quaternion[0],o=D.Matrix[0],h=D.Matrix[1],c=D.Matrix[2],u=D.Matrix[3];return e.subtractToRef(this.position,s),M.TranslationToRef(s.x,s.y,s.z,o),M.TranslationToRef(-s.x,-s.y,-s.z,h),M.RotationAxisToRef(t,i,c),h.multiplyToRef(c,u),u.multiplyToRef(o,u),u.decompose(r,a,n),this.position.addInPlace(n),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(!i||i===we.LOCAL){const r=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(r)}else this.setAbsolutePosition(this.getAbsolutePosition().add(s));return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=D.Quaternion[1],K.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=D.Quaternion[0];return K.RotationYawPitchRollToRef(t,e,i,r),s.multiplyInPlace(r),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==pe.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 r=this._getEffectiveParent(),n=pe._TmpScaling;let a=this._position;if(this._infiniteDistance&&!this.parent&&t){const h=t.getWorldMatrix(),c=new E(h.m[12],h.m[13],h.m[14]);a=pe._TmpTranslation,a.copyFromFloats(this._position.x+c.x,this._position.y+c.y,this._position.z+c.z)}n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant);let o;if(this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,o=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(K.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(o=pe._TmpRotation,K.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,o)),this._usePivotMatrix){const h=D.Matrix[1];M.ScalingToRef(n.x,n.y,n.z,h);const c=D.Matrix[0];o.toRotationMatrix(c),this._pivotMatrix.multiplyToRef(h,D.Matrix[4]),D.Matrix[4].multiplyToRef(c,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(a.x,a.y,a.z)}else M.ComposeToRef(n,o,a,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),s.useBillboardPath){this._transformToBoneReferal?r.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),D.Matrix[7]):D.Matrix[7].copyFrom(r.getWorldMatrix());const h=D.Vector3[5],c=D.Vector3[6],u=D.Quaternion[0];D.Matrix[7].decompose(c,u,h),M.ScalingToRef(c.x,c.y,c.z,D.Matrix[7]),D.Matrix[7].setTranslation(h),pe.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(u,h),this._localMatrix.setTranslation(h)),this._localMatrix.multiplyToRef(D.Matrix[7],this._worldMatrix)}else this._transformToBoneReferal?(this._localMatrix.multiplyToRef(r.getWorldMatrix(),D.Matrix[6]),D.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const h=D.Vector3[0];if(this._worldMatrix.getTranslationToRef(h),D.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&D.Matrix[1].multiplyToRef(qh,D.Matrix[1]),D.Matrix[1].setTranslationFromFloats(0,0,0),D.Matrix[1].invertToRef(D.Matrix[0]),(this.billboardMode&pe.BILLBOARDMODE_ALL)!==pe.BILLBOARDMODE_ALL){D.Matrix[0].decompose(void 0,D.Quaternion[0],void 0);const c=D.Vector3[1];D.Quaternion[0].toEulerAnglesToRef(c),(this.billboardMode&pe.BILLBOARDMODE_X)!==pe.BILLBOARDMODE_X&&(c.x=0),(this.billboardMode&pe.BILLBOARDMODE_Y)!==pe.BILLBOARDMODE_Y&&(c.y=0),(this.billboardMode&pe.BILLBOARDMODE_Z)!==pe.BILLBOARDMODE_Z&&(c.z=0),M.RotationYawPitchRollToRef(c.y,c.x,c.z,D.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(D.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(D.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const h=D.Vector3[0];this._worldMatrix.getTranslationToRef(h);const c=t.globalPosition;this._worldMatrix.invertToRef(D.Matrix[1]);const u=D.Vector3[1];E.TransformCoordinatesToRef(c,D.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),_=-Math.atan2(u.y,d);if(K.RotationYawPitchRollToRef(f,_,0,D.Quaternion[0]),(this.billboardMode&pe.BILLBOARDMODE_ALL)!==pe.BILLBOARDMODE_ALL){const p=D.Vector3[1];D.Quaternion[0].toEulerAnglesToRef(p),(this.billboardMode&pe.BILLBOARDMODE_X)!==pe.BILLBOARDMODE_X&&(p.x=0),(this.billboardMode&pe.BILLBOARDMODE_Y)!==pe.BILLBOARDMODE_Y&&(p.y=0),(this.billboardMode&pe.BILLBOARDMODE_Z)!==pe.BILLBOARDMODE_Z&&(p.z=0),M.RotationYawPitchRollToRef(p.y,p.x,p.z,D.Matrix[0])}else M.FromQuaternionToRef(D.Quaternion[0],D.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(D.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(D.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._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=M.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const t=this.getChildren();for(let i=0;i<t.length;++i){const s=t[i];if(s){s.computeWorldMatrix();const r=D.Matrix[0];s._localMatrix.multiplyToRef(this._localMatrix,r);const n=D.Quaternion[0];r.decompose(s.scaling,n,s.position),s.rotationQuaternion?s.rotationQuaternion.copyFrom(n):n.toEulerAnglesToRef(s.rotation)}}}this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=K.Identity()),this._worldMatrix=M.Identity()}_afterComputeWorldMatrix(){}registerAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this}unregisterAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this}getPositionInCameraSpace(e=null){return e||(e=this.getScene().activeCamera),E.TransformCoordinates(this.getAbsolutePosition(),e.getViewMatrix())}getDistanceToCamera(e=null){return e||(e=this.getScene().activeCamera),this.getAbsolutePosition().subtract(e.globalPosition).length()}clone(e,t,i){const s=J.Clone(()=>new pe(e,this.getScene()),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const r=this.getDescendants(!0);for(let n=0;n<r.length;n++){const a=r[n];a.clone&&a.clone(e+"."+a.name,s)}}return s}serialize(e){const t=J.Serialize(this,e);return t.type=this.getClassName(),t.uniqueId=this.uniqueId,this.parent&&this.parent._serializeAsParent(t),t.localMatrix=this.getPivotMatrix().asArray(),t.isEnabled=this.isEnabled(),t}static Parse(e,t,i){const s=J.Parse(()=>new pe(e.name,t),e,t,i);return e.localMatrix?s.setPreTransformMatrix(M.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(M.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),s}getChildTransformNodes(e,t){const i=[];return this._getDescendants(i,e,s=>(!t||t(s))&&s instanceof pe),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,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),a=n.max.subtract(n.min),o=Math.max(a.x,a.y,a.z);if(o===0)return this;const h=1/o;return this.scaling.scaleInPlace(h),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}pe.BILLBOARDMODE_NONE=0,pe.BILLBOARDMODE_X=1,pe.BILLBOARDMODE_Y=2,pe.BILLBOARDMODE_Z=4,pe.BILLBOARDMODE_ALL=7,pe.BILLBOARDMODE_USE_POSITION=128,pe.BillboardUseParentOrientation=!1,pe._TmpRotation=K.Zero(),pe._TmpScaling=E.Zero(),pe._TmpTranslation=E.Zero(),pe._LookAtVectorCache=new E(0,0,0),pe._RotationAxisCache=new K,g([Ut("position")],pe.prototype,"_position",void 0),g([Ut("rotation")],pe.prototype,"_rotation",void 0),g([oh("rotationQuaternion")],pe.prototype,"_rotationQuaternion",void 0),g([Ut("scaling")],pe.prototype,"_scaling",void 0),g([v("billboardMode")],pe.prototype,"_billboardMode",void 0),g([v()],pe.prototype,"scalingDeterminant",void 0),g([v("infiniteDistance")],pe.prototype,"_infiniteDistance",void 0),g([v()],pe.prototype,"ignoreNonUniformScaling",void 0),g([v()],pe.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class Zh{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new E(0,0,0),this._diffPositionForCollisions=new E(0,0,0),this._collisionResponse=!0}}class Qh{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=E.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class $h{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Qh,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 Zh,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class Vt extends pe{static get BILLBOARDMODE_NONE(){return pe.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return pe.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return pe.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return pe.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return pe.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return pe.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._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||t===void 0?void 0:t[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new $h,this._waitingMaterialId=null,this.cullingStrategy=Vt.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new B,this.onCollisionPositionChangeObservable=new B,this.onMaterialChangedObservable=new B,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=z.Red(),this.outlineWidth=.02,this.overlayColor=z.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 E(.5,1,.5),this.ellipsoidOffset=new E(0,0,0),this.edgesWidth=1,this.edgesColor=new ge(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 B,this._onCollisionPositionChange=(i,s,r=null)=>{s.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>L.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),r&&this.onCollideObservable.notifyObservers(r),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},t=this.getScene(),t.addMesh(this),this._resyncLightSources(),this._uniformBuffer=new q(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case bi.Aggressive:this.doNotSyncBoundingInfo=!0;case bi.Intermediate: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!==pe.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()}_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;i<t._drawWrappers.length;++i){const s=t._drawWrappers[i];!s||!s.defines||!s.defines.markAllAsDirty||e(s.defines)}}_markSubMeshesAsLightDirty(e=!1){this._markSubMeshesAsDirty(t=>t.markAsLightDirty(e))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty(e=>e.markAsAttributesDirty())}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty(e=>e.markAsMiscDirty())}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,s){return this}updateVerticesData(e,t,i,s){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){var e;return(e=this.rawBoundingInfo)!==null&&e!==void 0?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return this._boundingInfo!==null}buildBoundingInfo(e,t,i){return this._boundingInfo=new $t(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(A.MatricesIndicesKind)&&this.isVerticesDataPresent(A.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===pe.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 M;(this.rotationQuaternion?this.rotationQuaternion:K.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const n=E.Zero(),a=this.definedFacingForward?-1:1;return E.TransformCoordinatesFromFloatsToRef(e*a,t,i*a,s,n),n}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const s=this.definedFacingForward?1:-1;return new E(e*s,t,i*s)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked?this:(this._refreshBoundingInfo(this._getPositionData(e,t),null),this)}_refreshBoundingInfo(e,t){if(e){const i=bo(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new $t(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i<this.subMeshes.length;i++)this.subMeshes[i].refreshBoundingInfo(e);this._updateBoundingInfo()}_getData(e=!1,t=!1,i,s=A.PositionKind){if(i=i??this.getVerticesData(s).slice(),i&&t&&this.morphTargetManager){let r=0,n=0;for(let a=0;a<i.length;a++){for(let o=0;o<this.morphTargetManager.numTargets;o++){const h=this.morphTargetManager.getTarget(o),c=h.influence;if(c>0){const u=h.getPositions();u&&(i[a]+=(u[a]-i[a])*c)}}if(r++,s===A.PositionKind&&this._positions&&r===3){r=0;const o=n*3;this._positions[n++].copyFromFloats(i[o],i[o+1],i[o+2])}}}if(i&&e&&this.skeleton){const r=this.getVerticesData(A.MatricesIndicesKind),n=this.getVerticesData(A.MatricesWeightsKind);if(n&&r){const a=this.numBoneInfluencers>4,o=a?this.getVerticesData(A.MatricesIndicesExtraKind):null,h=a?this.getVerticesData(A.MatricesWeightsExtraKind):null,c=this.skeleton.getTransformMatrices(this),u=D.Vector3[0],f=D.Matrix[0],d=D.Matrix[1];let _=0;for(let p=0;p<i.length;p+=3,_+=4){f.reset();let m,T;for(m=0;m<4;m++)T=n[_+m],T>0&&(M.FromFloat32ArrayToRefScaled(c,Math.floor(r[_+m]*16),T,d),f.addToSelf(d));if(a)for(m=0;m<4;m++)T=h[_+m],T>0&&(M.FromFloat32ArrayToRefScaled(c,Math.floor(o[_+m]*16),T,d),f.addToSelf(d));s===A.NormalKind?E.TransformNormalFromFloatsToRef(i[p],i[p+1],i[p+2],f,u):E.TransformCoordinatesFromFloatsToRef(i[p],i[p+1],i[p+2],f,u),u.toArray(i,p),s===A.PositionKind&&this._positions&&this._positions[p/3].copyFrom(u)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,A.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,A.PositionKind)}_getPositionData(e,t){var i;let s=this.getVerticesData(A.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),s&&(e&&this.skeleton||t&&this.morphTargetManager)){if(s=s.slice(),this._generatePointsArray(),this._positions){const r=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(r.length);for(let n=0;n<r.length;n++)this._internalAbstractMeshDataInfo._positions[n]=((i=r[n])===null||i===void 0?void 0:i.clone())||new E}return this.getPositionData(e,t,s)}return s}_updateBoundingInfo(){return this._boundingInfo?this._boundingInfo.update(this.worldMatrixFromCache):this._boundingInfo=new $t(E.Zero(),E.Zero(),this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}_updateSubMeshesBoundingInfo(e){if(!this.subMeshes)return this;const t=this.subMeshes.length;for(let i=0;i<t;i++){const s=this.subMeshes[i];(t>1||!s.IsGlobal)&&s.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const s=this.getBoundingInfo(),r=e.getBoundingInfo();if(s.intersects(r,t))return!0;if(i){for(const n of this.getChildMeshes())if(n.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 r=e.verticesStart,n=e.verticesStart+e.verticesCount;for(let a=r;a<n;a++)e._lastColliderWorldVertices.push(E.TransformCoordinates(this._positions[a],t))}return i._collide(e._trianglePlanes,e._lastColliderWorldVertices,this.getIndices(),e.indexStart,e.indexStart+e.indexCount,e.verticesStart,!!e.getMaterial(),this,this._shouldConvertRHS(),((s=e.getMaterial())===null||s===void 0?void 0:s.fillMode)===7),this}_processCollisionsForSubMeshes(e,t){const i=this._scene.getCollidingSubMeshCandidates(this,e),s=i.length;for(let r=0;r<s;r++){const n=i.data[r];s>1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=D.Matrix[0],i=D.Matrix[1];return M.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,r,n=!1){const a=new br,o=this.getClassName(),h=o==="InstancedLinesMesh"||o==="LinesMesh"||o==="GreasedLineMesh"?this.intersectionThreshold:0,c=this.getBoundingInfo();if(!this.subMeshes||!n&&(!e.intersectsSphere(c.boundingSphere,h)||!e.intersectsBox(c.boundingBox,h)))return a;if(s)return a.hit=!n,a.pickedMesh=n?null:this,a.distance=n?0:E.Distance(e.origin,c.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;let u=null;const f=this._scene.getIntersectingSubMeshCandidates(this,e),d=f.length;let _=!1;for(let p=0;p<d;p++){const T=f.data[p].getMaterial();if(T&&(T.fillMode==7||T.fillMode==0||T.fillMode==1||T.fillMode==2||T.fillMode==4)){_=!0;break}}if(!_)return a.hit=!0,a.pickedMesh=this,a.distance=E.Distance(e.origin,c.boundingSphere.center),a.subMeshId=-1,a;for(let p=0;p<d;p++){const m=f.data[p];if(d>1&&!m.canIntersects(e))continue;const T=m.intersects(e,this._positions,this.getIndices(),t,i);if(T&&(t||!u||T.distance<u.distance)&&(u=T,u.subMeshId=p,t))break}if(u){const p=r??this.getWorldMatrix(),m=D.Vector3[0],T=D.Vector3[1];E.TransformCoordinatesToRef(e.origin,p,m),e.direction.scaleToRef(u.distance,T);const x=E.TransformNormal(T,p).addInPlace(m);return a.hit=!0,a.distance=E.Distance(m,x),a.pickedPoint=x,a.pickedMesh=this,a.bu=u.bu||0,a.bv=u.bv||0,a.subMeshFaceId=u.faceId,a.faceId=u.faceId+f.data[u.subMeshId].indexStart/(this.getClassName().indexOf("LinesMesh")!==-1?2:3),a.subMeshId=u.subMeshId,a}return a}clone(e,t,i){return null}releaseSubMeshes(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=new Array;return this}dispose(e,t=!1){let i;for(this._scene.useMaterialMeshMap&&this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this.getScene().freeActiveMeshes(),this.getScene().freeRenderingGroups(),this.actionManager!==void 0&&this.actionManager!==null&&(this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i<this._intersectionsInProgress.length;i++){const n=this._intersectionsInProgress[i],a=n._intersectionsInProgress.indexOf(this);n._intersectionsInProgress.splice(a,1)}this._intersectionsInProgress.length=0,this.getScene().lights.forEach(n=>{let a=n.includedOnlyMeshes.indexOf(this);a!==-1&&n.includedOnlyMeshes.splice(a,1),a=n.excludedMeshes.indexOf(this),a!==-1&&n.excludedMeshes.splice(a,1);const o=n.getShadowGenerators();if(o){const h=o.values();for(let c=h.next();c.done!==!0;c=h.next()){const f=c.value.getShadowMap();f&&f.renderList&&(a=f.renderList.indexOf(this),a!==-1&&f.renderList.splice(a,1))}}}),(this.getClassName()!=="InstancedMesh"||this.getClassName()!=="InstancedLinesMesh")&&this.releaseSubMeshes();const r=this.getScene().getEngine();if(this._occlusionQuery!==null&&(this.isOcclusionQueryInProgress=!1,r.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),r.wipeCaches(),this.getScene().removeMesh(this),this._parentContainer){const n=this._parentContainer.meshes.indexOf(this);n>-1&&this._parentContainer.meshes.splice(n,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;i<this.getScene().particleSystems.length;i++)this.getScene().particleSystems[i].emitter===this&&(this.getScene().particleSystems[i].dispose(),i--);this._internalAbstractMeshDataInfo._facetData.facetDataEnabled&&this.disableFacetData(),this._uniformBuffer.dispose(),this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this.onRebuildObservable.clear(),super.dispose(e,t)}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.setParent(null,t),this}_initFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;e.facetNormals||(e.facetNormals=new Array),e.facetPositions||(e.facetPositions=new Array),e.facetPartitioning||(e.facetPartitioning=new Array),e.facetNb=this.getIndices().length/3|0,e.partitioningSubdivisions=e.partitioningSubdivisions?e.partitioningSubdivisions:10,e.partitioningBBoxRatio=e.partitioningBBoxRatio?e.partitioningBBoxRatio:1.01;for(let t=0;t<e.facetNb;t++)e.facetNormals[t]=E.Zero(),e.facetPositions[t]=E.Zero();return e.facetDataEnabled=!0,this}updateFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();const t=this.getVerticesData(A.PositionKind),i=this.getIndices(),s=this.getVerticesData(A.NormalKind),r=this.getBoundingInfo();if(e.facetDepthSort&&!e.facetDepthSortEnabled){if(e.facetDepthSortEnabled=!0,i instanceof Uint16Array)e.depthSortedIndices=new Uint16Array(i);else if(i instanceof Uint32Array)e.depthSortedIndices=new Uint32Array(i);else{let a=!1;for(let o=0;o<i.length;o++)if(i[o]>65535){a=!0;break}a?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(a,o){return o.sqDistance-a.sqDistance},!e.facetDepthSortFrom){const a=this.getScene().activeCamera;e.facetDepthSortFrom=a?a.position:E.Zero()}e.depthSortedFacets=[];for(let a=0;a<e.facetNb;a++){const o={ind:a*3,sqDistance:0};e.depthSortedFacets.push(o)}e.invertedMatrix=M.Identity(),e.facetDepthSortOrigin=E.Zero()}e.bbSize.x=r.maximum.x-r.minimum.x>ke?r.maximum.x-r.minimum.x:ke,e.bbSize.y=r.maximum.y-r.minimum.y>ke?r.maximum.y-r.minimum.y:ke,e.bbSize.z=r.maximum.z-r.minimum.z>ke?r.maximum.z-r.minimum.z:ke;let n=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(n=n>e.bbSize.z?n:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/n),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/n),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/n),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),E.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&me.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const a=e.depthSortedIndices.length/3|0;for(let o=0;o<a;o++){const h=e.depthSortedFacets[o].ind;e.depthSortedIndices[o*3]=i[h],e.depthSortedIndices[o*3+1]=i[h+1],e.depthSortedIndices[o*3+2]=i[h+2]}this.updateIndices(e.depthSortedIndices,void 0,!0)}return this}getFacetLocalNormals(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetNormals||this.updateFacetData(),e.facetNormals}getFacetLocalPositions(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetPositions||this.updateFacetData(),e.facetPositions}getFacetLocalPartitioning(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetPartitioning||this.updateFacetData(),e.facetPartitioning}getFacetPosition(e){const t=E.Zero();return this.getFacetPositionToRef(e,t),t}getFacetPositionToRef(e,t){const i=this.getFacetLocalPositions()[e],s=this.getWorldMatrix();return E.TransformCoordinatesToRef(i,s,t),this}getFacetNormal(e){const t=E.Zero();return this.getFacetNormalToRef(e,t),t}getFacetNormalToRef(e,t){const i=this.getFacetLocalNormals()[e];return E.TransformNormalToRef(i,this.getWorldMatrix(),t),this}getFacetsAtLocalCoordinates(e,t,i){const s=this.getBoundingInfo(),r=this._internalAbstractMeshDataInfo._facetData,n=Math.floor((e-s.minimum.x*r.partitioningBBoxRatio)*r.subDiv.X*r.partitioningBBoxRatio/r.bbSize.x),a=Math.floor((t-s.minimum.y*r.partitioningBBoxRatio)*r.subDiv.Y*r.partitioningBBoxRatio/r.bbSize.y),o=Math.floor((i-s.minimum.z*r.partitioningBBoxRatio)*r.subDiv.Z*r.partitioningBBoxRatio/r.bbSize.z);return n<0||n>r.subDiv.max||a<0||a>r.subDiv.max||o<0||o>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*a+r.subDiv.max*r.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const a=this.getWorldMatrix(),o=D.Matrix[5];a.invertToRef(o);const h=D.Vector3[8];E.TransformCoordinatesFromFloatsToRef(e,t,i,o,h);const c=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,s,r,n);return s&&E.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,a,s),c}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let a=null,o=0,h=0,c=0,u=0,f=0,d=0,_=0,p=0;const m=this.getFacetLocalPositions(),T=this.getFacetLocalNormals(),S=this.getFacetsAtLocalCoordinates(e,t,i);if(!S)return null;let x=Number.MAX_VALUE,b=x,I,R,C;for(let y=0;y<S.length;y++)I=S[y],R=T[I],C=m[I],u=(e-C.x)*R.x+(t-C.y)*R.y+(i-C.z)*R.z,(!r||r&&n&&u>=0||r&&!n&&u<=0)&&(u=R.x*C.x+R.y*C.y+R.z*C.z,f=-(R.x*e+R.y*t+R.z*i-u)/(R.x*R.x+R.y*R.y+R.z*R.z),d=e+R.x*f,_=t+R.y*f,p=i+R.z*f,o=d-e,h=_-t,c=p-i,b=o*o+h*h+c*c,b<x&&(x=b,a=I,s&&(s.x=d,s.y=_,s.z=p)));return a}getFacetDataParameters(){return this._internalAbstractMeshDataInfo._facetData.facetParameters}disableFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetDataEnabled&&(e.facetDataEnabled=!1,e.facetPositions=new Array,e.facetNormals=new Array,e.facetPartitioning=new Array,e.facetParameters=null,e.depthSortedIndices=new Uint32Array(0)),this}updateIndices(e,t,i=!1){return this}createNormals(e){const t=this.getVerticesData(A.PositionKind),i=this.getIndices();let s;return this.isVerticesDataPresent(A.NormalKind)?s=this.getVerticesData(A.NormalKind):s=[],me.ComputeNormals(t,i,s,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(A.NormalKind,s,e),this}alignWithNormal(e,t){t||(t=As.Y);const i=D.Vector3[0],s=D.Vector3[1];return E.CrossToRef(t,e,s),E.CrossToRef(e,s,i),this.rotationQuaternion?K.RotationQuaternionFromAxisToRef(i,e,s,this.rotationQuaternion):E.RotationFromAxisToRef(i,e,s,this.rotation),this}_checkOcclusionQuery(){return!1}disableEdgesRendering(){throw fe("EdgesRenderer")}enableEdgesRendering(e,t,i){throw fe("EdgesRenderer")}getConnectedParticleSystems(){return this._scene.particleSystems.filter(e=>e.emitter===this)}}Vt.OCCLUSION_TYPE_NONE=0,Vt.OCCLUSION_TYPE_OPTIMISTIC=1,Vt.OCCLUSION_TYPE_STRICT=2,Vt.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,Vt.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,Vt.CULLINGSTRATEGY_STANDARD=0,Vt.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Vt.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Vt.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,Re("BABYLON.AbstractMesh",Vt);function zs(l){l.indexOf("vClipPlane")===-1&&l.push("vClipPlane"),l.indexOf("vClipPlane2")===-1&&l.push("vClipPlane2"),l.indexOf("vClipPlane3")===-1&&l.push("vClipPlane3"),l.indexOf("vClipPlane4")===-1&&l.push("vClipPlane4"),l.indexOf("vClipPlane5")===-1&&l.push("vClipPlane5"),l.indexOf("vClipPlane6")===-1&&l.push("vClipPlane6")}function nn(l,e,t){var i,s,r,n,a,o;const h=!!((i=l.clipPlane)!==null&&i!==void 0?i:e.clipPlane),c=!!((s=l.clipPlane2)!==null&&s!==void 0?s:e.clipPlane2),u=!!((r=l.clipPlane3)!==null&&r!==void 0?r:e.clipPlane3),f=!!((n=l.clipPlane4)!==null&&n!==void 0?n:e.clipPlane4),d=!!((a=l.clipPlane5)!==null&&a!==void 0?a:e.clipPlane5),_=!!((o=l.clipPlane6)!==null&&o!==void 0?o:e.clipPlane6);h&&t.push("#define CLIPPLANE"),c&&t.push("#define CLIPPLANE2"),u&&t.push("#define CLIPPLANE3"),f&&t.push("#define CLIPPLANE4"),d&&t.push("#define CLIPPLANE5"),_&&t.push("#define CLIPPLANE6")}function Jh(l,e,t){var i,s,r,n,a,o;let h=!1;const c=!!((i=l.clipPlane)!==null&&i!==void 0?i:e.clipPlane),u=!!((s=l.clipPlane2)!==null&&s!==void 0?s:e.clipPlane2),f=!!((r=l.clipPlane3)!==null&&r!==void 0?r:e.clipPlane3),d=!!((n=l.clipPlane4)!==null&&n!==void 0?n:e.clipPlane4),_=!!((a=l.clipPlane5)!==null&&a!==void 0?a:e.clipPlane5),p=!!((o=l.clipPlane6)!==null&&o!==void 0?o:e.clipPlane6);return t.CLIPPLANE!==c&&(t.CLIPPLANE=c,h=!0),t.CLIPPLANE2!==u&&(t.CLIPPLANE2=u,h=!0),t.CLIPPLANE3!==f&&(t.CLIPPLANE3=f,h=!0),t.CLIPPLANE4!==d&&(t.CLIPPLANE4=d,h=!0),t.CLIPPLANE5!==_&&(t.CLIPPLANE5=_,h=!0),t.CLIPPLANE6!==p&&(t.CLIPPLANE6=p,h=!0),h}function Xs(l,e,t){var i,s,r,n,a,o;let h=(i=e.clipPlane)!==null&&i!==void 0?i:t.clipPlane;Ys(l,"vClipPlane",h),h=(s=e.clipPlane2)!==null&&s!==void 0?s:t.clipPlane2,Ys(l,"vClipPlane2",h),h=(r=e.clipPlane3)!==null&&r!==void 0?r:t.clipPlane3,Ys(l,"vClipPlane3",h),h=(n=e.clipPlane4)!==null&&n!==void 0?n:t.clipPlane4,Ys(l,"vClipPlane4",h),h=(a=e.clipPlane5)!==null&&a!==void 0?a:t.clipPlane5,Ys(l,"vClipPlane5",h),h=(o=e.clipPlane6)!==null&&o!==void 0?o:t.clipPlane6,Ys(l,"vClipPlane6",h)}function Ys(l,e,t){t&&l.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d)}class X{static BindSceneUniformBuffer(e,t){t.bindToEffect(e,"Scene")}static PrepareDefinesForMergedUV(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}static BindTextureMatrix(e,t,i){const s=e.getTextureMatrix();t.updateMatrix(i+"Matrix",s)}static GetFogState(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==Ie.FOGMODE_NONE}static PrepareDefinesForMisc(e,t,i,s,r,n,a,o=!1){a._areMiscDirty&&(a.LOGARITHMICDEPTH=i,a.POINTSIZE=s,a.FOG=r&&this.GetFogState(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=n,a.DECAL_AFTER_DETAIL=o)}static PrepareDefinesForCamera(e,t){let i=!1;if(e.activeCamera){const s=t.CAMERA_ORTHOGRAPHIC?1:0,r=t.CAMERA_PERSPECTIVE?1:0,n=e.activeCamera.mode===ie.ORTHOGRAPHIC_CAMERA?1:0,a=e.activeCamera.mode===ie.PERSPECTIVE_CAMERA?1:0;(s^n||r^a)&&(t.CAMERA_ORTHOGRAPHIC=n===1,t.CAMERA_PERSPECTIVE=a===1,i=!0)}return i}static PrepareDefinesForFrameBoundValues(e,t,i,s,r,n=null,a=!1){let o=X.PrepareDefinesForCamera(e,s);n!==!1&&(o=Jh(i,e,s)),s.DEPTHPREPASS!==!t.getColorWrite()&&(s.DEPTHPREPASS=!s.DEPTHPREPASS,o=!0),s.INSTANCES!==r&&(s.INSTANCES=r,o=!0),s.THIN_INSTANCES!==a&&(s.THIN_INSTANCES=a,o=!0),o&&s.markAsUnprocessed()}static PrepareDefinesForBones(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=t.BONETEXTURE!==void 0;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=i?!1:void 0;const s=e.getScene().prePassRenderer;if(s&&s.enabled){const r=s.excludedSkinnedMesh.indexOf(e)===-1;t.BONES_VELOCITY_ENABLED=r}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.BONETEXTURE!==void 0&&(t.BONETEXTURE=!1)}static PrepareDefinesForMorphTargets(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.MORPHTARGETS=i.numInfluencers>0,t.NUM_MORPH_INFLUENCERS=i.numInfluencers,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}static PrepareDefinesForBakedVertexAnimation(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!!(i&&i.isEnabled)}static PrepareDefinesForAttributes(e,t,i,s,r=!1,n=!0,a=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent(A.NormalKind),t._needNormals&&e.isVerticesDataPresent(A.TangentKind)&&(t.TANGENT=!0);for(let o=1;o<=6;++o)t["UV"+o]=t._needUVs?e.isVerticesDataPresent(`uv${o===1?"":o}`):!1;if(i){const o=e.useVertexColors&&e.isVerticesDataPresent(A.ColorKind);t.VERTEXCOLOR=o,t.VERTEXALPHA=e.hasVertexAlpha&&o&&n}return e.isVerticesDataPresent(A.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),s&&this.PrepareDefinesForBones(e,t),r&&this.PrepareDefinesForMorphTargets(e,t),a&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(e,t){if(e.activeCamera){const i=t.MULTIVIEW;t.MULTIVIEW=e.activeCamera.outputRenderTarget!==null&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}static PrepareDefinesForOIT(e,t,i){const s=t.ORDER_INDEPENDENT_TRANSPARENCY,r=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,(s!==t.ORDER_INDEPENDENT_TRANSPARENCY||r!==t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){const s=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount;for(let n=0;n<r.length;n++){const a=e.prePassRenderer.getIndex(r[n].type);a!==-1?(t[r[n].define]=!0,t[r[n].index]=a):t[r[n].define]=!1}}else{t.PREPASS=!1;for(let n=0;n<r.length;n++)t[r[n].define]=!1}t.PREPASS!=s&&(t.markAsUnprocessed(),t.markAsImageProcessingDirty())}static PrepareDefinesForLight(e,t,i,s,r,n,a){var o;switch(a.needNormals=!0,r["LIGHT"+s]===void 0&&(a.needRebuild=!0),r["LIGHT"+s]=!0,r["SPOTLIGHT"+s]=!1,r["HEMILIGHT"+s]=!1,r["POINTLIGHT"+s]=!1,r["DIRLIGHT"+s]=!1,i.prepareLightSpecificDefines(r,s),r["LIGHT_FALLOFF_PHYSICAL"+s]=!1,r["LIGHT_FALLOFF_GLTF"+s]=!1,r["LIGHT_FALLOFF_STANDARD"+s]=!1,i.falloffType){case Be.FALLOFF_GLTF:r["LIGHT_FALLOFF_GLTF"+s]=!0;break;case Be.FALLOFF_PHYSICAL:r["LIGHT_FALLOFF_PHYSICAL"+s]=!0;break;case Be.FALLOFF_STANDARD:r["LIGHT_FALLOFF_STANDARD"+s]=!0;break}if(n&&!i.specular.equalsFloats(0,0,0)&&(a.specularEnabled=!0),r["SHADOW"+s]=!1,r["SHADOWCSM"+s]=!1,r["SHADOWCSMDEBUG"+s]=!1,r["SHADOWCSMNUM_CASCADES"+s]=!1,r["SHADOWCSMUSESHADOWMAXZ"+s]=!1,r["SHADOWCSMNOBLEND"+s]=!1,r["SHADOWCSM_RIGHTHANDED"+s]=!1,r["SHADOWPCF"+s]=!1,r["SHADOWPCSS"+s]=!1,r["SHADOWPOISSON"+s]=!1,r["SHADOWESM"+s]=!1,r["SHADOWCLOSEESM"+s]=!1,r["SHADOWCUBE"+s]=!1,r["SHADOWLOWQUALITY"+s]=!1,r["SHADOWMEDIUMQUALITY"+s]=!1,t&&t.receiveShadows&&e.shadowsEnabled&&i.shadowEnabled){const h=(o=i.getShadowGenerator(e.activeCamera))!==null&&o!==void 0?o:i.getShadowGenerator();if(h){const c=h.getShadowMap();c&&c.renderList&&c.renderList.length>0&&(a.shadowEnabled=!0,h.prepareDefines(r,s))}}i.lightmapMode!=Be.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+s]=!0,r["LIGHTMAPNOSPECULAR"+s]=i.lightmapMode==Be.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+s]=!1,r["LIGHTMAPNOSPECULAR"+s]=!1)}static PrepareDefinesForLights(e,t,i,s,r=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let a=0;const o={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n){for(const c of t.lightSources)if(this.PrepareDefinesForLight(e,t,c,a,i,s,o),a++,a===r)break}i.SPECULARTERM=o.specularEnabled,i.SHADOWS=o.shadowEnabled;for(let c=a;c<r;c++)i["LIGHT"+c]!==void 0&&(i["LIGHT"+c]=!1,i["HEMILIGHT"+c]=!1,i["POINTLIGHT"+c]=!1,i["DIRLIGHT"+c]=!1,i["SPOTLIGHT"+c]=!1,i["SHADOW"+c]=!1,i["SHADOWCSM"+c]=!1,i["SHADOWCSMDEBUG"+c]=!1,i["SHADOWCSMNUM_CASCADES"+c]=!1,i["SHADOWCSMUSESHADOWMAXZ"+c]=!1,i["SHADOWCSMNOBLEND"+c]=!1,i["SHADOWCSM_RIGHTHANDED"+c]=!1,i["SHADOWPCF"+c]=!1,i["SHADOWPCSS"+c]=!1,i["SHADOWPOISSON"+c]=!1,i["SHADOWESM"+c]=!1,i["SHADOWCLOSEESM"+c]=!1,i["SHADOWCUBE"+c]=!1,i["SHADOWLOWQUALITY"+c]=!1,i["SHADOWMEDIUMQUALITY"+c]=!1);const h=e.getEngine().getCaps();return i.SHADOWFLOAT===void 0&&(o.needRebuild=!0),i.SHADOWFLOAT=o.shadowEnabled&&(h.textureFloatRender&&h.textureFloatLinearFiltering||h.textureHalfFloatRender&&h.textureHalfFloatLinearFiltering),i.LIGHTMAPEXCLUDED=o.lightmapMode,o.needRebuild&&i.rebuild(),o.needNormals}static PrepareUniformsAndSamplersForLight(e,t,i,s,r=null,n=!1){r&&r.push("Light"+e),!n&&(t.push("vLightData"+e,"vLightDiffuse"+e,"vLightSpecular"+e,"vLightDirection"+e,"vLightFalloff"+e,"vLightGround"+e,"lightMatrix"+e,"shadowsInfo"+e,"depthValues"+e),i.push("shadowSampler"+e),i.push("depthSampler"+e),t.push("viewFrustumZ"+e,"cascadeBlendFactor"+e,"lightSizeUVCorrection"+e,"depthCorrection"+e,"penumbraDarkness"+e,"frustumLengths"+e),s&&(i.push("projectionLightSampler"+e),t.push("textureProjectionMatrix"+e)))}static PrepareUniformsAndSamplersList(e,t,i,s=4){let r,n=null;if(e.uniformsNames){const a=e;r=a.uniformsNames,n=a.uniformBuffersNames,t=a.samplers,i=a.defines,s=a.maxSimultaneousLights||0}else r=e,t||(t=[]);for(let a=0;a<s&&i["LIGHT"+a];a++)this.PrepareUniformsAndSamplersForLight(a,r,t,i["PROJECTEDLIGHTTEXTURE"+a],n);i.NUM_MORPH_INFLUENCERS&&r.push("morphTargetInfluences"),i.BAKED_VERTEX_ANIMATION_TEXTURE&&(r.push("bakedVertexAnimationSettings"),r.push("bakedVertexAnimationTextureSizeInverted"),r.push("bakedVertexAnimationTime"),t.push("bakedVertexAnimationTexture"))}static HandleFallbacksForShadows(e,t,i=4,s=0){let r=0;for(let n=0;n<i&&e["LIGHT"+n];n++)n>0&&(r=s+n,t.addFallback(r,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(s,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(s,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(s,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(s,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(s,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(s,"SHADOWCLOSEESM"+n));return r++}static PrepareAttributesForMorphTargetsInfluencers(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)}static PrepareAttributesForMorphTargets(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&Ee.LastCreatedEngine){const r=Ee.LastCreatedEngine.getCaps().maxVertexAttribs,n=t.morphTargetManager;if(n!=null&&n.isUsingTextureForTargets)return;const a=n&&n.supportsNormals&&i.NORMAL,o=n&&n.supportsTangents&&i.TANGENT,h=n&&n.supportsUVs&&i.UV1;for(let c=0;c<s;c++)e.push(A.PositionKind+c),a&&e.push(A.NormalKind+c),o&&e.push(A.TangentKind+c),h&&e.push(A.UVKind+"_"+c),e.length>r&&F.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,s){i.NUM_BONE_INFLUENCERS>0&&(s.addCPUSkinningFallback(0,t),e.push(A.MatricesIndicesKind),e.push(A.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(A.MatricesIndicesExtraKind),e.push(A.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(A.ColorInstanceKind)}static PushAttributesForInstances(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}static BindLightProperties(e,t,i){e.transferToEffect(t,i+"")}static BindLight(e,t,i,s,r,n=!0){e._bindLight(t,i,s,r,n)}static BindLights(e,t,i,s,r=4){const n=Math.min(t.lightSources.length,r);for(let a=0;a<n;a++){const o=t.lightSources[a];this.BindLight(o,a,e,i,typeof s=="boolean"?s:s.SPECULARTERM,t.receiveShadows)}}static BindFogParameters(e,t,i,s=!1){e.fogEnabled&&t.applyFog&&e.fogMode!==Ie.FOGMODE_NONE&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),s?(e.fogColor.toLinearSpaceToRef(this._TempFogColor,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",this._TempFogColor)):i.setColor3("vFogColor",e.fogColor))}static BindBonesParameters(e,t,i){if(!(!t||!e)&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const s=e.skeleton;if(s.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const r=s.getTransformMatrixTexture(e);t.setTexture("boneSampler",r),t.setFloat("boneTextureWidth",4*(s.bones.length+1))}else{const r=s.getTransformMatrices(e);r&&(t.setMatrices("mBones",r),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=r.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),X._CopyBonesTransformationMatrices(r,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){const i=e.morphTargetManager;!e||!i||t.setFloatArray("morphTargetInfluences",i.influences)}static BindLogDepth(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const s=i.activeCamera;s.mode===ie.ORTHOGRAPHIC_CAMERA&&F.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(s.maxZ+1)/Math.LN2))}}}X._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},X._TempFogColor=z.Black();class Bi{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){J.Clone(()=>e,this)}serialize(){return J.Serialize(this)}parse(e,t,i){J.Parse(()=>this,e,t,i)}}g([v()],Bi.prototype,"func",null),g([v()],Bi.prototype,"funcRef",null),g([v()],Bi.prototype,"funcMask",null),g([v()],Bi.prototype,"opStencilFail",null),g([v()],Bi.prototype,"opDepthFail",null),g([v()],Bi.prototype,"opStencilDepthPass",null),g([v()],Bi.prototype,"mask",null),g([v()],Bi.prototype,"enabled",null);var Rt;(function(l){l[l.Created=1]="Created",l[l.Disposed=2]="Disposed",l[l.GetDefineNames=4]="GetDefineNames",l[l.PrepareUniformBuffer=8]="PrepareUniformBuffer",l[l.IsReadyForSubMesh=16]="IsReadyForSubMesh",l[l.PrepareDefines=32]="PrepareDefines",l[l.BindForSubMesh=64]="BindForSubMesh",l[l.PrepareEffect=128]="PrepareEffect",l[l.GetAnimatables=256]="GetAnimatables",l[l.GetActiveTextures=512]="GetActiveTextures",l[l.HasTexture=1024]="HasTexture",l[l.FillRenderTargetTextures=2048]="FillRenderTargetTextures",l[l.HasRenderTargetTextures=4096]="HasRenderTargetTextures",l[l.HardBindForSubMesh=8192]="HardBindForSubMesh"})(Rt||(Rt={}));class V{get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;const t=this._alpha;this._alpha=e,(t===1||e===1)&&this.markAsDirty(V.MiscDirtyFlag+V.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(V.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(V.TextureDirtyFlag))}get cullBackFaces(){return this._cullBackFaces}get blockDirtyMechanism(){return this._blockDirtyMechanism}set blockDirtyMechanism(e){this._blockDirtyMechanism!==e&&(this._blockDirtyMechanism=e,e||this.markDirty())}atomicMaterialsUpdate(e){this.blockDirtyMechanism=!0;try{e(this)}finally{this.blockDirtyMechanism=!1}}get hasRenderTargetTextures(){return this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._eventInfo.hasRenderTargetTextures}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new B),this._onBindObservable}set onBind(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)}get onUnBindObservable(){return this._onUnBindObservable||(this._onUnBindObservable=new B),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new B),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(V.TextureDirtyFlag))}get alphaMode(){return this._alphaMode}set needDepthPrePass(e){this._needDepthPrePass!==e&&(this._needDepthPrePass=e,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))}get needDepthPrePass(){return this._needDepthPrePass}get isPrePassCapable(){return!1}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAsDirty(V.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case V.WireFrameFillMode:case V.LineListDrawMode:case V.LineLoopDrawMode:case V.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?V.WireFrameFillMode:V.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case V.PointFillMode:case V.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?V.PointFillMode:V.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(V.MiscDirtyFlag))}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new B,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=2,this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new Bi,this._useUBO=!1,this._fillMode=V.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedColorWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this._parentContainer=null,this._uniformBufferLayoutBuilt=!1,this._eventInfo={},this._callbackPluginEventGeneric=()=>{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const s=t||Ee.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||k.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Li(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=V.ClockWiseSideOrientation:this.sideOrientation=V.CounterClockWiseSideOrientation,this._uniformBuffer=new q(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),V.OnEventObservable.notifyObservers(this,Rt.Created))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const 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}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===V.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===V.MATERIAL_OPAQUE||this._transparencyMode===V.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)s.getMaterial()===this&&s.effect&&(s.effect._wasPreviouslyReady=!1,s.effect._wasPreviouslyUsingInstances=null,s.effect._forceRebindOnNextCall=e);e&&this.markAsDirty(V.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),r=(t??this.sideOrientation)===V.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,r,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),r}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(Rt.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i.effect;s&&(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){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,X.BindSceneUniformBuffer(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 i=this._scene.getEngine();this._cachedDepthWriteState=i.getDepthWrite(),i.setDepthWrite(!1)}if(this.disableColorWrite){const i=this._scene.getEngine();this._cachedColorWriteState=i.getColorWrite(),i.setColorWrite(!1)}if(this.depthFunction!==0){const i=this._scene.getEngine();this._cachedDepthFunctionState=i.getDepthFunction()||0,i.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(Rt.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(Rt.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(Rt.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),V._parsePlugins(i,e,this._scene,t),this.pluginManager)for(const s of this.pluginManager._plugins){const r=e.pluginManager.getPlugin(s.name);s.copyTo(r)}}getBindedMeshes(){if(this.meshMap){const e=new Array;for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}else return this._scene.meshes.filter(t=>t.material===this)}forceCompilation(e,t,i,s){const r=Object.assign({clipPlane:!1,useInstances:!1},i),n=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const o=()=>{if(!this._scene||!this._scene.getEngine())return;const h=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new Zt(0,0,0,1)),this._storeEffectOnSubMeshes){let c=!0,u=null;if(e.subMeshes){const f=new ci(0,0,0,0,0,e,void 0,!1,!1);f.materialDefines&&(f.materialDefines._renderId=-1),this.isReadyForSubMesh(e,f,r.useInstances)||(f.effect&&f.effect.getCompilationError()&&f.effect.allFallbacksProcessed()?u=f.effect.getCompilationError():(c=!1,setTimeout(o,16)))}c&&(this.allowShaderHotSwapping=a,u&&s&&s(u),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(o,16);r.clipPlane&&(n.clipPlane=h)};o()}forceCompilationAsync(e,t){return new Promise((i,s)=>{this.forceCompilation(e,()=>{i()},t,r=>{s(r)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(V._DirtyCallbackArray.length=0,e&V.TextureDirtyFlag&&V._DirtyCallbackArray.push(V._TextureDirtyCallBack),e&V.LightDirtyFlag&&V._DirtyCallbackArray.push(V._LightsDirtyCallBack),e&V.FresnelDirtyFlag&&V._DirtyCallbackArray.push(V._FresnelDirtyCallBack),e&V.AttributesDirtyFlag&&V._DirtyCallbackArray.push(V._AttributeDirtyCallBack),e&V.MiscDirtyFlag&&V._DirtyCallbackArray.push(V._MiscDirtyCallBack),e&V.PrePassDirtyFlag&&V._DirtyCallbackArray.push(V._PrePassDirtyCallBack),V._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(V._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 r of s._drawWrappers)!r||!r.defines||!r.defines.markAllAsDirty||this._materialContext===r.materialContext&&e(r.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(V._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(V._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(V._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(V._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(V._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(V._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(V._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(V._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(V._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(V._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==bi.BackwardCompatible){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){const s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(Rt.Disposed,this._eventInfo),this._parentContainer){const r=this._parentContainer.materials.indexOf(this);r>-1&&this._parentContainer.materials.splice(r,1),this._parentContainer=null}if(i!==!0)if(this.meshMap)for(const r in this.meshMap){const n=this.meshMap[r];n&&(n.material=null,this.releaseVertexArrayObject(n,e))}else{const r=s.meshes;for(const n of r)n.material===this&&!n.sourceMesh&&(n.material=null,this.releaseVertexArrayObject(n,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){if(e.geometry){const i=e.geometry;if(this._storeEffectOnSubMeshes)for(const s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose();else i._releaseVertexArrayObject(this._drawWrapper.effect)}}serialize(){const e=J.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 F.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;const r=k.Instantiate(e.customType).Parse(e,t,i);return r._loadedUniqueId=e.uniqueId,r}static _parsePlugins(e,t,i,s){var r;if(e.plugins)for(const n in e.plugins){const a=e.plugins[n];let o=(r=t.pluginManager)===null||r===void 0?void 0:r.getPlugin(a.name);if(!o){const h=k.Instantiate("BABYLON."+n);h&&(o=new h(t))}o==null||o.parse(a,i,s)}}}V.TriangleFillMode=0,V.WireFrameFillMode=1,V.PointFillMode=2,V.PointListDrawMode=3,V.LineListDrawMode=4,V.LineLoopDrawMode=5,V.LineStripDrawMode=6,V.TriangleStripDrawMode=7,V.TriangleFanDrawMode=8,V.ClockWiseSideOrientation=0,V.CounterClockWiseSideOrientation=1,V.TextureDirtyFlag=1,V.LightDirtyFlag=2,V.FresnelDirtyFlag=4,V.AttributesDirtyFlag=8,V.MiscDirtyFlag=16,V.PrePassDirtyFlag=32,V.AllDirtyFlag=63,V.MATERIAL_OPAQUE=0,V.MATERIAL_ALPHATEST=1,V.MATERIAL_ALPHABLEND=2,V.MATERIAL_ALPHATESTANDBLEND=3,V.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,V.MATERIAL_NORMALBLENDMETHOD_RNM=1,V.OnEventObservable=new B,V._AllDirtyCallBack=l=>l.markAllAsDirty(),V._ImageProcessingDirtyCallBack=l=>l.markAsImageProcessingDirty(),V._TextureDirtyCallBack=l=>l.markAsTexturesDirty(),V._FresnelDirtyCallBack=l=>l.markAsFresnelDirty(),V._MiscDirtyCallBack=l=>l.markAsMiscDirty(),V._PrePassDirtyCallBack=l=>l.markAsPrePassDirty(),V._LightsDirtyCallBack=l=>l.markAsLightDirty(),V._AttributeDirtyCallBack=l=>l.markAsAttributesDirty(),V._FresnelAndMiscDirtyCallBack=l=>{V._FresnelDirtyCallBack(l),V._MiscDirtyCallBack(l)},V._TextureAndMiscDirtyCallBack=l=>{V._TextureDirtyCallBack(l),V._MiscDirtyCallBack(l)},V._DirtyCallbackArray=[],V._RunDirtyCallBacks=l=>{for(const e of V._DirtyCallbackArray)e(l)},g([v()],V.prototype,"id",void 0),g([v()],V.prototype,"uniqueId",void 0),g([v()],V.prototype,"name",void 0),g([v()],V.prototype,"metadata",void 0),g([v()],V.prototype,"checkReadyOnEveryCall",void 0),g([v()],V.prototype,"checkReadyOnlyOnce",void 0),g([v()],V.prototype,"state",void 0),g([v("alpha")],V.prototype,"_alpha",void 0),g([v("backFaceCulling")],V.prototype,"_backFaceCulling",void 0),g([v("cullBackFaces")],V.prototype,"_cullBackFaces",void 0),g([v()],V.prototype,"sideOrientation",void 0),g([v("alphaMode")],V.prototype,"_alphaMode",void 0),g([v()],V.prototype,"_needDepthPrePass",void 0),g([v()],V.prototype,"disableDepthWrite",void 0),g([v()],V.prototype,"disableColorWrite",void 0),g([v()],V.prototype,"forceDepthWrite",void 0),g([v()],V.prototype,"depthFunction",void 0),g([v()],V.prototype,"separateCullingPass",void 0),g([v("fogEnabled")],V.prototype,"_fogEnabled",void 0),g([v()],V.prototype,"pointSize",void 0),g([v()],V.prototype,"zOffset",void 0),g([v()],V.prototype,"zOffsetUnits",void 0),g([v()],V.prototype,"pointsCloud",null),g([v()],V.prototype,"fillMode",null),g([v()],V.prototype,"transparencyMode",null);class Ss extends V{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=new Array,this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...s)=>{const r=t.apply(e,s);return this._markAllSubMeshesAsTexturesDirty(),r};const i=e.splice;e.splice=(s,r)=>{const n=i.apply(e,[s,r]);return this._markAllSubMeshesAsTexturesDirty(),n}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map(e=>e?e.getActiveTextures():[]))}hasTexture(e){var t;if(super.hasTexture(e))return!0;for(let i=0;i<this.subMaterials.length;i++)if(!((t=this.subMaterials[i])===null||t===void 0)&&t.hasTexture(e))return!0;return!1}getClassName(){return"MultiMaterial"}isReadyForSubMesh(e,t,i){for(let s=0;s<this.subMaterials.length;s++){const r=this.subMaterials[s];if(r){if(r._storeEffectOnSubMeshes){if(!r.isReadyForSubMesh(e,t,i))return!1;continue}if(!r.isReady(e))return!1}}return!0}clone(e,t){const i=new Ss(e,this.getScene());for(let s=0;s<this.subMaterials.length;s++){let r=null;const n=this.subMaterials[s];t&&n?r=n.clone(e+"-"+n.name):r=this.subMaterials[s],i.subMaterials.push(r)}return i}serialize(){const e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,xe&&(e.tags=xe.GetTags(this)),e.materialsUniqueIds=[],e.materials=[];for(let t=0;t<this.subMaterials.length;t++){const i=this.subMaterials[t];i?(e.materialsUniqueIds.push(i.uniqueId),e.materials.push(i.id)):(e.materialsUniqueIds.push(null),e.materials.push(null))}return e}dispose(e,t,i){const s=this.getScene();if(!s)return;if(i)for(let n=0;n<this.subMaterials.length;n++){const a=this.subMaterials[n];a&&a.dispose(e,t)}const r=s.multiMaterials.indexOf(this);r>=0&&s.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new Ss(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,xe&&xe.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(s=>i.subMaterials.push(t.getLastMaterialById(s))),i}}Re("BABYLON.MultiMaterial",Ss);class ec{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class tc{constructor(){this.visibleInstances={},this.batchCache=new Io,this.batchCacheReplacementModeInFrozenMode=new Io,this.instancesBufferSize=32*16*4}}class Io{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=new Array,this.hardwareInstancedRendering=new Array}}class ic{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=32*16,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class sc{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 ne extends Vt{static _GetDefaultSideOrientation(e){return e||ne.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(A.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(A.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 B),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new B),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new B),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new B),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new B),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){var e;return((e=this._thinInstanceDataStorage.instancesCount)!==null&&e!==void 0?e:0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=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,r,n=!0){if(super(e,t),this._internalMeshDataInfo=new sc,this.delayLoadState=0,this.instances=new Array,this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new tc,this._thinInstanceDataStorage=new ic,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=ne.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(a,o,h)=>{a&&h&&(this._uniformBuffer?this.transferToEffect(o):h.bindOnlyWorldMatrix(o))},s){if(s._geometry&&s._geometry.applyToMesh(this),pr.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 a=s._ranges;for(const o in a)Object.prototype.hasOwnProperty.call(a,o)&&a[o]&&this.createAnimationRange(o,a[o].from,a[o].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,xe&&xe.HasTags(s)&&xe.AddTagsTo(this,xe.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix()),this.id=e+"."+s.id,this.material=s.material,!r){const a=s.getDescendants(!0);for(let o=0;o<a.length;o++){const h=a[o];h.clone&&h.clone(e+"."+h.name,this)}}if(s.morphTargetManager&&(this.morphTargetManager=s.morphTargetManager),t.getPhysicsEngine){const a=t.getPhysicsEngine();if(n&&a)if(a.getPluginVersion()===1){const o=a.getImpostorForPhysicsObject(s);o&&(this.physicsImpostor=o.clone(this))}else a.getPluginVersion()===2&&s.physicsBody&&s.physicsBody.clone(this)}for(let a=0;a<t.particleSystems.length;a++){const o=t.particleSystems[a];o.emitter===s&&o.clone(o.name,this)}this.skeleton=s.skeleton,this.refreshBoundingInfo(!0,!0),this.computeWorldMatrix(!0)}i!==null&&(this.parent=i),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=a=>{a.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 B(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 r of this.getChildTransformNodes(!0))r.getClassName()==="InstancedMesh"&&s.getClassName()==="Mesh"&&r.sourceMesh===this?r.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):r.instantiateHierarchy(s,t,i);return s}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);if(e)if(this._geometry){const i=this.getIndices(),s=this.getVerticesData(A.PositionKind);s&&i&&(t+=", flat shading: "+(s.length/3===i.length?"YES":"NO"))}else t+=", flat shading: UNKNOWN";return t}_unBindEffect(){super._unBindEffect();for(const e of this.instances)e._unBindEffect()}get hasLODLevels(){return this._internalMeshDataInfo._LODLevels.length>0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,i)=>t.distanceOrScreenCoverage<i.distanceOrScreenCoverage?e:t.distanceOrScreenCoverage>i.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return F.Warn("You cannot use a mesh as LOD level twice"),this;const i=new ec(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let i=0;i<t._LODLevels.length;i++){const s=t._LODLevels[i];if(s.distanceOrScreenCoverage===e)return s.mesh}return null}removeLODLevel(e){const t=this._internalMeshDataInfo;for(let i=0;i<t._LODLevels.length;i++)t._LODLevels[i].mesh===e&&(t._LODLevels.splice(i,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this}getLOD(e,t){const i=this._internalMeshDataInfo;if(!i._LODLevels||i._LODLevels.length===0)return this;const s=t||this.getBoundingInfo().boundingSphere,r=e.mode===ie.ORTHOGRAPHIC_CAMERA?e.minZ:s.centerWorld.subtract(e.globalPosition).length();let n=r,a=1;if(i._useLODScreenCoverage){const o=e.screenArea;let h=s.radiusWorld*e.minZ/r;h=h*h*Math.PI,n=h/o,a=-1}if(a*i._LODLevels[i._LODLevels.length-1].distanceOrScreenCoverage>a*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let o=0;o<i._LODLevels.length;o++){const h=i._LODLevels[o];if(a*h.distanceOrScreenCoverage<a*n){if(h.mesh){if(h.mesh.delayLoadState===4)return h.mesh._checkDelayState(),this;if(h.mesh.delayLoadState===2)return this;h.mesh._preActivate(),h.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)}return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,h.mesh),h.mesh}}return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this}get geometry(){return this._geometry}getTotalVertices(){return this._geometry===null||this._geometry===void 0?0:this._geometry.getTotalVertices()}getVerticesData(e,t,i,s){var r,n;if(!this._geometry)return null;let a=s||(n=(r=this._userInstancedBuffersStorage)===null||r===void 0?void 0:r.vertexBuffers[e])===null||n===void 0?void 0:n.getFloatData(this.instances.length+1,i||t&&this._geometry.meshes.length!==1);return a||(a=this._geometry.getVerticesData(e,t,i)),a}getVertexBuffer(e,t){var i,s;return this._geometry?(s=t||(i=this._userInstancedBuffersStorage)===null||i===void 0?void 0:i.vertexBuffers[e])!==null&&s!==void 0?s:this._geometry.getVertexBuffer(e):null}isVerticesDataPresent(e,t){var i;return this._geometry?!t&&((i=this._userInstancedBuffersStorage)===null||i===void 0?void 0:i.vertexBuffers[e])!==void 0||this._geometry.isVerticesDataPresent(e):this._delayInfo?this._delayInfo.indexOf(e)!==-1:!1}isVertexBufferUpdatable(e,t){var i;if(!this._geometry)return this._delayInfo?this._delayInfo.indexOf(e)!==-1:!1;if(!t){const s=(i=this._userInstancedBuffersStorage)===null||i===void 0?void 0:i.vertexBuffers[e];if(s)return s.isUpdatable()}return this._geometry.isVertexBufferUpdatable(e)}getVerticesDataKinds(e){if(!this._geometry){const i=new Array;return this._delayInfo&&this._delayInfo.forEach(function(s){i.push(s)}),i}const t=this._geometry.getVerticesDataKinds();if(!e&&this._userInstancedBuffersStorage)for(const i in this._userInstancedBuffersStorage.vertexBuffers)t.indexOf(i)===-1&&t.push(i);return t}getTotalIndices(){return this._geometry?this._geometry.getTotalIndices():0}getIndices(e,t){return this._geometry?this._geometry.getIndices(e,t):[]}get isBlocked(){return this._masterMesh!==null&&this._masterMesh!==void 0}isReady(e=!1,t=!1){var i,s,r,n,a,o,h;if(this.delayLoadState===2||!super.isReady(e))return!1;if(!this.subMeshes||this.subMeshes.length===0||!e)return!0;const c=this.getEngine(),u=this.getScene(),f=t||c.getCaps().instancedArrays&&(this.instances.length>0||this.hasThinInstances);this.computeWorldMatrix();const d=this.material||u.defaultMaterial;if(d){if(d._storeEffectOnSubMeshes)for(const p of this.subMeshes){const m=p.getMaterial();if(m){if(m._storeEffectOnSubMeshes){if(!m.isReadyForSubMesh(this,p,f))return!1}else if(!m.isReady(this,f))return!1}}else if(!d.isReady(this,f))return!1}const _=c.currentRenderPassId;for(const p of this.lightSources){const m=p.getShadowGenerators();if(!m)continue;const T=m.values();for(let S=T.next();S.done!==!0;S=T.next()){const x=S.value;if(x&&(!(!((i=x.getShadowMap())===null||i===void 0)&&i.renderList)||!((s=x.getShadowMap())===null||s===void 0)&&s.renderList&&((n=(r=x.getShadowMap())===null||r===void 0?void 0:r.renderList)===null||n===void 0?void 0:n.indexOf(this))!==-1)){const I=(a=x.getShadowMap().renderPassIds)!==null&&a!==void 0?a:[c.currentRenderPassId];for(let R=0;R<I.length;++R){c.currentRenderPassId=I[R];for(const C of this.subMeshes)if(!x.isReady(C,f,(h=(o=C.getMaterial())===null||o===void 0?void 0:o.needAlphaBlendingForMesh(this))!==null&&h!==void 0?h:!1))return c.currentRenderPassId=_,!1}c.currentRenderPassId=_}}}for(const p of this._internalMeshDataInfo._LODLevels)if(p.mesh&&!p.mesh.isReady(f))return!1;return!0}get areNormalsFrozen(){return this._internalMeshDataInfo._areNormalsFrozen}freezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!0,this}unfreezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!1,this}set overridenInstanceCount(e){this._instanceDataStorage.overridenInstanceCount=e}_preActivate(){const e=this._internalMeshDataInfo,t=this.getScene().getRenderId();return e._preActivateId===t?this:(e._preActivateId=t,this._instanceDataStorage.visibleInstances=null,this)}_preActivateForIntermediateRendering(e){return this._instanceDataStorage.visibleInstances&&(this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId=e),this}_registerInstanceForRenderId(e,t){return this._instanceDataStorage.visibleInstances||(this._instanceDataStorage.visibleInstances={defaultRenderId:t,selfDefaultRenderId:this._renderId}),this._instanceDataStorage.visibleInstances[t]||(this._instanceDataStorage.previousRenderId!==void 0&&this._instanceDataStorage.isFrozen&&(this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId]=null),this._instanceDataStorage.previousRenderId=t,this._instanceDataStorage.visibleInstances[t]=new Array),this._instanceDataStorage.visibleInstances[t].push(e),this}_afterComputeWorldMatrix(){super._afterComputeWorldMatrix(),this.hasThinInstances&&(this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1))}_postActivate(){this.edgesShareWithInstances&&this.edgesRenderer&&this.edgesRenderer.isEnabled&&this._renderingGroup&&(this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer),this.edgesRenderer.customInstances.push(this.getWorldMatrix()))}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;const i=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getPositionData(e,t),i),this}_createGlobalSubMesh(e){const t=this.getTotalVertices();if(!t||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){const i=this.getIndices();if(!i)return null;const s=i.length;let r=!1;if(e)r=!0;else for(const n of this.subMeshes){if(n.indexStart+n.indexCount>s){r=!0;break}if(n.verticesStart+n.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new ci(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 r=0;r<e&&!(s>=t);r++)ci.CreateFromIndices(0,s,r===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 r=new me;r.set(t,e);const n=this.getScene();new Bt(Bt.RandomId(),n,r,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=Bt.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(A.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(A.PositionKind,i,!1,!1),t){const s=this.getIndices(),r=this.getVerticesData(A.NormalKind);if(!r)return this;me.ComputeNormals(i,s,r),this.updateVerticesData(A.NormalKind,r,!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(Bt.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const s=new me;s.indices=e;const r=this.getScene();new Bt(Bt.RandomId(),r,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 r=this.getScene().getEngine();this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t);let n;if(this._unIndexed)n=null;else switch(this._getRenderingFillMode(i)){case V.PointFillMode:n=null;break;case V.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case V.TriangleFillMode:n=this._geometry.getIndexBuffer();break}return!s||!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,n):this._geometry._bind(t,n,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const r=this.getScene().getEngine();return this._unIndexed||t==V.PointFillMode?r.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==V.WireFrameFillMode?r.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):r.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(),r=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const a=this._instanceDataStorage.visibleInstances,o=i.getRenderId(),h=s?a.intermediateDefaultRenderId:a.defaultRenderId;n.visibleInstances[e]=a[o],!n.visibleInstances[e]&&h&&(n.visibleInstances[e]=a[h])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&n.visibleInstances[e]!==null&&n.visibleInstances[e]!==void 0,this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,s,r){var n;const a=i.visibleInstances[e._id],o=a?a.length:0,h=this._instanceDataStorage,c=h.instancesBufferSize;let u=h.instancesBuffer,f=h.instancesPreviousBuffer;const _=(o+1)*16*4;for(;h.instancesBufferSize<_;)h.instancesBufferSize*=2;(!h.instancesData||c!=h.instancesBufferSize)&&(h.instancesData=new Float32Array(h.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!h.instancesPreviousData||c!=h.instancesBufferSize)&&(h.instancesPreviousData=new Float32Array(h.instancesBufferSize/4));let p=0,m=0;const T=i.renderSelf[e._id],S=!u||c!==h.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!h.instancesPreviousBuffer;if(!this._instanceDataStorage.manualUpdate&&(!h.isFrozen||S)){const x=this.getWorldMatrix();if(T&&(this._scene.needsPreviousWorldMatrices&&(h.masterMeshPreviousWorldMatrix?(h.masterMeshPreviousWorldMatrix.copyToArray(h.instancesPreviousData,p),h.masterMeshPreviousWorldMatrix.copyFrom(x)):(h.masterMeshPreviousWorldMatrix=x.clone(),h.masterMeshPreviousWorldMatrix.copyToArray(h.instancesPreviousData,p))),x.copyToArray(h.instancesData,p),p+=16,m++),a){if(ne.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&(!((n=e.getMaterial())===null||n===void 0)&&n.needAlphaBlendingForMesh(e.getRenderingMesh()))){const b=this._scene.activeCamera.globalPosition;for(let I=0;I<a.length;I++){const R=a[I];R._distanceToCamera=E.Distance(R.getBoundingInfo().boundingSphere.centerWorld,b)}a.sort((I,R)=>I._distanceToCamera>R._distanceToCamera?-1:I._distanceToCamera<R._distanceToCamera?1:0)}for(let b=0;b<a.length;b++){const I=a[b],R=I.getWorldMatrix();R.copyToArray(h.instancesData,p),this._scene.needsPreviousWorldMatrices&&(I._previousWorldMatrix?(I._previousWorldMatrix.copyToArray(h.instancesPreviousData,p),I._previousWorldMatrix.copyFrom(R)):(I._previousWorldMatrix=R.clone(),I._previousWorldMatrix.copyToArray(h.instancesPreviousData,p))),p+=16,m++}}}else m=(T?1:0)+o;return S?(u&&u.dispose(),f&&f.dispose(),u=new Gs(r,h.instancesData,!0,16,!1,!0),h.instancesBuffer=u,this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this._userInstancedBuffersStorage.vertexBuffers.world0=u.createVertexBuffer("world0",0,4),this._userInstancedBuffersStorage.vertexBuffers.world1=u.createVertexBuffer("world1",4,4),this._userInstancedBuffersStorage.vertexBuffers.world2=u.createVertexBuffer("world2",8,4),this._userInstancedBuffersStorage.vertexBuffers.world3=u.createVertexBuffer("world3",12,4),this._scene.needsPreviousWorldMatrices&&(f=new Gs(r,h.instancesPreviousData,!0,16,!1,!0),h.instancesPreviousBuffer=f,this._userInstancedBuffersStorage.vertexBuffers.previousWorld0=f.createVertexBuffer("previousWorld0",0,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld1=f.createVertexBuffer("previousWorld1",4,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld2=f.createVertexBuffer("previousWorld2",8,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld3=f.createVertexBuffer("previousWorld3",12,4)),this._invalidateInstanceVertexArrayObject()):(!this._instanceDataStorage.isFrozen||this._instanceDataStorage.forceMatrixUpdates)&&(u.updateDirectly(h.instancesData,0,m),this._scene.needsPreviousWorldMatrices&&(!this._instanceDataStorage.manualUpdate||this._instanceDataStorage.previousManualUpdate)&&f.updateDirectly(h.instancesPreviousData,0,m)),this._processInstancedBuffers(a,T),this.getScene()._activeIndices.addCount(e.indexCount*m,!1),r._currentDrawContext&&(r._currentDrawContext.useInstancing=!0),this._bind(e,s,t),this._draw(e,t,m),this._scene.needsPreviousWorldMatrices&&!S&&this._instanceDataStorage.manualUpdate&&(!this._instanceDataStorage.isFrozen||this._instanceDataStorage.forceMatrixUpdates)&&!this._instanceDataStorage.previousManualUpdate&&f.updateDirectly(h.instancesData,0,m),r.unbindInstanceAttributes(),this}_renderWithThinInstances(e,t,i,s){var r,n;const a=(n=(r=this._thinInstanceDataStorage)===null||r===void 0?void 0:r.instancesCount)!==null&&n!==void 0?n:0;this.getScene()._activeIndices.addCount(e.indexCount*a,!1),s._currentDrawContext&&(s._currentDrawContext.useInstancing=!0),this._bind(e,i,t),this._draw(e,t,a),this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&this._thinInstanceDataStorage.matrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,a):this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.matrixData,!1)),s.unbindInstanceAttributes()}_processInstancedBuffers(e,t){}_processRendering(e,t,i,s,r,n,a,o){const h=this.getScene(),c=h.getEngine();if(s=this._getRenderingFillMode(s),n&&t.getRenderingMesh().hasThinInstances)return this._renderWithThinInstances(t,s,i,c),this;if(n)this._renderWithInstances(t,s,r,i,c);else{c._currentDrawContext&&(c._currentDrawContext.useInstancing=!1);let u=0;r.renderSelf[t._id]&&(a&&a(!1,e.getWorldMatrix(),o),u++,this._draw(t,s,this._instanceDataStorage.overridenInstanceCount));const f=r.visibleInstances[t._id];if(f){const d=f.length;u+=d;for(let _=0;_<d;_++){const m=f[_].getWorldMatrix();a&&a(!0,m,o),this._draw(t,s)}}h._activeIndices.addCount(t.indexCount*u,!1)}return this}_rebuild(e=!1){if(this._instanceDataStorage.instancesBuffer&&(e&&this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null),this._userInstancedBuffersStorage){for(const t in this._userInstancedBuffersStorage.vertexBuffers){const i=this._userInstancedBuffersStorage.vertexBuffers[t];i&&(e&&i.dispose(),this._userInstancedBuffersStorage.vertexBuffers[t]=null)}this._userInstancedBuffersStorage.vertexArrayObjects&&(this._userInstancedBuffersStorage.vertexArrayObjects={})}this._internalMeshDataInfo._effectiveMaterial=null,super._rebuild(e)}_freeze(){if(this.subMeshes){for(let e=0;e<this.subMeshes.length;e++)this._getInstancesRenderList(e);this._internalMeshDataInfo._effectiveMaterial=null,this._instanceDataStorage.isFrozen=!0}}_unFreeze(){this._instanceDataStorage.isFrozen=!1,this._instanceDataStorage.previousBatch=null}render(e,t,i){var s,r,n;const a=this.getScene();if(this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!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 h=a.getEngine();let c=0,u=null;this.ignoreCameraMaxZ&&a.activeCamera&&!a._isInIntermediateRendering()&&(c=a.activeCamera.maxZ,u=a.activeCamera,a.activeCamera.maxZ=0,a.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const f=e.getRenderingMesh(),d=o.hardwareInstancedRendering[e._id]||f.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,_=this._instanceDataStorage,p=e.getMaterial();if(!p)return u&&(u.maxZ=c,a.updateTransformMatrix(!0)),this;if(!_.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==p){if(p._storeEffectOnSubMeshes){if(!p.isReadyForSubMesh(this,e,d))return u&&(u.maxZ=c,a.updateTransformMatrix(!0)),this}else if(!p.isReady(this,d))return u&&(u.maxZ=c,a.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=p}else if(p._storeEffectOnSubMeshes&&!(!((s=e.effect)===null||s===void 0)&&s._wasPreviouslyReady)||!p._storeEffectOnSubMeshes&&!(!((r=p.getEffect())===null||r===void 0)&&r._wasPreviouslyReady))return u&&(u.maxZ=c,a.updateTransformMatrix(!0)),this;t&&h.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);let m;this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?m=e._drawWrapper:m=this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const T=(n=m==null?void 0:m.effect)!==null&&n!==void 0?n:null;for(const y of a._beforeRenderingMeshStage)y.action(this,e,o,T);if(!m||!T)return u&&(u.maxZ=c,a.updateTransformMatrix(!0)),this;const S=i||this;let x;if(!_.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||this.overrideMaterialSideOrientation!==null)){const y=S._getWorldMatrixDeterminant();x=this.overrideMaterialSideOrientation,x==null&&(x=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),y<0&&(x=x===V.ClockWiseSideOrientation?V.CounterClockWiseSideOrientation:V.ClockWiseSideOrientation),_.sideOrientation=x}else x=_.sideOrientation;const b=this._internalMeshDataInfo._effectiveMaterial._preBind(m,x);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&h.setDepthWrite(!0);const I=this._internalMeshDataInfo._effectiveMaterial,R=I.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),d||this._bind(e,T,R,!1);const C=S.getWorldMatrix();I._storeEffectOnSubMeshes?I.bindForSubMesh(C,this,e):I.bind(C,this),!I.backFaceCulling&&I.separateCullingPass&&(h.setState(!0,I.zOffset,!1,!b,I.cullBackFaces,I.stencil,I.zOffsetUnits),this._processRendering(this,e,T,R,o,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),h.setState(!0,I.zOffset,!1,b,I.cullBackFaces,I.stencil,I.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,T,R,o,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const y of a._afterRenderingMeshStage)y.action(this,e,o,T);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),u&&(u.maxZ=c,a.updateTransformMatrix(!0)),a.performancePriority===bi.Aggressive&&!_.isFrozen&&this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(A.MatricesWeightsKind)&&(this.isVerticesDataPresent(A.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(A.MatricesWeightsKind),t=e.length;for(let i=0;i<t;i+=4){const s=e[i]+e[i+1]+e[i+2]+e[i+3];if(s===0)e[i]=1;else{const r=1/s;e[i]*=r,e[i+1]*=r,e[i+2]*=r,e[i+3]*=r}}this.setVerticesData(A.MatricesWeightsKind,e)}_normalizeSkinWeightsAndExtra(){const e=this.getVerticesData(A.MatricesWeightsExtraKind),t=this.getVerticesData(A.MatricesWeightsKind),i=t.length;for(let s=0;s<i;s+=4){let r=t[s]+t[s+1]+t[s+2]+t[s+3];if(r+=e[s]+e[s+1]+e[s+2]+e[s+3],r===0)t[s]=1;else{const n=1/r;t[s]*=n,t[s+1]*=n,t[s+2]*=n,t[s+3]*=n,e[s]*=n,e[s+1]*=n,e[s+2]*=n,e[s+3]*=n}}this.setVerticesData(A.MatricesWeightsKind,t),this.setVerticesData(A.MatricesWeightsKind,e)}validateSkinning(){const e=this.getVerticesData(A.MatricesWeightsExtraKind),t=this.getVerticesData(A.MatricesWeightsKind);if(t===null||this.skeleton==null)return{skinned:!1,valid:!0,report:"not skinned"};const i=t.length;let s=0,r=0,n=0,a=0;const o=e===null?4:8,h=new Array;for(let m=0;m<=o;m++)h[m]=0;const c=.001;for(let m=0;m<i;m+=4){let T=t[m],S=T,x=S===0?0:1;for(let b=1;b<o;b++){const I=b<4?t[m+b]:e[m+b-4];I>T&&s++,I!==0&&x++,S+=I,T=I}if(h[x]++,x>n&&(n=x),S===0)r++;else{const b=1/S;let I=0;for(let R=0;R<o;R++)R<4?I+=Math.abs(t[m+R]-t[m+R]*b):I+=Math.abs(e[m+R-4]-e[m+R-4]*b);I>c&&a++}}const u=this.skeleton.bones.length,f=this.getVerticesData(A.MatricesIndicesKind),d=this.getVerticesData(A.MatricesIndicesExtraKind);let _=0;for(let m=0;m<i;m+=4)for(let T=0;T<o;T++){const S=T<4?f[m+T]:d[m+T-4];(S>=u||S<0)&&_++}const p="Number of Weights = "+i/4+`
22
22
  Maximum influences = `+n+`
@@ -3566,7 +3566,7 @@ vMainUV1=uvUpdated;
3566
3566
  `+o)}}return i}}}os._MaterialPluginClassToMainDefine={},os._MaterialPluginCounter=0,Ee.OnEnginesDisposedObservable.add(()=>{Ad()});const Td=[];let Yo=null;function Ad(){Td.length=0,V.OnEventObservable.remove(Yo),Yo=null}class Ii{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,s,r=!0,n=!1){this.priority=500,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,e.pluginManager||(e.pluginManager=new os(e),e.onDisposeObservable.add(()=>{e.pluginManager=void 0})),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,r&&this._pluginManager._addPlugin(this),n&&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){J.Clone(()=>e,this)}serialize(){return J.Serialize(this)}parse(e,t,i){J.Parse(()=>this,e,t,i)}}g([v()],Ii.prototype,"name",void 0),g([v()],Ii.prototype,"priority",void 0),g([v()],Ii.prototype,"registerForExtraEvents",void 0);class vd extends Ni{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class ls extends Ii{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new vd,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=V.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&&H.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&&H.DetailTextureEnabled&&this._isEnabled?(X.PrepareDefinesForMergedUV(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&this._texture&&H.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),X.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&H.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===void 0||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"}]}}}g([Me("detailTexture"),W("_markAllSubMeshesAsTexturesDirty")],ls.prototype,"texture",void 0),g([v()],ls.prototype,"diffuseBlendLevel",void 0),g([v()],ls.prototype,"roughnessBlendLevel",void 0),g([v()],ls.prototype,"bumpLevel",void 0),g([v(),W("_markAllSubMeshesAsTexturesDirty")],ls.prototype,"normalBlendMethod",void 0),g([v(),W("_markAllSubMeshesAsTexturesDirty")],ls.prototype,"isEnabled",void 0);const Xn={effect:null,subMesh:null};class Sd extends Ni{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.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 Y extends zn{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 z(0,0,0),this.diffuseColor=new z(1,1,1),this.specularColor=new z(1,1,1),this.emissiveColor=new z(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=M.Zero(),this._globalAmbientColor=new z(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new ls(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new fn,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),Y.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),Y.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 Y.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||Y.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()}needAlphaBlending(){return this._disableAlphaBlending?!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===V.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==V.MATERIAL_OPAQUE}_hasAlphaChannel(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Rt.GetDefineNames,this._eventInfo),t.materialDefines=new Sd(this._eventInfo.defineNames));const s=this.getScene(),r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();r._needNormals=X.PrepareDefinesForLights(s,e,r,!0,this._maxSimultaneousLights,this._disableLighting),X.PrepareDefinesForMultiview(s,r);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(X.PrepareDefinesForPrePass(s,r,this.canRenderToMRT&&!a),X.PrepareDefinesForOIT(s,r,a),r._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,r._needUVs=!1;for(let h=1;h<=6;++h)r["MAINUV"+h]=!1;if(s.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&&Y.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())X.PrepareDefinesForMergedUV(this._diffuseTexture,r,"DIFFUSE");else return!1;else r.DIFFUSE=!1;if(this._ambientTexture&&Y.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())X.PrepareDefinesForMergedUV(this._ambientTexture,r,"AMBIENT");else return!1;else r.AMBIENT=!1;if(this._opacityTexture&&Y.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())X.PrepareDefinesForMergedUV(this._opacityTexture,r,"OPACITY"),r.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else r.OPACITY=!1;if(this._reflectionTexture&&Y.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===O.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 O.EXPLICIT_MODE:r.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case O.PLANAR_MODE:r.setReflectionMode("REFLECTIONMAP_PLANAR");break;case O.PROJECTION_MODE:r.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case O.SKYBOX_MODE:r.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case O.SPHERICAL_MODE:r.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case O.EQUIRECTANGULAR_MODE:r.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case O.FIXED_EQUIRECTANGULAR_MODE:r.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case O.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:r.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case O.CUBIC_MODE:case O.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&&Y.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())X.PrepareDefinesForMergedUV(this._emissiveTexture,r,"EMISSIVE");else return!1;else r.EMISSIVE=!1;if(this._lightmapTexture&&Y.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())X.PrepareDefinesForMergedUV(this._lightmapTexture,r,"LIGHTMAP"),r.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,r.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else r.LIGHTMAP=!1;if(this._specularTexture&&Y.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())X.PrepareDefinesForMergedUV(this._specularTexture,r,"SPECULAR"),r.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else r.SPECULAR=!1;if(s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&Y.BumpTextureEnabled){if(this._bumpTexture.isReady())X.PrepareDefinesForMergedUV(this._bumpTexture,r,"BUMP"),r.PARALLAX=this._useParallax,r.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;r.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else r.BUMP=!1,r.PARALLAX=!1,r.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&Y.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&&(Y.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),X.PrepareDefinesForMisc(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,r,this._applyDecalMapAfterDetailMap),X.PrepareDefinesForFrameBoundValues(s,n,this,r,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=r,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),X.PrepareDefinesForAttributes(e,r,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let o=!1;if(r.isDirty){const h=r._areLightsDisposed;r.markAsProcessed();const c=new on;r.REFLECTION&&c.addFallback(0,"REFLECTION"),r.SPECULAR&&c.addFallback(0,"SPECULAR"),r.BUMP&&c.addFallback(0,"BUMP"),r.PARALLAX&&c.addFallback(1,"PARALLAX"),r.PARALLAXOCCLUSION&&c.addFallback(0,"PARALLAXOCCLUSION"),r.SPECULAROVERALPHA&&c.addFallback(0,"SPECULAROVERALPHA"),r.FOG&&c.addFallback(1,"FOG"),r.POINTSIZE&&c.addFallback(0,"POINTSIZE"),r.LOGARITHMICDEPTH&&c.addFallback(0,"LOGARITHMICDEPTH"),X.HandleFallbacksForShadows(r,c,this._maxSimultaneousLights),r.SPECULARTERM&&c.addFallback(0,"SPECULARTERM"),r.DIFFUSEFRESNEL&&c.addFallback(1,"DIFFUSEFRESNEL"),r.OPACITYFRESNEL&&c.addFallback(2,"OPACITYFRESNEL"),r.REFLECTIONFRESNEL&&c.addFallback(3,"REFLECTIONFRESNEL"),r.EMISSIVEFRESNEL&&c.addFallback(4,"EMISSIVEFRESNEL"),r.FRESNEL&&c.addFallback(4,"FRESNEL"),r.MULTIVIEW&&c.addFallback(0,"MULTIVIEW");const u=[A.PositionKind];r.NORMAL&&u.push(A.NormalKind),r.TANGENT&&u.push(A.TangentKind);for(let b=1;b<=6;++b)r["UV"+b]&&u.push(`uv${b===1?"":b}`);r.VERTEXCOLOR&&u.push(A.ColorKind),X.PrepareAttributesForBones(u,e,r,c),X.PrepareAttributesForInstances(u,r),X.PrepareAttributesForMorphTargets(u,e,r),X.PrepareAttributesForBakedVertexAnimation(u,e,r);let f="default";const d=["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"],_=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],p=["Material","Scene","Mesh"];this._eventInfo.fallbacks=c,this._eventInfo.fallbackRank=0,this._eventInfo.defines=r,this._eventInfo.uniforms=d,this._eventInfo.attributes=u,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=p,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._callbackPluginEventGeneric(Rt.PrepareEffect,this._eventInfo),fn.AddUniforms(d),Se&&(Se.PrepareUniforms(d,r),Se.PrepareSamplers(_,r)),X.PrepareUniformsAndSamplersList({uniformsNames:d,uniformBuffersNames:p,samplers:_,defines:r,maxSimultaneousLights:this._maxSimultaneousLights}),zs(d);const m={};this.customShaderNameResolve&&(f=this.customShaderNameResolve(f,d,p,_,r,u,m));const T=r.toString(),S=t.effect;let x=s.getEngine().createEffect(f,{attributes:u,uniformsNames:d,uniformBuffersNames:p,samplers:_,defines:T,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:r.NUM_MORPH_INFLUENCERS},processFinalCode:m.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:r.PREPASS},n);if(this._eventInfo.customCode=void 0,x)if(this._onEffectCreatedObservable&&(Xn.effect=x,Xn.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Xn)),this.allowShaderHotSwapping&&S&&!x.isReady()){if(x=S,r.markAsUnprocessed(),o=this.isFrozen,h)return r._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(x,r,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(r._renderId=s.getRenderId(),t.effect._wasPreviouslyReady=!o,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var s;const r=this.getScene(),n=i.materialDefines;if(!n)return;const a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),n.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=a._forceRebindOnNextCall||this._mustRebind(r,a,t.visibility);X.BindBonesParameters(t,a);const h=this._uniformBuffer;if(o){if(this.bindViewProjection(a),!h.useUbo||!this.isFrozen||!h.isSync||a._forceRebindOnNextCall){if(Y.FresnelEnabled&&n.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(h.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),h.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&h.updateColor4("opacityParts",new z(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(h.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),h.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(h.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),h.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(h.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),h.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),r.texturesEnabled){if(this._diffuseTexture&&Y.DiffuseTextureEnabled&&(h.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),X.BindTextureMatrix(this._diffuseTexture,h,"diffuse")),this._ambientTexture&&Y.AmbientTextureEnabled&&(h.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),X.BindTextureMatrix(this._ambientTexture,h,"ambient")),this._opacityTexture&&Y.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),X.BindTextureMatrix(this._opacityTexture,h,"opacity")),this._hasAlphaChannel()&&h.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&Y.ReflectionTextureEnabled&&(h.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),h.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const c=this._reflectionTexture;h.updateVector3("vReflectionPosition",c.boundingBoxPosition),h.updateVector3("vReflectionSize",c.boundingBoxSize)}if(this._emissiveTexture&&Y.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),X.BindTextureMatrix(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&Y.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),X.BindTextureMatrix(this._lightmapTexture,h,"lightmap")),this._specularTexture&&Y.SpecularTextureEnabled&&(h.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),X.BindTextureMatrix(this._specularTexture,h,"specular")),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&Y.BumpTextureEnabled&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),X.BindTextureMatrix(this._bumpTexture,h,"bump"),r._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&Y.RefractionTextureEnabled){let c=1;if(this._refractionTexture.isCube||(h.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(c=this._refractionTexture.depth)),h.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,c,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const u=this._refractionTexture;h.updateVector3("vRefractionPosition",u.boundingBoxPosition),h.updateVector3("vRefractionSize",u.boundingBoxSize)}}}this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),n.SPECULARTERM&&h.updateColor4("vSpecularColor",this.specularColor,this.specularPower),h.updateColor3("vEmissiveColor",Y.EmissiveTextureEnabled?this.emissiveColor:z.BlackReadOnly),h.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),r.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor)}r.texturesEnabled&&(this._diffuseTexture&&Y.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&Y.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Y.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&Y.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&Y.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Y.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&Y.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&Y.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&Y.RefractionTextureEnabled&&(this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Xs(a,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&X.BindLights(r,t,a,n,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==Ie.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||n.PREPASS)&&this.bindView(a),X.BindFogParameters(r,t,a),n.NUM_MORPH_INFLUENCERS&&X.BindMorphTargetParameters(t,a),n.BAKED_VERTEX_ANIMATION_TEXTURE&&((s=t.bakedVertexAnimationManager)===null||s===void 0||s.bind(a,n.INSTANCES)),this.useLogarithmicDepth&&X.BindLogDepth(n,a,r),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),h.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,r,n,a,o,h,c,u;t&&((i=this._diffuseTexture)===null||i===void 0||i.dispose(),(s=this._ambientTexture)===null||s===void 0||s.dispose(),(r=this._opacityTexture)===null||r===void 0||r.dispose(),(n=this._reflectionTexture)===null||n===void 0||n.dispose(),(a=this._emissiveTexture)===null||a===void 0||a.dispose(),(o=this._specularTexture)===null||o===void 0||o.dispose(),(h=this._bumpTexture)===null||h===void 0||h.dispose(),(c=this._lightmapTexture)===null||c===void 0||c.dispose(),(u=this._refractionTexture)===null||u===void 0||u.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=J.Clone(()=>new Y(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=J.Parse(()=>new Y(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),V._parsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return H.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){H.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return H.DetailTextureEnabled}static set DetailTextureEnabled(e){H.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return H.AmbientTextureEnabled}static set AmbientTextureEnabled(e){H.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return H.OpacityTextureEnabled}static set OpacityTextureEnabled(e){H.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return H.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){H.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return H.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){H.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return H.SpecularTextureEnabled}static set SpecularTextureEnabled(e){H.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return H.BumpTextureEnabled}static set BumpTextureEnabled(e){H.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return H.LightmapTextureEnabled}static set LightmapTextureEnabled(e){H.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return H.RefractionTextureEnabled}static set RefractionTextureEnabled(e){H.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return H.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){H.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return H.FresnelEnabled}static set FresnelEnabled(e){H.FresnelEnabled=e}}g([Me("diffuseTexture")],Y.prototype,"_diffuseTexture",void 0),g([W("_markAllSubMeshesAsTexturesAndMiscDirty")],Y.prototype,"diffuseTexture",void 0),g([Me("ambientTexture")],Y.prototype,"_ambientTexture",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"ambientTexture",void 0),g([Me("opacityTexture")],Y.prototype,"_opacityTexture",void 0),g([W("_markAllSubMeshesAsTexturesAndMiscDirty")],Y.prototype,"opacityTexture",void 0),g([Me("reflectionTexture")],Y.prototype,"_reflectionTexture",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"reflectionTexture",void 0),g([Me("emissiveTexture")],Y.prototype,"_emissiveTexture",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"emissiveTexture",void 0),g([Me("specularTexture")],Y.prototype,"_specularTexture",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"specularTexture",void 0),g([Me("bumpTexture")],Y.prototype,"_bumpTexture",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"bumpTexture",void 0),g([Me("lightmapTexture")],Y.prototype,"_lightmapTexture",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"lightmapTexture",void 0),g([Me("refractionTexture")],Y.prototype,"_refractionTexture",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"refractionTexture",void 0),g([Ft("ambient")],Y.prototype,"ambientColor",void 0),g([Ft("diffuse")],Y.prototype,"diffuseColor",void 0),g([Ft("specular")],Y.prototype,"specularColor",void 0),g([Ft("emissive")],Y.prototype,"emissiveColor",void 0),g([v()],Y.prototype,"specularPower",void 0),g([v("useAlphaFromDiffuseTexture")],Y.prototype,"_useAlphaFromDiffuseTexture",void 0),g([W("_markAllSubMeshesAsTexturesAndMiscDirty")],Y.prototype,"useAlphaFromDiffuseTexture",void 0),g([v("useEmissiveAsIllumination")],Y.prototype,"_useEmissiveAsIllumination",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"useEmissiveAsIllumination",void 0),g([v("linkEmissiveWithDiffuse")],Y.prototype,"_linkEmissiveWithDiffuse",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"linkEmissiveWithDiffuse",void 0),g([v("useSpecularOverAlpha")],Y.prototype,"_useSpecularOverAlpha",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"useSpecularOverAlpha",void 0),g([v("useReflectionOverAlpha")],Y.prototype,"_useReflectionOverAlpha",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"useReflectionOverAlpha",void 0),g([v("disableLighting")],Y.prototype,"_disableLighting",void 0),g([W("_markAllSubMeshesAsLightsDirty")],Y.prototype,"disableLighting",void 0),g([v("useObjectSpaceNormalMap")],Y.prototype,"_useObjectSpaceNormalMap",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"useObjectSpaceNormalMap",void 0),g([v("useParallax")],Y.prototype,"_useParallax",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"useParallax",void 0),g([v("useParallaxOcclusion")],Y.prototype,"_useParallaxOcclusion",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"useParallaxOcclusion",void 0),g([v()],Y.prototype,"parallaxScaleBias",void 0),g([v("roughness")],Y.prototype,"_roughness",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"roughness",void 0),g([v()],Y.prototype,"indexOfRefraction",void 0),g([v()],Y.prototype,"invertRefractionY",void 0),g([v()],Y.prototype,"alphaCutOff",void 0),g([v("useLightmapAsShadowmap")],Y.prototype,"_useLightmapAsShadowmap",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"useLightmapAsShadowmap",void 0),g([dr("diffuseFresnelParameters")],Y.prototype,"_diffuseFresnelParameters",void 0),g([W("_markAllSubMeshesAsFresnelDirty")],Y.prototype,"diffuseFresnelParameters",void 0),g([dr("opacityFresnelParameters")],Y.prototype,"_opacityFresnelParameters",void 0),g([W("_markAllSubMeshesAsFresnelAndMiscDirty")],Y.prototype,"opacityFresnelParameters",void 0),g([dr("reflectionFresnelParameters")],Y.prototype,"_reflectionFresnelParameters",void 0),g([W("_markAllSubMeshesAsFresnelDirty")],Y.prototype,"reflectionFresnelParameters",void 0),g([dr("refractionFresnelParameters")],Y.prototype,"_refractionFresnelParameters",void 0),g([W("_markAllSubMeshesAsFresnelDirty")],Y.prototype,"refractionFresnelParameters",void 0),g([dr("emissiveFresnelParameters")],Y.prototype,"_emissiveFresnelParameters",void 0),g([W("_markAllSubMeshesAsFresnelDirty")],Y.prototype,"emissiveFresnelParameters",void 0),g([v("useReflectionFresnelFromSpecular")],Y.prototype,"_useReflectionFresnelFromSpecular",void 0),g([W("_markAllSubMeshesAsFresnelDirty")],Y.prototype,"useReflectionFresnelFromSpecular",void 0),g([v("useGlossinessFromSpecularMapAlpha")],Y.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"useGlossinessFromSpecularMapAlpha",void 0),g([v("maxSimultaneousLights")],Y.prototype,"_maxSimultaneousLights",void 0),g([W("_markAllSubMeshesAsLightsDirty")],Y.prototype,"maxSimultaneousLights",void 0),g([v("invertNormalMapX")],Y.prototype,"_invertNormalMapX",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"invertNormalMapX",void 0),g([v("invertNormalMapY")],Y.prototype,"_invertNormalMapY",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"invertNormalMapY",void 0),g([v("twoSidedLighting")],Y.prototype,"_twoSidedLighting",void 0),g([W("_markAllSubMeshesAsTexturesDirty")],Y.prototype,"twoSidedLighting",void 0),g([v("applyDecalMapAfterDetailMap")],Y.prototype,"_applyDecalMapAfterDetailMap",void 0),g([W("_markAllSubMeshesAsMiscDirty")],Y.prototype,"applyDecalMapAfterDetailMap",void 0),g([v()],Y.prototype,"useLogarithmicDepth",null),Re("BABYLON.StandardMaterial",Y),Ie.DefaultMaterialFactory=l=>new Y("default material",l);const Yn={effect:null,subMesh:null};class vi extends zn{constructor(e,t,i,s={},r=!0){super(e,t,r),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new M,this._cachedWorldViewProjectionMatrix=new M,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options=Object.assign({needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1},s)}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){this._options.uniforms.indexOf(e)===-1&&this._options.uniforms.push(e)}setTexture(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return this._options.externalTextures.indexOf(e)===-1&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((i,s)=>(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;s<t.length;s++)t[s].copyToArray(i,s*16);return this._matrixArrays[e]=i,this}setMatrix3x3(e,t){return this._checkUniform(e),this._matrices3x3[e]=t,this}setMatrix2x2(e,t){return this._checkUniform(e),this._matrices2x2[e]=t,this}setArray2(e,t){return this._checkUniform(e),this._vectors2Arrays[e]=t,this}setArray3(e,t){return this._checkUniform(e),this._vectors3Arrays[e]=t,this}setArray4(e,t){return this._checkUniform(e),this._vectors4Arrays[e]=t,this}setUniformBuffer(e,t){return this._options.uniformBuffers.indexOf(e)===-1&&this._options.uniformBuffers.push(e),this._uniformBuffers[e]=t,this}setTextureSampler(e,t){return this._options.samplerObjects.indexOf(e)===-1&&this._options.samplerObjects.push(e),this._textureSamplers[e]=t,this}setStorageBuffer(e,t){return this._options.storageBuffers.indexOf(e)===-1&&this._options.storageBuffers.push(e),this._storageBuffers[e]=t,this}setDefine(e,t){const i=e.trimEnd()+" ",s=this.options.defines.findIndex(r=>r===e||r.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 s,r,n,a;const o=i&&this._storeEffectOnSubMeshes;if(this.isFrozen)if(o){if(i.effect&&i.effect._wasPreviouslyReady)return!0}else{const w=this._drawWrapper.effect;if(w&&w._wasPreviouslyReady&&w._wasPreviouslyUsingInstances===t)return!0}const h=this.getScene(),c=h.getEngine(),u=[],f=[],d=new on;let _=this._shaderPath,p=this._options.uniforms,m=this._options.uniformBuffers,T=this._options.samplers;c.getCaps().multiview&&h.activeCamera&&h.activeCamera.outputRenderTarget&&h.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,u.push("#define MULTIVIEW"),this._options.uniforms.indexOf("viewProjection")!==-1&&this._options.uniforms.indexOf("viewProjectionR")===-1&&this._options.uniforms.push("viewProjectionR"));for(let w=0;w<this._options.defines.length;w++){const G=this._options.defines[w].indexOf("#define")===0?this._options.defines[w]:`#define ${this._options.defines[w]}`;u.push(G)}for(let w=0;w<this._options.attributes.length;w++)f.push(this._options.attributes[w]);if(e&&e.isVerticesDataPresent(A.ColorKind)&&(f.push(A.ColorKind),u.push("#define VERTEXCOLOR")),t&&(u.push("#define INSTANCES"),X.PushAttributesForInstances(f,this._materialHelperNeedsPreviousMatrices),e!=null&&e.hasThinInstances&&(u.push("#define THIN_INSTANCES"),e&&e.isVerticesDataPresent(A.ColorInstanceKind)&&(f.push(A.ColorInstanceKind),u.push("#define INSTANCESCOLOR")))),e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton){f.push(A.MatricesIndicesKind),f.push(A.MatricesWeightsKind),e.numBoneInfluencers>4&&(f.push(A.MatricesIndicesExtraKind),f.push(A.MatricesWeightsExtraKind));const w=e.skeleton;u.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),d.addCPUSkinningFallback(0,e),w.isUsingTextureForMatrices?(u.push("#define BONETEXTURE"),this._options.uniforms.indexOf("boneTextureWidth")===-1&&this._options.uniforms.push("boneTextureWidth"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(u.push("#define BonesPerMesh "+(w.bones.length+1)),this._options.uniforms.indexOf("mBones")===-1&&this._options.uniforms.push("mBones"))}else u.push("#define NUM_BONE_INFLUENCERS 0");let S=0;const x=e?e.morphTargetManager:null;if(x){const w=x.supportsUVs&&u.indexOf("#define UV1")!==-1,G=x.supportsTangents&&u.indexOf("#define TANGENT")!==-1,te=x.supportsNormals&&u.indexOf("#define NORMAL")!==-1;S=x.numInfluencers,w&&u.push("#define MORPHTARGETS_UV"),G&&u.push("#define MORPHTARGETS_TANGENT"),te&&u.push("#define MORPHTARGETS_NORMAL"),S>0&&u.push("#define MORPHTARGETS"),x.isUsingTextureForTargets&&(u.push("#define MORPHTARGETS_TEXTURE"),this._options.uniforms.indexOf("morphTargetTextureIndices")===-1&&this._options.uniforms.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),u.push("#define NUM_MORPH_INFLUENCERS "+S);for(let Q=0;Q<S;Q++)f.push(A.PositionKind+Q),te&&f.push(A.NormalKind+Q),G&&f.push(A.TangentKind+Q),w&&f.push(A.UVKind+"_"+Q);S>0&&(p=p.slice(),p.push("morphTargetInfluences"),p.push("morphTargetTextureInfo"),p.push("morphTargetTextureIndices"))}else u.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const w=e.bakedVertexAnimationManager;w&&w.isEnabled&&(u.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),this._options.uniforms.indexOf("bakedVertexAnimationSettings")===-1&&this._options.uniforms.push("bakedVertexAnimationSettings"),this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"),this._options.uniforms.indexOf("bakedVertexAnimationTime")===-1&&this._options.uniforms.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture")),X.PrepareAttributesForBakedVertexAnimation(f,e,u)}for(const w in this._textures)if(!this._textures[w].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&u.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(zs(p),nn(this,h,u)),this.customShaderNameResolve&&(p=p.slice(),m=m.slice(),T=T.slice(),_=this.customShaderNameResolve(_,p,m,T,u,f));const b=o?i._getDrawWrapper():this._drawWrapper,I=(s=b==null?void 0:b.effect)!==null&&s!==void 0?s:null,R=(r=b==null?void 0:b.defines)!==null&&r!==void 0?r:null,C=u.join(`
3567
3567
  `);let y=I;return R!==C&&(y=c.createEffect(_,{attributes:f,uniformsNames:p,uniformBuffersNames:m,samplers:T,defines:C,fallbacks:d,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:S},shaderLanguage:this._options.shaderLanguage},c),o?i.setEffect(y,C,this._materialContext):b&&b.setEffect(y,C),this._onEffectCreatedObservable&&(Yn.effect=y,Yn.subMesh=(n=i??(e==null?void 0:e.subMeshes[0]))!==null&&n!==void 0?n:null,this._onEffectCreatedObservable.notifyObservers(Yn))),y._wasPreviouslyUsingInstances=!!t,!((a=!(y!=null&&y.isReady()))!==null&&a!==void 0)||a?!1:(I!==y&&h.resetCachedMaterial(),y._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=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)))}bindForSubMesh(e,t,i){var s;this.bind(e,t,(s=i._drawWrapperOverride)===null||s===void 0?void 0:s.effect,i)}bind(e,t,i,s){var r;const n=s&&this._storeEffectOnSubMeshes,a=i??(n?s.effect:this.getEffect());if(!a)return;this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);const o=this._options.uniformBuffers;let h=!1;if(a&&o&&o.length>0&&this.getScene().getEngine().supportsUniformBuffers)for(let u=0;u<o.length;++u)switch(o[u]){case"Mesh":t&&(t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e));break;case"Scene":X.BindSceneUniformBuffer(a,this.getScene().getSceneUniformBuffer()),this.getScene().finalizeSceneUbo(),h=!0;break}const c=t&&n?this._mustRebind(this.getScene(),a,t.visibility):this.getScene().getCachedMaterial()!==this;if(a&&c){!h&&this._options.uniforms.indexOf("view")!==-1&&a.setMatrix("view",this.getScene().getViewMatrix()),!h&&this._options.uniforms.indexOf("projection")!==-1&&a.setMatrix("projection",this.getScene().getProjectionMatrix()),!h&&this._options.uniforms.indexOf("viewProjection")!==-1&&(a.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._multiview&&a.setMatrix("viewProjectionR",this.getScene()._transformMatrixR)),this.getScene().activeCamera&&this._options.uniforms.indexOf("cameraPosition")!==-1&&a.setVector3("cameraPosition",this.getScene().activeCamera.globalPosition),X.BindBonesParameters(t,a),Xs(a,this,this.getScene());let u;for(u in this._textures)a.setTexture(u,this._textures[u]);for(u in this._textureArrays)a.setTextureArray(u,this._textureArrays[u]);for(u in this._externalTextures)a.setExternalTexture(u,this._externalTextures[u]);for(u in this._ints)a.setInt(u,this._ints[u]);for(u in this._uints)a.setUInt(u,this._uints[u]);for(u in this._floats)a.setFloat(u,this._floats[u]);for(u in this._floatsArrays)a.setArray(u,this._floatsArrays[u]);for(u in this._colors3)a.setColor3(u,this._colors3[u]);for(u in this._colors3Arrays)a.setArray3(u,this._colors3Arrays[u]);for(u in this._colors4){const f=this._colors4[u];a.setFloat4(u,f.r,f.g,f.b,f.a)}for(u in this._colors4Arrays)a.setArray4(u,this._colors4Arrays[u]);for(u in this._vectors2)a.setVector2(u,this._vectors2[u]);for(u in this._vectors3)a.setVector3(u,this._vectors3[u]);for(u in this._vectors4)a.setVector4(u,this._vectors4[u]);for(u in this._quaternions)a.setQuaternion(u,this._quaternions[u]);for(u in this._matrices)a.setMatrix(u,this._matrices[u]);for(u in this._matrixArrays)a.setMatrices(u,this._matrixArrays[u]);for(u in this._matrices3x3)a.setMatrix3x3(u,this._matrices3x3[u]);for(u in this._matrices2x2)a.setMatrix2x2(u,this._matrices2x2[u]);for(u in this._vectors2Arrays)a.setArray2(u,this._vectors2Arrays[u]);for(u in this._vectors3Arrays)a.setArray3(u,this._vectors3Arrays[u]);for(u in this._vectors4Arrays)a.setArray4(u,this._vectors4Arrays[u]);for(u in this._quaternionsArrays)a.setArray4(u,this._quaternionsArrays[u]);for(u in this._uniformBuffers){const f=this._uniformBuffers[u].getBuffer();f&&a.bindUniformBuffer(f,u)}for(u in this._textureSamplers)a.setTextureSampler(u,this._textureSamplers[u]);for(u in this._storageBuffers)a.setStorageBuffer(u,this._storageBuffers[u])}if(a&&t&&(c||!this.isFrozen)){const u=t.morphTargetManager;u&&u.numInfluencers>0&&X.BindMorphTargetParameters(t,a);const f=t.bakedVertexAnimationManager;f&&f.isEnabled&&((r=t.bakedVertexAnimationManager)===null||r===void 0||r.bind(a,!!a._wasPreviouslyUsingInstances))}this._afterBind(t,a)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let s=0;s<i.length;s++)e.push(i[s])}return e}hasTexture(e){if(super.hasTexture(e))return!0;for(const t in this._textures)if(this._textures[t]===e)return!0;for(const t in this._textureArrays){const i=this._textureArrays[t];for(let s=0;s<i.length;s++)if(i[s]===e)return!0}return!1}clone(e){const t=J.Clone(()=>new vi(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);t.name=e,t.id=e,typeof t._shaderPath=="object"&&(t._shaderPath=Object.assign({},t._shaderPath)),this._options=Object.assign({},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 r=this._textureArrays[s];for(let n=0;n<r.length;n++)r[n].dispose()}}this._textures={},super.dispose(e,t,i)}serialize(){const e=J.Serialize(this);e.customType="BABYLON.ShaderMaterial",e.uniqueId=this.uniqueId,e.options=this._options,e.shaderPath=this._shaderPath,e.storeEffectOnSubMeshes=this._storeEffectOnSubMeshes;let t;e.stencil=this.stencil.serialize(),e.textures={};for(t in this._textures)e.textures[t]=this._textures[t].serialize();e.textureArrays={};for(t in this._textureArrays){e.textureArrays[t]=[];const i=this._textureArrays[t];for(let s=0;s<i.length;s++)e.textureArrays[t].push(i[s].serialize())}e.ints={};for(t in this._ints)e.ints[t]=this._ints[t];e.uints={};for(t in this._uints)e.uints[t]=this._uints[t];e.floats={};for(t in this._floats)e.floats[t]=this._floats[t];e.FloatArrays={};for(t in this._floatsArrays)e.FloatArrays[t]=this._floatsArrays[t];e.colors3={};for(t in this._colors3)e.colors3[t]=this._colors3[t].asArray();e.colors3Arrays={};for(t in this._colors3Arrays)e.colors3Arrays[t]=this._colors3Arrays[t];e.colors4={};for(t in this._colors4)e.colors4[t]=this._colors4[t].asArray();e.colors4Arrays={};for(t in this._colors4Arrays)e.colors4Arrays[t]=this._colors4Arrays[t];e.vectors2={};for(t in this._vectors2)e.vectors2[t]=this._vectors2[t].asArray();e.vectors3={};for(t in this._vectors3)e.vectors3[t]=this._vectors3[t].asArray();e.vectors4={};for(t in this._vectors4)e.vectors4[t]=this._vectors4[t].asArray();e.quaternions={};for(t in this._quaternions)e.quaternions[t]=this._quaternions[t].asArray();e.matrices={};for(t in this._matrices)e.matrices[t]=this._matrices[t].asArray();e.matrixArray={};for(t in this._matrixArrays)e.matrixArray[t]=this._matrixArrays[t];e.matrices3x3={};for(t in this._matrices3x3)e.matrices3x3[t]=this._matrices3x3[t];e.matrices2x2={};for(t in this._matrices2x2)e.matrices2x2[t]=this._matrices2x2[t];e.vectors2Arrays={};for(t in this._vectors2Arrays)e.vectors2Arrays[t]=this._vectors2Arrays[t];e.vectors3Arrays={};for(t in this._vectors3Arrays)e.vectors3Arrays[t]=this._vectors3Arrays[t];e.vectors4Arrays={};for(t in this._vectors4Arrays)e.vectors4Arrays[t]=this._vectors4Arrays[t];e.quaternionsArrays={};for(t in this._quaternionsArrays)e.quaternionsArrays[t]=this._quaternionsArrays[t];return e}static Parse(e,t,i){const s=J.Parse(()=>new vi(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);let r;e.stencil&&s.stencil.parse(e.stencil,t,i);for(r in e.textures)s.setTexture(r,O.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],a=new Array;for(let o=0;o<n.length;o++)a.push(O.Parse(n[o],t,i));s.setTextureArray(r,a)}for(r in e.ints)s.setInt(r,e.ints[r]);for(r in e.uints)s.setUInt(r,e.uints[r]);for(r in e.floats)s.setFloat(r,e.floats[r]);for(r in e.floatsArrays)s.setFloats(r,e.floatsArrays[r]);for(r in e.colors3)s.setColor3(r,z.FromArray(e.colors3[r]));for(r in e.colors3Arrays){const n=e.colors3Arrays[r].reduce((a,o,h)=>(h%3===0?a.push([o]):a[a.length-1].push(o),a),[]).map(a=>z.FromArray(a));s.setColor3Array(r,n)}for(r in e.colors4)s.setColor4(r,ge.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const n=e.colors4Arrays[r].reduce((a,o,h)=>(h%4===0?a.push([o]):a[a.length-1].push(o),a),[]).map(a=>ge.FromArray(a));s.setColor4Array(r,n)}for(r in e.vectors2)s.setVector2(r,ae.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,E.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,He.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,K.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,M.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise((r,n)=>{const a=new wt;a.addEventListener("readystatechange",()=>{if(a.readyState==4)if(a.status==200){const o=JSON.parse(a.responseText),h=this.Parse(o,i||Ee.LastCreatedScene,s);e&&(h.name=e),r(h)}else n("Unable to load the ShaderMaterial")}),a.open("GET",t),a.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((s,r)=>{const n=new wt;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const a=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(a.shaderMaterial),h=this.Parse(o,t||Ee.LastCreatedScene,i);h.snippetId=e,s(h)}else r("Unable to load the snippet "+e)}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}vi.SnippetUrl="https://snippet.babylonjs.com",vi.CreateFromSnippetAsync=vi.ParseFromSnippetAsync,Re("BABYLON.ShaderMaterial",vi),lt.AddNodeConstructor("Light_Type_3",(l,e)=>()=>new Or(l,E.Zero(),e));class Or extends Ae{constructor(e,t,i){super(e,i),this.groundColor=new z(0,0,0),this.direction=t||E.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=E.Normalize(e.subtract(E.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=E.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=E.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=M.Identity()),this._worldMatrix}getTypeID(){return Ae.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}g([Ft()],Or.prototype,"groundColor",void 0),g([Ut()],Or.prototype,"direction",void 0);class bs extends Ae{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return this.parent&&this.parent.getWorldMatrix?(this.transformedPosition||(this.transformedPosition=E.Zero()),E.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=E.Zero()),E.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=E.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=E.Cross(this.direction,As.Y),t=E.Cross(e,this.direction);return E.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=E.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=M.Identity()),M.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)}}g([Ut()],bs.prototype,"position",null),g([Ut()],bs.prototype,"direction",null),g([v()],bs.prototype,"shadowMinZ",null),g([v()],bs.prototype,"shadowMaxZ",null),lt.AddNodeConstructor("Light_Type_1",(l,e)=>()=>new fi(l,E.Zero(),e));class fi extends bs{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i){super(e,i),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return Ae.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;t&&M.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,this.shadowMinZ!==void 0?this.shadowMinZ:t.minZ,this.shadowMaxZ!==void 0?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const c=E.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;let u=Number.MAX_VALUE,f=Number.MIN_VALUE;for(let d=0;d<i.length;d++){const _=i[d];if(!_)continue;const m=_.getBoundingInfo().boundingBox;for(let T=0;T<m.vectorsWorld.length;T++)E.TransformCoordinatesToRef(m.vectorsWorld[T],t,c),c.x<this._orthoLeft&&(this._orthoLeft=c.x),c.y<this._orthoBottom&&(this._orthoBottom=c.y),c.x>this._orthoRight&&(this._orthoRight=c.x),c.y>this._orthoTop&&(this._orthoTop=c.y),this.autoCalcShadowZBounds&&(c.z<u&&(u=c.z),c.z>f&&(f=c.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=u,this._shadowMaxZ=f)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,a=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,o=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,h=this.getScene().getEngine().useReverseDepthBuffer;M.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,h?o:a,h?a:o,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}g([v()],fi.prototype,"shadowFrustumSize",null),g([v()],fi.prototype,"shadowOrthoScale",null),g([v()],fi.prototype,"autoUpdateExtends",void 0),g([v()],fi.prototype,"autoCalcShadowZBounds",void 0),g([v("orthoLeft")],fi.prototype,"_orthoLeft",void 0),g([v("orthoRight")],fi.prototype,"_orthoRight",void 0),g([v("orthoTop")],fi.prototype,"_orthoTop",void 0),g([v("orthoBottom")],fi.prototype,"_orthoBottom",void 0),lt.AddNodeConstructor("Light_Type_0",(l,e)=>()=>new Dr(l,E.Zero(),e));class Dr extends bs{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 Ae.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new E(1,0,0);case 1:return new E(-1,0,0);case 2:return new E(0,-1,0);case 3:return new E(0,1,0);case 4:return new E(0,0,1);case 5:return new E(0,0,-1)}return E.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;const r=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,n=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;M.PerspectiveFovLHToRef(this.shadowAngle,1,a?n:r,a?r:n,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}g([v()],Dr.prototype,"shadowAngle",null),lt.AddNodeConstructor("Light_Type_2",(l,e)=>()=>new Kt(l,E.Zero(),E.Zero(),0,0,e));class Kt extends bs{get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(e*.5),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()}get innerAngle(){return this._innerAngle}set innerAngle(e){this._innerAngle=e,this._computeAngleValues()}get shadowAngleScale(){return this._shadowAngleScale}set shadowAngleScale(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()}get projectionTextureMatrix(){return this._projectionTextureMatrix}get projectionTextureLightNear(){return this._projectionTextureLightNear}set projectionTextureLightNear(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureLightFar(){return this._projectionTextureLightFar}set projectionTextureLightFar(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureUpDirection(){return this._projectionTextureUpDirection}set projectionTextureUpDirection(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0}get projectionTexture(){return this._projectionTexture}set projectionTexture(e){this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(Kt._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):Kt._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce(()=>{this._markMeshesAsLightDirty()})))}static _IsProceduralTexture(e){return e.onGeneratedObservable!==void 0}static _IsTexture(e){return e.onLoadObservable!==void 0}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,s,r,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=M.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=E.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=E.Zero(),this._projectionTextureViewLightMatrix=M.Zero(),this._projectionTextureProjectionLightMatrix=M.Zero(),this._projectionTextureScalingMatrix=M.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=s,this.exponent=r}getClassName(){return"SpotLight"}getTypeID(){return Ae.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;this._shadowAngleScale=this._shadowAngleScale||1;const r=this._shadowAngleScale*this._angle,n=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,a=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;M.PerspectiveFovLHToRef(r,1,o?a:n,o?n:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.direction,this._projectionTextureViewTargetVector),M.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),s=-i*t,r=1/Math.tan(this._angle/2),n=1;M.FromValuesToRef(r/n,0,0,0,0,r,0,0,0,0,i,1,0,0,s,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof O){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;M.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}_computeAngleValues(){this._lightAngleScale=1/Math.max(.001,Math.cos(this._innerAngle*.5)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightSampler"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=E.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=E.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return this.computeTransformedInformation()?i=E.Normalize(this.transformedDirection):i=E.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){const t=this._scene.getEngine(),i=this.shadowMinZ!==void 0?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=this.shadowMaxZ!==void 0?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!!(this.projectionTexture&&this.projectionTexture.isReady())}}g([v()],Kt.prototype,"angle",null),g([v()],Kt.prototype,"innerAngle",null),g([v()],Kt.prototype,"shadowAngleScale",null),g([v()],Kt.prototype,"exponent",void 0),g([v()],Kt.prototype,"projectionTextureLightNear",null),g([v()],Kt.prototype,"projectionTextureLightFar",null),g([v()],Kt.prototype,"projectionTextureUpDirection",null),g([Me("projectedLightTexture")],Kt.prototype,"_projectionTexture",void 0);class dt{static SetMatrix(e,t,i,s,r){let n=null;if(i.semantic==="MODEL"?n=t.getWorldMatrix():i.semantic==="PROJECTION"?n=e.getProjectionMatrix():i.semantic==="VIEW"?n=e.getViewMatrix():i.semantic==="MODELVIEWINVERSETRANSPOSE"?n=M.Transpose(t.getWorldMatrix().multiply(e.getViewMatrix()).invert()):i.semantic==="MODELVIEW"?n=t.getWorldMatrix().multiply(e.getViewMatrix()):i.semantic==="MODELVIEWPROJECTION"?n=t.getWorldMatrix().multiply(e.getTransformMatrix()):i.semantic==="MODELINVERSE"?n=t.getWorldMatrix().invert():i.semantic==="VIEWINVERSE"?n=e.getViewMatrix().invert():i.semantic==="PROJECTIONINVERSE"?n=e.getProjectionMatrix().invert():i.semantic==="MODELVIEWINVERSE"?n=t.getWorldMatrix().multiply(e.getViewMatrix()).invert():i.semantic==="MODELVIEWPROJECTIONINVERSE"?n=t.getWorldMatrix().multiply(e.getTransformMatrix()).invert():i.semantic==="MODELINVERSETRANSPOSE"&&(n=M.Transpose(t.getWorldMatrix().invert())),n)switch(i.type){case Yt.FLOAT_MAT2:r.setMatrix2x2(s,M.GetAsMatrix2x2(n));break;case Yt.FLOAT_MAT3:r.setMatrix3x3(s,M.GetAsMatrix3x3(n));break;case Yt.FLOAT_MAT4:r.setMatrix(s,n);break}}static SetUniform(e,t,i,s){switch(s){case Yt.FLOAT:return e.setFloat(t,i),!0;case Yt.FLOAT_VEC2:return e.setVector2(t,ae.FromArray(i)),!0;case Yt.FLOAT_VEC3:return e.setVector3(t,E.FromArray(i)),!0;case Yt.FLOAT_VEC4:return e.setVector4(t,He.FromArray(i)),!0;default:return!1}}static GetWrapMode(e){switch(e){case Pr.CLAMP_TO_EDGE:return O.CLAMP_ADDRESSMODE;case Pr.MIRRORED_REPEAT:return O.MIRROR_ADDRESSMODE;case Pr.REPEAT:return O.WRAP_ADDRESSMODE;default:return O.WRAP_ADDRESSMODE}}static GetByteStrideFromType(e){switch(e.type){case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4;case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 1}}static GetTextureFilterMode(e){switch(e){case Ei.LINEAR:case Ei.LINEAR_MIPMAP_NEAREST:case Ei.LINEAR_MIPMAP_LINEAR:return O.TRILINEAR_SAMPLINGMODE;case Ei.NEAREST:case Ei.NEAREST_MIPMAP_NEAREST:return O.NEAREST_SAMPLINGMODE;default:return O.BILINEAR_SAMPLINGMODE}}static GetBufferFromBufferView(e,t,i,s,r){i=t.byteOffset+i;const n=e.loadedBufferViews[t.buffer];if(i+s>n.byteLength)throw new Error("Buffer access is out of range");const a=n.buffer;switch(i+=n.byteOffset,r){case as.BYTE:return new Int8Array(a,i,s);case as.UNSIGNED_BYTE:return new Uint8Array(a,i,s);case as.SHORT:return new Int16Array(a,i,s);case as.UNSIGNED_SHORT:return new Uint16Array(a,i,s);default:return new Float32Array(a,i,s)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],s=t.count*dt.GetByteStrideFromType(t);return dt.GetBufferFromBufferView(e,i,t.byteOffset,s,t.componentType)}static DecodeBufferToText(e){let t="";const i=e.byteLength;for(let s=0;s<i;++s)t+=String.fromCharCode(e[s]);return t}static GetDefaultMaterial(e){if(!dt._DefaultMaterial){nt.ShadersStore.GLTFDefaultMaterialVertexShader=["precision highp float;","","uniform mat4 worldView;","uniform mat4 projection;","","attribute vec3 position;","","void main(void)","{"," gl_Position = projection * worldView * vec4(position, 1.0);","}"].join(`
3568
3568
  `),nt.ShadersStore.GLTFDefaultMaterialPixelShader=["precision highp float;","","uniform vec4 u_emission;","","void main(void)","{"," gl_FragColor = u_emission;","}"].join(`
3569
- `);const t={vertex:"GLTFDefaultMaterial",fragment:"GLTFDefaultMaterial"},i={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};dt._DefaultMaterial=new vi("GLTFDefaultMaterial",e,t,i),dt._DefaultMaterial.setColor4("u_emission",new ge(.5,.5,.5,1))}return dt._DefaultMaterial}}dt._DefaultMaterial=null;class P{}P.ALPHA_DISABLE=0,P.ALPHA_ADD=1,P.ALPHA_COMBINE=2,P.ALPHA_SUBTRACT=3,P.ALPHA_MULTIPLY=4,P.ALPHA_MAXIMIZED=5,P.ALPHA_ONEONE=6,P.ALPHA_PREMULTIPLIED=7,P.ALPHA_PREMULTIPLIED_PORTERDUFF=8,P.ALPHA_INTERPOLATE=9,P.ALPHA_SCREENMODE=10,P.ALPHA_ONEONE_ONEONE=11,P.ALPHA_ALPHATOCOLOR=12,P.ALPHA_REVERSEONEMINUS=13,P.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,P.ALPHA_ONEONE_ONEZERO=15,P.ALPHA_EXCLUSION=16,P.ALPHA_LAYER_ACCUMULATE=17,P.ALPHA_EQUATION_ADD=0,P.ALPHA_EQUATION_SUBSTRACT=1,P.ALPHA_EQUATION_REVERSE_SUBTRACT=2,P.ALPHA_EQUATION_MAX=3,P.ALPHA_EQUATION_MIN=4,P.ALPHA_EQUATION_DARKEN=5,P.DELAYLOADSTATE_NONE=0,P.DELAYLOADSTATE_LOADED=1,P.DELAYLOADSTATE_LOADING=2,P.DELAYLOADSTATE_NOTLOADED=4,P.NEVER=512,P.ALWAYS=519,P.LESS=513,P.EQUAL=514,P.LEQUAL=515,P.GREATER=516,P.GEQUAL=518,P.NOTEQUAL=517,P.KEEP=7680,P.ZERO=0,P.REPLACE=7681,P.INCR=7682,P.DECR=7683,P.INVERT=5386,P.INCR_WRAP=34055,P.DECR_WRAP=34056,P.TEXTURE_CLAMP_ADDRESSMODE=0,P.TEXTURE_WRAP_ADDRESSMODE=1,P.TEXTURE_MIRROR_ADDRESSMODE=2,P.TEXTURE_CREATIONFLAG_STORAGE=1,P.TEXTUREFORMAT_ALPHA=0,P.TEXTUREFORMAT_LUMINANCE=1,P.TEXTUREFORMAT_LUMINANCE_ALPHA=2,P.TEXTUREFORMAT_RGB=4,P.TEXTUREFORMAT_RGBA=5,P.TEXTUREFORMAT_RED=6,P.TEXTUREFORMAT_R=6,P.TEXTUREFORMAT_RG=7,P.TEXTUREFORMAT_RED_INTEGER=8,P.TEXTUREFORMAT_R_INTEGER=8,P.TEXTUREFORMAT_RG_INTEGER=9,P.TEXTUREFORMAT_RGB_INTEGER=10,P.TEXTUREFORMAT_RGBA_INTEGER=11,P.TEXTUREFORMAT_BGRA=12,P.TEXTUREFORMAT_DEPTH24_STENCIL8=13,P.TEXTUREFORMAT_DEPTH32_FLOAT=14,P.TEXTUREFORMAT_DEPTH16=15,P.TEXTUREFORMAT_DEPTH24=16,P.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,P.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,P.TEXTUREFORMAT_STENCIL8=19,P.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,P.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,P.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,P.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,P.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,P.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,P.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,P.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,P.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,P.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,P.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,P.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,P.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,P.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,P.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,P.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,P.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,P.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,P.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,P.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,P.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,P.TEXTURETYPE_UNSIGNED_BYTE=0,P.TEXTURETYPE_UNSIGNED_INT=0,P.TEXTURETYPE_FLOAT=1,P.TEXTURETYPE_HALF_FLOAT=2,P.TEXTURETYPE_BYTE=3,P.TEXTURETYPE_SHORT=4,P.TEXTURETYPE_UNSIGNED_SHORT=5,P.TEXTURETYPE_INT=6,P.TEXTURETYPE_UNSIGNED_INTEGER=7,P.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,P.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,P.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,P.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,P.TEXTURETYPE_UNSIGNED_INT_24_8=12,P.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,P.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,P.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,P.TEXTURETYPE_UNDEFINED=16,P.TEXTURE_2D=3553,P.TEXTURE_2D_ARRAY=35866,P.TEXTURE_CUBE_MAP=34067,P.TEXTURE_CUBE_MAP_ARRAY=3735928559,P.TEXTURE_3D=32879,P.TEXTURE_NEAREST_SAMPLINGMODE=1,P.TEXTURE_NEAREST_NEAREST=1,P.TEXTURE_BILINEAR_SAMPLINGMODE=2,P.TEXTURE_LINEAR_LINEAR=2,P.TEXTURE_TRILINEAR_SAMPLINGMODE=3,P.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,P.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,P.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,P.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,P.TEXTURE_NEAREST_LINEAR=7,P.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,P.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,P.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,P.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,P.TEXTURE_LINEAR_NEAREST=12,P.TEXTURE_EXPLICIT_MODE=0,P.TEXTURE_SPHERICAL_MODE=1,P.TEXTURE_PLANAR_MODE=2,P.TEXTURE_CUBIC_MODE=3,P.TEXTURE_PROJECTION_MODE=4,P.TEXTURE_SKYBOX_MODE=5,P.TEXTURE_INVCUBIC_MODE=6,P.TEXTURE_EQUIRECTANGULAR_MODE=7,P.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,P.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,P.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,P.TEXTURE_FILTERING_QUALITY_HIGH=64,P.TEXTURE_FILTERING_QUALITY_MEDIUM=16,P.TEXTURE_FILTERING_QUALITY_LOW=8,P.SCALEMODE_FLOOR=1,P.SCALEMODE_NEAREST=2,P.SCALEMODE_CEILING=3,P.MATERIAL_TextureDirtyFlag=1,P.MATERIAL_LightDirtyFlag=2,P.MATERIAL_FresnelDirtyFlag=4,P.MATERIAL_AttributesDirtyFlag=8,P.MATERIAL_MiscDirtyFlag=16,P.MATERIAL_PrePassDirtyFlag=32,P.MATERIAL_AllDirtyFlag=63,P.MATERIAL_TriangleFillMode=0,P.MATERIAL_WireFrameFillMode=1,P.MATERIAL_PointFillMode=2,P.MATERIAL_PointListDrawMode=3,P.MATERIAL_LineListDrawMode=4,P.MATERIAL_LineLoopDrawMode=5,P.MATERIAL_LineStripDrawMode=6,P.MATERIAL_TriangleStripDrawMode=7,P.MATERIAL_TriangleFanDrawMode=8,P.MATERIAL_ClockWiseSideOrientation=0,P.MATERIAL_CounterClockWiseSideOrientation=1,P.ACTION_NothingTrigger=0,P.ACTION_OnPickTrigger=1,P.ACTION_OnLeftPickTrigger=2,P.ACTION_OnRightPickTrigger=3,P.ACTION_OnCenterPickTrigger=4,P.ACTION_OnPickDownTrigger=5,P.ACTION_OnDoublePickTrigger=6,P.ACTION_OnPickUpTrigger=7,P.ACTION_OnPickOutTrigger=16,P.ACTION_OnLongPressTrigger=8,P.ACTION_OnPointerOverTrigger=9,P.ACTION_OnPointerOutTrigger=10,P.ACTION_OnEveryFrameTrigger=11,P.ACTION_OnIntersectionEnterTrigger=12,P.ACTION_OnIntersectionExitTrigger=13,P.ACTION_OnKeyDownTrigger=14,P.ACTION_OnKeyUpTrigger=15,P.PARTICLES_BILLBOARDMODE_Y=2,P.PARTICLES_BILLBOARDMODE_ALL=7,P.PARTICLES_BILLBOARDMODE_STRETCHED=8,P.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,P.MESHES_CULLINGSTRATEGY_STANDARD=0,P.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,P.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,P.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,P.SCENELOADER_NO_LOGGING=0,P.SCENELOADER_MINIMAL_LOGGING=1,P.SCENELOADER_SUMMARY_LOGGING=2,P.SCENELOADER_DETAILED_LOGGING=3,P.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,P.PREPASS_POSITION_TEXTURE_TYPE=1,P.PREPASS_VELOCITY_TEXTURE_TYPE=2,P.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,P.PREPASS_COLOR_TEXTURE_TYPE=4,P.PREPASS_DEPTH_TEXTURE_TYPE=5,P.PREPASS_NORMAL_TEXTURE_TYPE=6,P.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,P.BUFFER_CREATIONFLAG_READ=1,P.BUFFER_CREATIONFLAG_WRITE=2,P.BUFFER_CREATIONFLAG_READWRITE=3,P.BUFFER_CREATIONFLAG_UNIFORM=4,P.BUFFER_CREATIONFLAG_VERTEX=8,P.BUFFER_CREATIONFLAG_INDEX=16,P.BUFFER_CREATIONFLAG_STORAGE=32,P.RENDERPASS_MAIN=0,P.INPUT_ALT_KEY=18,P.INPUT_CTRL_KEY=17,P.INPUT_META_KEY1=91,P.INPUT_META_KEY2=92,P.INPUT_META_KEY3=93,P.INPUT_SHIFT_KEY=16,P.SNAPSHOTRENDERING_STANDARD=0,P.SNAPSHOTRENDERING_FAST=1,P.PERSPECTIVE_CAMERA=0,P.ORTHOGRAPHIC_CAMERA=1,P.FOVMODE_VERTICAL_FIXED=0,P.FOVMODE_HORIZONTAL_FIXED=1,P.RIG_MODE_NONE=0,P.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,P.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,P.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,P.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,P.RIG_MODE_STEREOSCOPIC_INTERLACED=14,P.RIG_MODE_VR=20,P.RIG_MODE_WEBVR=21,P.RIG_MODE_CUSTOM=22,P.MAX_SUPPORTED_UV_SETS=6,P.GL_ALPHA_EQUATION_ADD=32774,P.GL_ALPHA_EQUATION_MIN=32775,P.GL_ALPHA_EQUATION_MAX=32776,P.GL_ALPHA_EQUATION_SUBTRACT=32778,P.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,P.GL_ALPHA_FUNCTION_SRC=768,P.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,P.GL_ALPHA_FUNCTION_SRC_ALPHA=770,P.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,P.GL_ALPHA_FUNCTION_DST_ALPHA=772,P.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,P.GL_ALPHA_FUNCTION_DST_COLOR=774,P.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,P.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,P.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,P.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,P.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,P.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,P.SnippetUrl="https://snippet.babylonjs.com";var hs;(function(l){l[l.IDENTIFIER=1]="IDENTIFIER",l[l.UNKNOWN=2]="UNKNOWN",l[l.END_OF_INPUT=3]="END_OF_INPUT"})(hs||(hs={}));class Ko{constructor(e){this._pos=0,this.currentToken=hs.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}getNextToken(){if(this.isEnd())return hs.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=hs.UNKNOWN,this.currentString==="_"||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=hs.IDENTIFIER,this.currentIdentifier=this.currentString;!this.isEnd()&&(this.isLetterOrDigitPattern.test(this.currentString=this.peek())||this.currentString==="_");)this.currentIdentifier+=this.currentString,this.forward();return this.currentToken}peek(){return this._toParse[this._pos]}read(){return this._toParse[this._pos++]}forward(){this._pos++}isEnd(){return this._pos>=this._maxPos}}const jo=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],qo=["world","view","projection","worldView","worldViewProjection","mBones"],Rd=["translation","rotation","scale"],xd=["position","rotationQuaternion","scaling"],Cd=(l,e)=>{for(const t in l){const i=l[t];e.buffers[t]=i,e.buffersCount++}},bd=(l,e)=>{for(const t in l){const i=l[t];e.shaders[t]=i,e.shaderscount++}},kt=(l,e,t)=>{for(const i in l){const s=l[i];t[e][i]=s}},Id=l=>{if(l)for(let e=0;e<l.length/2;e++)l[e*2+1]=1-l[e*2+1]},Zo=l=>{if(l.semantic==="NORMAL")return"normal";if(l.semantic==="POSITION")return"position";if(l.semantic==="JOINT")return"matricesIndices";if(l.semantic==="WEIGHT")return"matricesWeights";if(l.semantic==="COLOR")return"color";if(l.semantic&&l.semantic.indexOf("TEXCOORD_")!==-1){const e=Number(l.semantic.split("_")[1]);return"uv"+(e===0?"":e+1)}return null},yd=l=>{for(const e in l.animations){const t=l.animations[e];if(!t.channels||!t.samplers)continue;let i=null;for(let s=0;s<t.channels.length;s++){const r=t.channels[s],n=t.samplers[r.sampler];if(!n)continue;let a=null,o=null;t.parameters?(a=t.parameters[n.input],o=t.parameters[n.output]):(a=n.input,o=n.output);const h=dt.GetBufferFromAccessor(l,l.accessors[a]),c=dt.GetBufferFromAccessor(l,l.accessors[o]),u=r.target.id;let f=l.scene.getNodeById(u);if(f===null&&(f=l.scene.getNodeByName(u)),f===null){k.Warn("Creating animation named "+e+". But cannot find node named "+u+" to attach to");continue}const d=f instanceof Ue;let _=r.target.path;const p=Rd.indexOf(_);p!==-1&&(_=xd[p]);let m=N.ANIMATIONTYPE_MATRIX;d||(_==="rotationQuaternion"?(m=N.ANIMATIONTYPE_QUATERNION,f.rotationQuaternion=new K):m=N.ANIMATIONTYPE_VECTOR3);let T=null;const S=[];let x=0,b=!1;d&&i&&i.getKeys().length===h.length&&(T=i,b=!0),b||(l.scene._blockEntityCollection=!!l.assetContainer,T=new N(e,d?"_matrix":_,1,m,N.ANIMATIONLOOPMODE_CYCLE),l.scene._blockEntityCollection=!1);for(let I=0;I<h.length;I++){let R=null;if(_==="rotationQuaternion"?(R=K.FromArray([c[x],c[x+1],c[x+2],c[x+3]]),x+=4):(R=E.FromArray([c[x],c[x+1],c[x+2]]),x+=3),d){const C=f;let y=E.Zero(),w=new K,G=E.Zero(),te=C.getBaseMatrix();b&&i&&(te=i.getKeys()[I].value),te.decompose(G,w,y),_==="position"?y=R:_==="rotationQuaternion"?w=R:G=R,R=M.Compose(G,w,y)}b?i&&(i.getKeys()[I].value=R):S.push({frame:h[I],value:R})}!b&&T&&(T.setKeys(S),f.animations.push(T)),i=T,l.scene.stopAnimation(f),l.scene.beginAnimation(f,0,h[h.length-1],!0,1)}}},Kn=l=>{let e=null;if(l.translation||l.rotation||l.scale){const t=E.FromArray(l.scale||[1,1,1]),i=K.FromArray(l.rotation||[0,0,0,1]),s=E.FromArray(l.translation||[0,0,0]);e=M.Compose(t,i,s)}else e=M.FromArray(l.matrix);return e},Qo=(l,e,t,i)=>{for(let r=0;r<i.bones.length;r++)if(i.bones[r].name===t)return i.bones[r];const s=l.nodes;for(const r in s){const n=s[r];if(!n.jointName)continue;const a=n.children;for(let o=0;o<a.length;o++){const h=l.nodes[a[o]];if(h.jointName&&h.jointName===t){const c=Kn(n),u=new Ue(n.name||"",i,Qo(l,e,n.jointName,i),c);return u.id=r,u}}}return null},Md=(l,e)=>{for(let t=0;t<l.length;t++){const i=l[t];for(let s=0;s<i.node.children.length;s++)if(i.node.children[s]===e)return i.bone}return null},jn=(l,e)=>{const t=l.nodes;let i=t[e];if(i)return{node:i,id:e};for(const s in t)if(i=t[s],i.jointName===e)return{node:i,id:s};return null},Pd=(l,e)=>{for(let t=0;t<l.jointNames.length;t++)if(l.jointNames[t]===e)return!0;return!1},Od=(l,e,t,i)=>{for(const s in l.nodes){const r=l.nodes[s],n=s;if(!r.jointName||Pd(t,r.jointName))continue;const a=Kn(r),o=new Ue(r.name||"",e,null,a);o.id=n,i.push({bone:o,node:r,id:n})}for(let s=0;s<i.length;s++){const r=i[s],n=r.node.children;for(let a=0;a<n.length;a++){let o=null;for(let h=0;h<i.length;h++)if(i[h].id===n[a]){o=i[h];break}o&&(o.bone._parent=r.bone,r.bone.children.push(o.bone))}}},Dd=(l,e,t,i)=>{if(i||(i=new qs(e.name||"","",l.scene)),!e.babylonSkeleton)return i;const s=[],r=[];Od(l,i,e,s),i.bones=[];for(let a=0;a<e.jointNames.length;a++){const o=jn(l,e.jointNames[a]);if(!o)continue;const h=o.node;if(!h){k.Warn("Joint named "+e.jointNames[a]+" does not exist");continue}const c=o.id,u=l.scene.getBoneById(c);if(u){i.bones.push(u);continue}let f=!1,d=null;for(let m=0;m<a;m++){const T=jn(l,e.jointNames[m]);if(!T)continue;const S=T.node;if(!S){k.Warn("Joint named "+e.jointNames[m]+" does not exist when looking for parent");continue}const x=S.children;if(x){f=!1;for(let b=0;b<x.length;b++)if(x[b]===c){d=Qo(l,e,e.jointNames[m],i),f=!0;break}if(f)break}}const _=Kn(h);!d&&s.length>0&&(d=Md(s,c),d&&r.indexOf(d)===-1&&r.push(d));const p=new Ue(h.jointName||"",i,d,_);p.id=c}const n=i.bones;i.bones=[];for(let a=0;a<e.jointNames.length;a++){const o=jn(l,e.jointNames[a]);if(o){for(let h=0;h<n.length;h++)if(n[h].id===o.id){i.bones.push(n[h]);break}}}i.prepare();for(let a=0;a<r.length;a++)i.bones.push(r[a]);return i},$o=(l,e,t,i,s)=>{if(s||(l.scene._blockEntityCollection=!!l.assetContainer,s=new ne(e.name||"",l.scene),s._parentContainer=l.assetContainer,l.scene._blockEntityCollection=!1,s.id=i),!e.babylonNode)return s;const r=[];let n=null;const a=new Array,o=new Array,h=new Array,c=new Array;for(let d=0;d<t.length;d++){const _=t[d],p=l.meshes[_];if(p)for(let m=0;m<p.primitives.length;m++){const T=new me,S=p.primitives[m],x=S.attributes;let b=null,I=null;for(const C in x)if(b=l.accessors[x[C]],I=dt.GetBufferFromAccessor(l,b),C==="NORMAL")T.normals=new Float32Array(I.length),T.normals.set(I);else if(C==="POSITION"){if(Ze.HomogeneousCoordinates){T.positions=new Float32Array(I.length-I.length/4);for(let y=0;y<I.length;y+=4)T.positions[y]=I[y],T.positions[y+1]=I[y+1],T.positions[y+2]=I[y+2]}else T.positions=new Float32Array(I.length),T.positions.set(I);o.push(T.positions.length)}else if(C.indexOf("TEXCOORD_")!==-1){const y=Number(C.split("_")[1]),w=A.UVKind+(y===0?"":y+1),G=new Float32Array(I.length);G.set(I),Id(G),T.set(G,w)}else C==="JOINT"?(T.matricesIndices=new Float32Array(I.length),T.matricesIndices.set(I)):C==="WEIGHT"?(T.matricesWeights=new Float32Array(I.length),T.matricesWeights.set(I)):C==="COLOR"&&(T.colors=new Float32Array(I.length),T.colors.set(I));if(b=l.accessors[S.indices],b)I=dt.GetBufferFromAccessor(l,b),T.indices=new Int32Array(I.length),T.indices.set(I),c.push(T.indices.length);else{const C=[];for(let y=0;y<T.positions.length/3;y++)C.push(y);T.indices=new Int32Array(C),c.push(T.indices.length)}n?n.merge(T):n=T;const R=l.scene.getMaterialById(S.material);r.push(R===null?dt.GetDefaultMaterial(l.scene):R),a.push(a.length===0?0:a[a.length-1]+o[o.length-2]),h.push(h.length===0?0:h[h.length-1]+c[c.length-2])}}let u;l.scene._blockEntityCollection=!!l.assetContainer,r.length>1?(u=new Ss("multimat"+i,l.scene),u.subMaterials=r):u=new Y("multimat"+i,l.scene),r.length===1&&(u=r[0]),u._parentContainer=l.assetContainer,s.material||(s.material=u),new Bt(i,l.scene,n,!1,s),s.computeWorldMatrix(!0),l.scene._blockEntityCollection=!1,s.subMeshes=[];let f=0;for(let d=0;d<t.length;d++){const _=t[d],p=l.meshes[_];if(p)for(let m=0;m<p.primitives.length;m++)ci.AddToMesh(f,a[f],o[f],h[f],c[f],s,s,!0),f++}return s},qn=(l,e,t,i)=>{l.position&&(l.position=e),(l.rotationQuaternion||l.rotation)&&(l.rotationQuaternion=t),l.scaling&&(l.scaling=i)},Ld=(l,e)=>{if(e.matrix){const t=new E(0,0,0),i=new K,s=new E(0,0,0);M.FromArray(e.matrix).decompose(s,i,t),qn(l,t,i,s)}else e.translation&&e.rotation&&e.scale&&qn(l,E.FromArray(e.translation),K.FromArray(e.rotation),E.FromArray(e.scale));l.computeWorldMatrix(!0)},Nd=(l,e,t)=>{let i=null;if(l.importOnlyMeshes&&(e.skin||e.meshes)&&l.importMeshesNames&&l.importMeshesNames.length>0&&l.importMeshesNames.indexOf(e.name||"")===-1)return null;if(e.skin){if(e.meshes){const s=l.skins[e.skin],r=$o(l,e,e.meshes,t,e.babylonNode);r.skeleton=l.scene.getLastSkeletonById(e.skin),r.skeleton===null&&(r.skeleton=Dd(l,s,r,s.babylonSkeleton),s.babylonSkeleton||(s.babylonSkeleton=r.skeleton)),i=r}}else if(e.meshes)i=$o(l,e,e.mesh?[e.mesh]:e.meshes,t,e.babylonNode);else if(e.light&&!e.babylonNode&&!l.importOnlyMeshes){const s=l.lights[e.light];if(s){if(s.type==="ambient"){const r=s[s.type],n=new Or(e.light,E.Zero(),l.scene);n.name=e.name||"",r.color&&(n.diffuse=z.FromArray(r.color)),i=n}else if(s.type==="directional"){const r=s[s.type],n=new fi(e.light,E.Zero(),l.scene);n.name=e.name||"",r.color&&(n.diffuse=z.FromArray(r.color)),i=n}else if(s.type==="point"){const r=s[s.type],n=new Dr(e.light,E.Zero(),l.scene);n.name=e.name||"",r.color&&(n.diffuse=z.FromArray(r.color)),i=n}else if(s.type==="spot"){const r=s[s.type],n=new Kt(e.light,E.Zero(),E.Zero(),0,0,l.scene);n.name=e.name||"",r.color&&(n.diffuse=z.FromArray(r.color)),r.fallOfAngle&&(n.angle=r.fallOfAngle),r.fallOffExponent&&(n.exponent=r.fallOffExponent),i=n}}}else if(e.camera&&!e.babylonNode&&!l.importOnlyMeshes){const s=l.cameras[e.camera];if(s){if(l.scene._blockEntityCollection=!!l.assetContainer,s.type==="orthographic"){const r=new Cs(e.camera,E.Zero(),l.scene,!1);r.name=e.name||"",r.mode=ie.ORTHOGRAPHIC_CAMERA,r.attachControl(),i=r,r._parentContainer=l.assetContainer}else if(s.type==="perspective"){const r=s[s.type],n=new Cs(e.camera,E.Zero(),l.scene,!1);n.name=e.name||"",n.attachControl(),r.aspectRatio||(r.aspectRatio=l.scene.getEngine().getRenderWidth()/l.scene.getEngine().getRenderHeight()),r.znear&&r.zfar&&(n.maxZ=r.zfar,n.minZ=r.znear),i=n,n._parentContainer=l.assetContainer}l.scene._blockEntityCollection=!1}}if(!e.jointName){if(e.babylonNode)return e.babylonNode;if(i===null){l.scene._blockEntityCollection=!!l.assetContainer;const s=new ne(e.name||"",l.scene);s._parentContainer=l.assetContainer,l.scene._blockEntityCollection=!1,e.babylonNode=s,i=s}}if(i!==null){if(e.matrix&&i instanceof ne)Ld(i,e);else{const s=e.translation||[0,0,0],r=e.rotation||[0,0,0,1],n=e.scale||[1,1,1];qn(i,E.FromArray(s),K.FromArray(r),E.FromArray(n))}i.updateCache(!0),e.babylonNode=i}return i},Lr=(l,e,t,i=!1)=>{const s=l.nodes[e];let r=null;if(l.importOnlyMeshes&&!i&&l.importMeshesNames?l.importMeshesNames.indexOf(s.name||"")!==-1||l.importMeshesNames.length===0?i=!0:i=!1:i=!0,!s.jointName&&i&&(r=Nd(l,s,e),r!==null&&(r.id=e,r.parent=t)),s.children)for(let n=0;n<s.children.length;n++)Lr(l,s.children[n],r,i)},Jo=l=>{let e=l.currentScene;if(e)for(let t=0;t<e.nodes.length;t++)Lr(l,e.nodes[t],null);else for(const t in l.scenes){e=l.scenes[t];for(let i=0;i<e.nodes.length;i++)Lr(l,e.nodes[i],null)}yd(l);for(let t=0;t<l.scene.skeletons.length;t++){const i=l.scene.skeletons[t];l.scene.beginAnimation(i,0,Number.MAX_VALUE,!0,1)}},Fd=(l,e,t,i,s,r,n)=>{const a=r.values||s.parameters;for(const o in t){const h=t[o],c=h.type;if(c===Yt.FLOAT_MAT2||c===Yt.FLOAT_MAT3||c===Yt.FLOAT_MAT4){if(h.semantic&&!h.source&&!h.node)dt.SetMatrix(e.scene,l,h,o,i.getEffect());else if(h.semantic&&(h.source||h.node)){let u=e.scene.getNodeByName(h.source||h.node||"");if(u===null&&(u=e.scene.getNodeById(h.source||h.node||"")),u===null)continue;dt.SetMatrix(e.scene,u,h,o,i.getEffect())}}else{const u=a[s.uniforms[o]];if(!u)continue;if(c===Yt.SAMPLER_2D){const f=e.textures[r.values?u:h.value].babylonTexture;if(f==null)continue;i.getEffect().setTexture(o,f)}else dt.SetUniform(i.getEffect(),o,u,c)}}n(i)},wd=(l,e,t,i,s)=>{const r=i.values||t.parameters,n=t.uniforms;for(const a in s){const o=s[a],h=o.type;let c=r[n[a]];if(c===void 0&&(c=o.value),!c)continue;const u=f=>d=>{o.value&&f&&(e.setTexture(f,d),delete s[f])};h===Yt.SAMPLER_2D?yt.LoadTextureAsync(l,i.values?c:o.value,u(a),()=>u(null)):o.value&&dt.SetUniform(e,a,i.values?c:o.value,h)&&delete s[a]}},Bd=(l,e,t)=>(i,s)=>{e.dispose(!0),t("Cannot compile program named "+l.name+". Error: "+s+". Default material will be applied")},Ud=(l,e,t,i,s,r)=>n=>{wd(l,e,t,i,s),e.onBind=a=>{Fd(a,l,s,e,t,i,r)}},el=(l,e,t)=>{for(const i in e.uniforms){const s=e.uniforms[i],r=e.parameters[s];if(l.currentIdentifier===i&&r.semantic&&!r.source&&!r.node){const n=jo.indexOf(r.semantic);if(n!==-1)return delete t[i],qo[n]}}return l.currentIdentifier},tl=l=>{for(const e in l.materials)yt.LoadMaterialAsync(l,e,()=>{},()=>{})};class Vi{static CreateRuntime(e,t,i){const s={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:i,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&kt(e.extensions,"extensions",s),e.extensionsUsed&&kt(e.extensionsUsed,"extensionsUsed",s),e.buffers&&Cd(e.buffers,s),e.bufferViews&&kt(e.bufferViews,"bufferViews",s),e.accessors&&kt(e.accessors,"accessors",s),e.meshes&&kt(e.meshes,"meshes",s),e.lights&&kt(e.lights,"lights",s),e.cameras&&kt(e.cameras,"cameras",s),e.nodes&&kt(e.nodes,"nodes",s),e.images&&kt(e.images,"images",s),e.textures&&kt(e.textures,"textures",s),e.shaders&&bd(e.shaders,s),e.programs&&kt(e.programs,"programs",s),e.samplers&&kt(e.samplers,"samplers",s),e.techniques&&kt(e.techniques,"techniques",s),e.materials&&kt(e.materials,"materials",s),e.animations&&kt(e.animations,"animations",s),e.skins&&kt(e.skins,"skins",s),e.scenes&&(s.scenes=e.scenes),e.scene&&e.scenes&&(s.currentScene=e.scenes[e.scene]),s}static LoadBufferAsync(e,t,i,s,r){const n=e.buffers[t];k.IsBase64(n.uri)?setTimeout(()=>i(new Uint8Array(k.DecodeBase64(n.uri)))):k.LoadFile(e.rootUrl+n.uri,a=>i(new Uint8Array(a)),r,void 0,!0,a=>{a&&s(a.status+" "+a.statusText)})}static LoadTextureBufferAsync(e,t,i,s){const r=e.textures[t];if(!r||!r.source){s("");return}if(r.babylonTexture){i(null);return}const n=e.images[r.source];k.IsBase64(n.uri)?setTimeout(()=>i(new Uint8Array(k.DecodeBase64(n.uri)))):k.LoadFile(e.rootUrl+n.uri,a=>i(new Uint8Array(a)),void 0,void 0,!0,a=>{a&&s(a.status+" "+a.statusText)})}static CreateTextureAsync(e,t,i,s){const r=e.textures[t];if(r.babylonTexture){s(r.babylonTexture);return}const n=e.samplers[r.sampler],a=n.minFilter===Ei.NEAREST_MIPMAP_NEAREST||n.minFilter===Ei.NEAREST_MIPMAP_LINEAR||n.minFilter===Ei.LINEAR_MIPMAP_NEAREST||n.minFilter===Ei.LINEAR_MIPMAP_LINEAR,o=O.BILINEAR_SAMPLINGMODE,h=i==null?new Blob:new Blob([i]),c=URL.createObjectURL(h),u=()=>URL.revokeObjectURL(c),f=new O(c,e.scene,!a,!0,o,u,u);n.wrapS!==void 0&&(f.wrapU=dt.GetWrapMode(n.wrapS)),n.wrapT!==void 0&&(f.wrapV=dt.GetWrapMode(n.wrapT)),f.name=t,r.babylonTexture=f,s(f)}static LoadShaderStringAsync(e,t,i,s){const r=e.shaders[t];if(k.IsBase64(r.uri)){const n=atob(r.uri.split(",")[1]);i&&i(n)}else k.LoadFile(e.rootUrl+r.uri,i,void 0,void 0,!1,n=>{n&&s&&s(n.status+" "+n.statusText)})}static LoadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r.technique){s&&s("No technique found.");return}const n=e.techniques[r.technique];if(!n){e.scene._blockEntityCollection=!!e.assetContainer;const R=new Y(t,e.scene);R._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,R.diffuseColor=new z(.5,.5,.5),R.sideOrientation=V.CounterClockWiseSideOrientation,i(R);return}const a=e.programs[n.program],o=n.states,h=nt.ShadersStore[a.vertexShader+"VertexShader"],c=nt.ShadersStore[a.fragmentShader+"PixelShader"];let u="",f="";const d=new Ko(h),_=new Ko(c),p={},m=[],T=[],S=[];for(const R in n.uniforms){const C=n.uniforms[R],y=n.parameters[C];if(p[R]=y,y.semantic&&!y.node&&!y.source){const w=jo.indexOf(y.semantic);w!==-1?(m.push(qo[w]),delete p[R]):m.push(R)}else y.type===Yt.SAMPLER_2D?S.push(R):m.push(R)}for(const R in n.attributes){const C=n.attributes[R],y=n.parameters[C];if(y.semantic){const w=Zo(y);w&&T.push(w)}}for(;!d.isEnd()&&d.getNextToken();){if(d.currentToken!==hs.IDENTIFIER){u+=d.currentString;continue}let C=!1;for(const y in n.attributes){const w=n.attributes[y],G=n.parameters[w];if(d.currentIdentifier===y&&G.semantic){u+=Zo(G),C=!0;break}}C||(u+=el(d,n,p))}for(;!_.isEnd()&&_.getNextToken();){if(_.currentToken!==hs.IDENTIFIER){f+=_.currentString;continue}f+=el(_,n,p)}const x={vertex:a.vertexShader+t,fragment:a.fragmentShader+t},b={attributes:T,uniforms:m,samplers:S,needAlphaBlending:o&&o.enable&&o.enable.indexOf(3042)!==-1};nt.ShadersStore[a.vertexShader+t+"VertexShader"]=u,nt.ShadersStore[a.fragmentShader+t+"PixelShader"]=f;const I=new vi(t,e.scene,x,b);if(I.onError=Bd(a,I,s),I.onCompiled=Ud(e,I,n,r,p,i),I.sideOrientation=V.CounterClockWiseSideOrientation,o&&o.functions){const R=o.functions;R.cullFace&&R.cullFace[0]!==Wn.BACK&&(I.backFaceCulling=!1);const C=R.blendFuncSeparate;C&&(C[0]===st.SRC_ALPHA&&C[1]===st.ONE_MINUS_SRC_ALPHA&&C[2]===st.ONE&&C[3]===st.ONE?I.alphaMode=P.ALPHA_COMBINE:C[0]===st.ONE&&C[1]===st.ONE&&C[2]===st.ZERO&&C[3]===st.ONE?I.alphaMode=P.ALPHA_ONEONE:C[0]===st.SRC_ALPHA&&C[1]===st.ONE&&C[2]===st.ZERO&&C[3]===st.ONE?I.alphaMode=P.ALPHA_ADD:C[0]===st.ZERO&&C[1]===st.ONE_MINUS_SRC_COLOR&&C[2]===st.ONE&&C[3]===st.ONE?I.alphaMode=P.ALPHA_SUBTRACT:C[0]===st.DST_COLOR&&C[1]===st.ZERO&&C[2]===st.ONE&&C[3]===st.ONE?I.alphaMode=P.ALPHA_MULTIPLY:C[0]===st.SRC_ALPHA&&C[1]===st.ONE_MINUS_SRC_COLOR&&C[2]===st.ONE&&C[3]===st.ONE&&(I.alphaMode=P.ALPHA_MAXIMIZED))}}}let Zs=class Ka{static RegisterExtension(e){if(Ka.Extensions[e.name]){k.Error('Tool with the same name "'+e.name+'" already exists');return}Ka.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,s,r,n,a,o){return t.useRightHandedSystem=!0,yt.LoadRuntimeAsync(t,i,s,h=>{h.assetContainer=r,h.importOnlyMeshes=!0,e===""?h.importMeshesNames=[]:typeof e=="string"?h.importMeshesNames=[e]:e&&!(e instanceof Array)?h.importMeshesNames=[e]:(h.importMeshesNames=[],k.Warn("Argument meshesNames must be of type string or string[]")),this._createNodes(h);const c=new Array,u=new Array;for(const f in h.nodes){const d=h.nodes[f];d.babylonNode instanceof Vt&&c.push(d.babylonNode)}for(const f in h.skins){const d=h.skins[f];d.babylonSkeleton instanceof qs&&u.push(d.babylonSkeleton)}this._loadBuffersAsync(h,()=>{this._loadShadersAsync(h,()=>{tl(h),Jo(h),!Ze.IncrementalLoading&&n&&n(c,u)})}),Ze.IncrementalLoading&&n&&n(c,u)},o),!0}importMeshAsync(e,t,i,s,r,n){return new Promise((a,o)=>{this._importMeshAsync(e,t,s,r,i,(h,c)=>{a({meshes:h,particleSystems:[],skeletons:c,animationGroups:[],lights:[],transformNodes:[],geometries:[]})},n,h=>{o(new Error(h))})})}_loadAsync(e,t,i,s,r,n){e.useRightHandedSystem=!0,yt.LoadRuntimeAsync(e,t,i,a=>{yt.LoadRuntimeExtensionsAsync(a,()=>{this._createNodes(a),this._loadBuffersAsync(a,()=>{this._loadShadersAsync(a,()=>{tl(a),Jo(a),Ze.IncrementalLoading||s()})}),Ze.IncrementalLoading&&s()},n)},n)}loadAsync(e,t,i,s){return new Promise((r,n)=>{this._loadAsync(e,t,i,()=>{r()},s,a=>{n(new Error(a))})})}_loadShadersAsync(e,t){let i=!1;const s=(r,n)=>{yt.LoadShaderStringAsync(e,r,a=>{a instanceof ArrayBuffer||(e.loadedShaderCount++,a&&(nt.ShadersStore[r+(n.type===Hn.VERTEX?"VertexShader":"PixelShader")]=a),e.loadedShaderCount===e.shaderscount&&t())},()=>{k.Error("Error when loading shader program named "+r+" located at "+n.uri)})};for(const r in e.shaders){i=!0;const n=e.shaders[r];n?s.bind(this,r,n)():k.Error("No shader named: "+r)}i||t()}_loadBuffersAsync(e,t){let i=!1;const s=(r,n)=>{yt.LoadBufferAsync(e,r,a=>{e.loadedBufferCount++,a&&(a.byteLength!=e.buffers[r].byteLength&&k.Error("Buffer named "+r+" is length "+a.byteLength+". Expected: "+n.byteLength),e.loadedBufferViews[r]=a),e.loadedBufferCount===e.buffersCount&&t()},()=>{k.Error("Error when loading buffer named "+r+" located at "+n.uri)})};for(const r in e.buffers){i=!0;const n=e.buffers[r];n?s.bind(this,r,n)():k.Error("No buffer named: "+r)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;i<t.nodes.length;i++)Lr(e,t.nodes[i],null);else for(const i in e.scenes){t=e.scenes[i];for(let s=0;s<t.nodes.length;s++)Lr(e,t.nodes[s],null)}}};Zs.Extensions={};class yt{constructor(e){this._name=e}get name(){return this._name}loadRuntimeAsync(e,t,i,s,r){return!1}loadRuntimeExtensionsAsync(e,t,i){return!1}loadBufferAsync(e,t,i,s,r){return!1}loadTextureBufferAsync(e,t,i,s){return!1}createTextureAsync(e,t,i,s,r){return!1}loadShaderStringAsync(e,t,i,s){return!1}loadMaterialAsync(e,t,i,s){return!1}static LoadRuntimeAsync(e,t,i,s,r){yt._ApplyExtensions(n=>n.loadRuntimeAsync(e,t,i,s,r),()=>{setTimeout(()=>{s&&s(Vi.CreateRuntime(t.json,e,i))})})}static LoadRuntimeExtensionsAsync(e,t,i){yt._ApplyExtensions(s=>s.loadRuntimeExtensionsAsync(e,t,i),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,i,s,r){yt._ApplyExtensions(n=>n.loadBufferAsync(e,t,i,s,r),()=>{Vi.LoadBufferAsync(e,t,i,s,r)})}static LoadTextureAsync(e,t,i,s){yt._LoadTextureBufferAsync(e,t,r=>{r&&yt._CreateTextureAsync(e,t,r,i,s)},s)}static LoadShaderStringAsync(e,t,i,s){yt._ApplyExtensions(r=>r.loadShaderStringAsync(e,t,i,s),()=>{Vi.LoadShaderStringAsync(e,t,i,s)})}static LoadMaterialAsync(e,t,i,s){yt._ApplyExtensions(r=>r.loadMaterialAsync(e,t,i,s),()=>{Vi.LoadMaterialAsync(e,t,i,s)})}static _LoadTextureBufferAsync(e,t,i,s){yt._ApplyExtensions(r=>r.loadTextureBufferAsync(e,t,i,s),()=>{Vi.LoadTextureBufferAsync(e,t,i,s)})}static _CreateTextureAsync(e,t,i,s,r){yt._ApplyExtensions(n=>n.createTextureAsync(e,t,i,s,r),()=>{Vi.CreateTextureAsync(e,t,i,s)})}static _ApplyExtensions(e,t){for(const i in Zs.Extensions){const s=Zs.Extensions[i];if(e(s))return}t()}}Ze._CreateGLTF1Loader=()=>new Zs;const Vd="binary_glTF";class kd extends yt{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,s){const r=t.json.extensionsUsed;return!r||r.indexOf(this.name)===-1||!t.bin?!1:(this._bin=t.bin,s(Vi.CreateRuntime(t.json,e,i)),!0)}loadBufferAsync(e,t,i,s){return e.extensionsUsed.indexOf(this.name)===-1||t!==Vd?!1:(this._bin.readAsync(0,this._bin.byteLength).then(i,r=>s(r.message)),!0)}loadTextureBufferAsync(e,t,i){const s=e.textures[t],r=e.images[s.source];if(!r.extensions||!(this.name in r.extensions))return!1;const n=r.extensions[this.name],a=e.bufferViews[n.bufferView],o=dt.GetBufferFromBufferView(e,a,0,a.byteLength,as.UNSIGNED_BYTE);return i(o),!0}loadShaderStringAsync(e,t,i){const s=e.shaders[t];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],n=e.bufferViews[r.bufferView],a=dt.GetBufferFromBufferView(e,n,0,n.byteLength,as.UNSIGNED_BYTE);return setTimeout(()=>{const o=dt.DecodeBufferToText(a);i(o)}),!0}}Zs.RegisterExtension(new kd);class Gd extends yt{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const t=e.extensions[this.name];if(!t)return!1;const i=t.lights;if(i)for(const s in i){const r=i[s];switch(r.type){case"ambient":{const n=new Or(r.name,new E(0,1,0),e.scene),a=r.ambient;a&&(n.diffuse=z.FromArray(a.color||[1,1,1]));break}case"point":{const n=new Dr(r.name,new E(10,10,10),e.scene),a=r.point;a&&(n.diffuse=z.FromArray(a.color||[1,1,1]));break}case"directional":{const n=new fi(r.name,new E(0,-1,0),e.scene),a=r.directional;a&&(n.diffuse=z.FromArray(a.color||[1,1,1]));break}case"spot":{const n=r.spot;if(n){const a=new Kt(r.name,new E(0,10,0),new E(0,-1,0),n.fallOffAngle||Math.PI,n.fallOffExponent||0,e.scene);a.diffuse=z.FromArray(n.color||[1,1,1])}break}default:k.Warn('GLTF Material Common extension: light type "'+r.type+"” not supported");break}}return!1}loadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r||!r.extensions)return!1;const n=r.extensions[this.name];if(!n)return!1;const a=new Y(t,e.scene);return a.sideOrientation=V.CounterClockWiseSideOrientation,n.technique==="CONSTANT"&&(a.disableLighting=!0),a.backFaceCulling=n.doubleSided===void 0?!1:!n.doubleSided,a.alpha=n.values.transparency===void 0?1:n.values.transparency,a.specularPower=n.values.shininess===void 0?0:n.values.shininess,typeof n.values.ambient=="string"?this._loadTexture(e,n.values.ambient,a,"ambientTexture",s):a.ambientColor=z.FromArray(n.values.ambient||[0,0,0]),typeof n.values.diffuse=="string"?this._loadTexture(e,n.values.diffuse,a,"diffuseTexture",s):a.diffuseColor=z.FromArray(n.values.diffuse||[0,0,0]),typeof n.values.emission=="string"?this._loadTexture(e,n.values.emission,a,"emissiveTexture",s):a.emissiveColor=z.FromArray(n.values.emission||[0,0,0]),typeof n.values.specular=="string"?this._loadTexture(e,n.values.specular,a,"specularTexture",s):a.specularColor=z.FromArray(n.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,s,r){Vi.LoadTextureBufferAsync(e,t,n=>{Vi.CreateTextureAsync(e,t,n,a=>i[s]=a)},r)}}Zs.RegisterExtension(new Gd);class Nr{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}class Hd{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class Fr{get from(){return this._from}get to(){return this._to}get isStarted(){return this._isStarted}get isPlaying(){return this._isStarted&&!this._isPaused}get speedRatio(){return this._speedRatio}set speedRatio(e){if(this._speedRatio!==e){this._speedRatio=e;for(let t=0;t<this._animatables.length;t++){const i=this._animatables[t];i.speedRatio=this._speedRatio}}}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){if(this._loopAnimation!==e){this._loopAnimation=e;for(let t=0;t<this._animatables.length;t++){const i=this._animatables[t];i.loopAnimation=this._loopAnimation}}}get isAdditive(){return this._isAdditive}set isAdditive(e){if(this._isAdditive!==e){this._isAdditive=e;for(let t=0;t<this._animatables.length;t++){const i=this._animatables[t];i.isAdditive=this._isAdditive}}}get weight(){return this._weight}set weight(e){this._weight!==e&&(this._weight=e,this.setWeightForAllAnimatables(this._weight))}get targetedAnimations(){return this._targetedAnimations}get animatables(){return this._animatables}get children(){return this._targetedAnimations}get playOrder(){return this._playOrder}set playOrder(e){if(this._playOrder!==e&&(this._playOrder=e,this._animatables.length>0)){for(let t=0;t<this._animatables.length;t++)this._animatables[t].playOrder=this._playOrder;this._scene.sortActiveAnimatables()}}enableBlending(e){for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.enableBlending=!0,this._targetedAnimations[t].animation.blendingSpeed=e}disableBlending(){for(let e=0;e<this._targetedAnimations.length;++e)this._targetedAnimations[e].animation.enableBlending=!1}static MergeAnimationGroups(e,t=!0,i=!1,s){if(e.length===0)return null;s=s??e[0].weight;let r=Number.MAX_VALUE,n=Number.MIN_VALUE;if(i)for(const o of e)o.from<r&&(r=o.from),o.to>n&&(n=o.to);const a=new Fr(e[0].name+"_merged",e[0]._scene,s);for(const o of e){i&&o.normalize(r,n);for(const h of o.targetedAnimations)a.addTargetedAnimation(h.animation,h.target);t&&o.dispose()}return a}constructor(e,t=null,i=-1,s=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._parentContainer=null,this.onAnimationEndObservable=new B,this.onAnimationLoopObservable=new B,this.onAnimationGroupLoopObservable=new B,this.onAnimationGroupEndObservable=new B,this.onAnimationGroupPauseObservable=new B,this.onAnimationGroupPlayObservable=new B,this.metadata=null,this._animationLoopFlags=[],this._scene=t||Ee.LastCreatedScene,this._weight=i,this._playOrder=s,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new Hd;i.animation=e,i.target=t;const s=e.getKeys();return this._from>s[0].frame&&(this._from=s[0].frame),this._to<s[s.length-1].frame&&(this._to=s[s.length-1].frame),this._targetedAnimations.push(i),i}removeTargetedAnimation(e){for(let t=this._targetedAnimations.length-1;t>-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){e==null&&(e=this._from),t==null&&(t=this._to);for(let i=0;i<this._targetedAnimations.length;i++){const r=this._targetedAnimations[i].animation.getKeys(),n=r[0],a=r[r.length-1];if(n.frame>e){const o={frame:e,value:n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation};r.splice(0,0,o)}if(a.frame<t){const o={frame:t,value:a.value,inTangent:a.inTangent,outTangent:a.outTangent,interpolation:a.interpolation};r.push(o)}}return this._from=e,this._to=t,this}_processLoop(e,t,i){e.onAnimationLoop=()=>{this.onAnimationLoopObservable.notifyObservers(t),!this._animationLoopFlags[i]&&(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._targetedAnimations.length&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,s,r){if(this._isStarted||this._targetedAnimations.length===0)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n<this._targetedAnimations.length;n++){const a=this._targetedAnimations[n],o=this._scene.beginDirectAnimation(a.target,[a.animation],i!==void 0?i:this._from,s!==void 0?s:this._to,e,t,void 0,void 0,r!==void 0?r:this._isAdditive);o.weight=this._weight,o.playOrder=this._playOrder,o.onAnimationEnd=()=>{this.onAnimationEndObservable.notifyObservers(a),this._checkAnimationGroupEnded(o)},this._processLoop(o,a,n),this._animatables.push(o)}return this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e<this._animatables.length;e++)this._animatables[e].pause();return this.onAnimationGroupPauseObservable.notifyObservers(this),this}play(e){return this.isStarted&&this._animatables.length===this._targetedAnimations.length?(e!==void 0&&(this.loopAnimation=e),this.restart()):(this.stop(),this.start(e,this._speedRatio)),this._isPaused=!1,this}reset(){if(!this._isStarted)return this.play(),this.goToFrame(0),this.stop(),this;for(let e=0;e<this._animatables.length;e++)this._animatables[e].reset();return this}restart(){if(!this._isStarted)return this;for(let e=0;e<this._animatables.length;e++)this._animatables[e].restart();return this.onAnimationGroupPlayObservable.notifyObservers(this),this}stop(){if(!this._isStarted)return this;const e=this._animatables.slice();for(let i=0;i<e.length;i++)e[i].stop(void 0,void 0,!0);let t=0;for(let i=0;i<this._scene._activeAnimatables.length;i++){const s=this._scene._activeAnimatables[i];s._runtimeAnimations.length>0&&(this._scene._activeAnimatables[t++]=s)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t<this._animatables.length;t++){const i=this._animatables[t];i.weight=e}return this}syncAllAnimationsWith(e){for(let t=0;t<this._animatables.length;t++)this._animatables[t].syncWith(e);return this}goToFrame(e){if(!this._isStarted)return this;for(let t=0;t<this._animatables.length;t++)this._animatables[t].goToFrame(e);return this}dispose(){this._targetedAnimations.length=0,this._animatables.length=0;const e=this._scene.animationGroups.indexOf(this);if(e>-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const t=this._parentContainer.animationGroups.indexOf(this);t>-1&&this._parentContainer.animationGroups.splice(t,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e){const t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),this._animatables.length===0&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const s=new Fr(e||this.name,this._scene);for(const r of this._targetedAnimations)s.addTargetedAnimation(i?r.animation.clone():r.animation,t?t(r.target):r.target);return s}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.targetedAnimations=[];for(let t=0;t<this.targetedAnimations.length;t++){const i=this.targetedAnimations[t];e.targetedAnimations[t]=i.serialize()}return xe&&xe.HasTags(this)&&(e.tags=xe.GetTags(this)),this.metadata&&(e.metadata=this.metadata),e}static Parse(e,t){const i=new Fr(e.name,t);for(let s=0;s<e.targetedAnimations.length;s++){const r=e.targetedAnimations[s],n=N.Parse(r.animation),a=r.targetId;if(r.animation.property==="influence"){const o=t.getMorphTargetById(a);o&&i.addTargetedAnimation(n,o)}else{const o=t.getNodeById(a);o!=null&&i.addTargetedAnimation(n,o)}}return e.from!==null&&e.to!==null&&i.normalize(e.from,e.to),xe&&xe.AddTagsTo(i,e.tags),e.metadata!==void 0&&(i.metadata=e.metadata),i}static MakeAnimationAdditive(e,t=0,i,s=!1,r){let n=e;s&&(n=e.clone(r||n.name));const a=n.targetedAnimations;for(let o=0;o<a.length;o++){const h=a[o];N.MakeAnimationAdditive(h.animation,t,i)}return n.isAdditive=!0,n}getClassName(){return"AnimationGroup"}toString(e){let t="Name: "+this.name;return t+=", type: "+this.getClassName(),e&&(t+=", from: "+this._from,t+=", to: "+this._to,t+=", isStarted: "+this._isStarted,t+=", speedRatio: "+this._speedRatio,t+=", targetedAnimations length: "+this._targetedAnimations.length,t+=", animatables length: "+this._animatables),t}}const Wd="rgbdDecodePixelShader",zd=`varying vec2 vUV;
3569
+ `);const t={vertex:"GLTFDefaultMaterial",fragment:"GLTFDefaultMaterial"},i={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};dt._DefaultMaterial=new vi("GLTFDefaultMaterial",e,t,i),dt._DefaultMaterial.setColor4("u_emission",new ge(.5,.5,.5,1))}return dt._DefaultMaterial}}dt._DefaultMaterial=null;class P{}P.ALPHA_DISABLE=0,P.ALPHA_ADD=1,P.ALPHA_COMBINE=2,P.ALPHA_SUBTRACT=3,P.ALPHA_MULTIPLY=4,P.ALPHA_MAXIMIZED=5,P.ALPHA_ONEONE=6,P.ALPHA_PREMULTIPLIED=7,P.ALPHA_PREMULTIPLIED_PORTERDUFF=8,P.ALPHA_INTERPOLATE=9,P.ALPHA_SCREENMODE=10,P.ALPHA_ONEONE_ONEONE=11,P.ALPHA_ALPHATOCOLOR=12,P.ALPHA_REVERSEONEMINUS=13,P.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,P.ALPHA_ONEONE_ONEZERO=15,P.ALPHA_EXCLUSION=16,P.ALPHA_LAYER_ACCUMULATE=17,P.ALPHA_EQUATION_ADD=0,P.ALPHA_EQUATION_SUBSTRACT=1,P.ALPHA_EQUATION_REVERSE_SUBTRACT=2,P.ALPHA_EQUATION_MAX=3,P.ALPHA_EQUATION_MIN=4,P.ALPHA_EQUATION_DARKEN=5,P.DELAYLOADSTATE_NONE=0,P.DELAYLOADSTATE_LOADED=1,P.DELAYLOADSTATE_LOADING=2,P.DELAYLOADSTATE_NOTLOADED=4,P.NEVER=512,P.ALWAYS=519,P.LESS=513,P.EQUAL=514,P.LEQUAL=515,P.GREATER=516,P.GEQUAL=518,P.NOTEQUAL=517,P.KEEP=7680,P.ZERO=0,P.REPLACE=7681,P.INCR=7682,P.DECR=7683,P.INVERT=5386,P.INCR_WRAP=34055,P.DECR_WRAP=34056,P.TEXTURE_CLAMP_ADDRESSMODE=0,P.TEXTURE_WRAP_ADDRESSMODE=1,P.TEXTURE_MIRROR_ADDRESSMODE=2,P.TEXTURE_CREATIONFLAG_STORAGE=1,P.TEXTUREFORMAT_ALPHA=0,P.TEXTUREFORMAT_LUMINANCE=1,P.TEXTUREFORMAT_LUMINANCE_ALPHA=2,P.TEXTUREFORMAT_RGB=4,P.TEXTUREFORMAT_RGBA=5,P.TEXTUREFORMAT_RED=6,P.TEXTUREFORMAT_R=6,P.TEXTUREFORMAT_RG=7,P.TEXTUREFORMAT_RED_INTEGER=8,P.TEXTUREFORMAT_R_INTEGER=8,P.TEXTUREFORMAT_RG_INTEGER=9,P.TEXTUREFORMAT_RGB_INTEGER=10,P.TEXTUREFORMAT_RGBA_INTEGER=11,P.TEXTUREFORMAT_BGRA=12,P.TEXTUREFORMAT_DEPTH24_STENCIL8=13,P.TEXTUREFORMAT_DEPTH32_FLOAT=14,P.TEXTUREFORMAT_DEPTH16=15,P.TEXTUREFORMAT_DEPTH24=16,P.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,P.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,P.TEXTUREFORMAT_STENCIL8=19,P.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,P.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,P.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,P.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,P.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,P.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,P.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,P.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,P.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,P.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,P.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,P.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,P.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,P.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,P.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,P.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,P.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,P.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,P.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,P.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,P.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,P.TEXTURETYPE_UNSIGNED_BYTE=0,P.TEXTURETYPE_UNSIGNED_INT=0,P.TEXTURETYPE_FLOAT=1,P.TEXTURETYPE_HALF_FLOAT=2,P.TEXTURETYPE_BYTE=3,P.TEXTURETYPE_SHORT=4,P.TEXTURETYPE_UNSIGNED_SHORT=5,P.TEXTURETYPE_INT=6,P.TEXTURETYPE_UNSIGNED_INTEGER=7,P.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,P.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,P.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,P.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,P.TEXTURETYPE_UNSIGNED_INT_24_8=12,P.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,P.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,P.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,P.TEXTURETYPE_UNDEFINED=16,P.TEXTURE_2D=3553,P.TEXTURE_2D_ARRAY=35866,P.TEXTURE_CUBE_MAP=34067,P.TEXTURE_CUBE_MAP_ARRAY=3735928559,P.TEXTURE_3D=32879,P.TEXTURE_NEAREST_SAMPLINGMODE=1,P.TEXTURE_NEAREST_NEAREST=1,P.TEXTURE_BILINEAR_SAMPLINGMODE=2,P.TEXTURE_LINEAR_LINEAR=2,P.TEXTURE_TRILINEAR_SAMPLINGMODE=3,P.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,P.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,P.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,P.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,P.TEXTURE_NEAREST_LINEAR=7,P.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,P.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,P.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,P.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,P.TEXTURE_LINEAR_NEAREST=12,P.TEXTURE_EXPLICIT_MODE=0,P.TEXTURE_SPHERICAL_MODE=1,P.TEXTURE_PLANAR_MODE=2,P.TEXTURE_CUBIC_MODE=3,P.TEXTURE_PROJECTION_MODE=4,P.TEXTURE_SKYBOX_MODE=5,P.TEXTURE_INVCUBIC_MODE=6,P.TEXTURE_EQUIRECTANGULAR_MODE=7,P.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,P.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,P.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,P.TEXTURE_FILTERING_QUALITY_HIGH=64,P.TEXTURE_FILTERING_QUALITY_MEDIUM=16,P.TEXTURE_FILTERING_QUALITY_LOW=8,P.SCALEMODE_FLOOR=1,P.SCALEMODE_NEAREST=2,P.SCALEMODE_CEILING=3,P.MATERIAL_TextureDirtyFlag=1,P.MATERIAL_LightDirtyFlag=2,P.MATERIAL_FresnelDirtyFlag=4,P.MATERIAL_AttributesDirtyFlag=8,P.MATERIAL_MiscDirtyFlag=16,P.MATERIAL_PrePassDirtyFlag=32,P.MATERIAL_AllDirtyFlag=63,P.MATERIAL_TriangleFillMode=0,P.MATERIAL_WireFrameFillMode=1,P.MATERIAL_PointFillMode=2,P.MATERIAL_PointListDrawMode=3,P.MATERIAL_LineListDrawMode=4,P.MATERIAL_LineLoopDrawMode=5,P.MATERIAL_LineStripDrawMode=6,P.MATERIAL_TriangleStripDrawMode=7,P.MATERIAL_TriangleFanDrawMode=8,P.MATERIAL_ClockWiseSideOrientation=0,P.MATERIAL_CounterClockWiseSideOrientation=1,P.ACTION_NothingTrigger=0,P.ACTION_OnPickTrigger=1,P.ACTION_OnLeftPickTrigger=2,P.ACTION_OnRightPickTrigger=3,P.ACTION_OnCenterPickTrigger=4,P.ACTION_OnPickDownTrigger=5,P.ACTION_OnDoublePickTrigger=6,P.ACTION_OnPickUpTrigger=7,P.ACTION_OnPickOutTrigger=16,P.ACTION_OnLongPressTrigger=8,P.ACTION_OnPointerOverTrigger=9,P.ACTION_OnPointerOutTrigger=10,P.ACTION_OnEveryFrameTrigger=11,P.ACTION_OnIntersectionEnterTrigger=12,P.ACTION_OnIntersectionExitTrigger=13,P.ACTION_OnKeyDownTrigger=14,P.ACTION_OnKeyUpTrigger=15,P.PARTICLES_BILLBOARDMODE_Y=2,P.PARTICLES_BILLBOARDMODE_ALL=7,P.PARTICLES_BILLBOARDMODE_STRETCHED=8,P.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,P.MESHES_CULLINGSTRATEGY_STANDARD=0,P.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,P.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,P.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,P.SCENELOADER_NO_LOGGING=0,P.SCENELOADER_MINIMAL_LOGGING=1,P.SCENELOADER_SUMMARY_LOGGING=2,P.SCENELOADER_DETAILED_LOGGING=3,P.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,P.PREPASS_POSITION_TEXTURE_TYPE=1,P.PREPASS_VELOCITY_TEXTURE_TYPE=2,P.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,P.PREPASS_COLOR_TEXTURE_TYPE=4,P.PREPASS_DEPTH_TEXTURE_TYPE=5,P.PREPASS_NORMAL_TEXTURE_TYPE=6,P.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,P.BUFFER_CREATIONFLAG_READ=1,P.BUFFER_CREATIONFLAG_WRITE=2,P.BUFFER_CREATIONFLAG_READWRITE=3,P.BUFFER_CREATIONFLAG_UNIFORM=4,P.BUFFER_CREATIONFLAG_VERTEX=8,P.BUFFER_CREATIONFLAG_INDEX=16,P.BUFFER_CREATIONFLAG_STORAGE=32,P.RENDERPASS_MAIN=0,P.INPUT_ALT_KEY=18,P.INPUT_CTRL_KEY=17,P.INPUT_META_KEY1=91,P.INPUT_META_KEY2=92,P.INPUT_META_KEY3=93,P.INPUT_SHIFT_KEY=16,P.SNAPSHOTRENDERING_STANDARD=0,P.SNAPSHOTRENDERING_FAST=1,P.PERSPECTIVE_CAMERA=0,P.ORTHOGRAPHIC_CAMERA=1,P.FOVMODE_VERTICAL_FIXED=0,P.FOVMODE_HORIZONTAL_FIXED=1,P.RIG_MODE_NONE=0,P.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,P.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,P.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,P.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,P.RIG_MODE_STEREOSCOPIC_INTERLACED=14,P.RIG_MODE_VR=20,P.RIG_MODE_WEBVR=21,P.RIG_MODE_CUSTOM=22,P.MAX_SUPPORTED_UV_SETS=6,P.GL_ALPHA_EQUATION_ADD=32774,P.GL_ALPHA_EQUATION_MIN=32775,P.GL_ALPHA_EQUATION_MAX=32776,P.GL_ALPHA_EQUATION_SUBTRACT=32778,P.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,P.GL_ALPHA_FUNCTION_SRC=768,P.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,P.GL_ALPHA_FUNCTION_SRC_ALPHA=770,P.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,P.GL_ALPHA_FUNCTION_DST_ALPHA=772,P.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,P.GL_ALPHA_FUNCTION_DST_COLOR=774,P.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,P.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,P.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,P.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,P.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,P.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,P.SnippetUrl="https://snippet.babylonjs.com";var hs;(function(l){l[l.IDENTIFIER=1]="IDENTIFIER",l[l.UNKNOWN=2]="UNKNOWN",l[l.END_OF_INPUT=3]="END_OF_INPUT"})(hs||(hs={}));class Ko{constructor(e){this._pos=0,this.currentToken=hs.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}getNextToken(){if(this.isEnd())return hs.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=hs.UNKNOWN,this.currentString==="_"||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=hs.IDENTIFIER,this.currentIdentifier=this.currentString;!this.isEnd()&&(this.isLetterOrDigitPattern.test(this.currentString=this.peek())||this.currentString==="_");)this.currentIdentifier+=this.currentString,this.forward();return this.currentToken}peek(){return this._toParse[this._pos]}read(){return this._toParse[this._pos++]}forward(){this._pos++}isEnd(){return this._pos>=this._maxPos}}const jo=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],qo=["world","view","projection","worldView","worldViewProjection","mBones"],Rd=["translation","rotation","scale"],xd=["position","rotationQuaternion","scaling"],Cd=(l,e)=>{for(const t in l){const i=l[t];e.buffers[t]=i,e.buffersCount++}},bd=(l,e)=>{for(const t in l){const i=l[t];e.shaders[t]=i,e.shaderscount++}},kt=(l,e,t)=>{for(const i in l){const s=l[i];t[e][i]=s}},Id=l=>{if(l)for(let e=0;e<l.length/2;e++)l[e*2+1]=1-l[e*2+1]},Zo=l=>{if(l.semantic==="NORMAL")return"normal";if(l.semantic==="POSITION")return"position";if(l.semantic==="JOINT")return"matricesIndices";if(l.semantic==="WEIGHT")return"matricesWeights";if(l.semantic==="COLOR")return"color";if(l.semantic&&l.semantic.indexOf("TEXCOORD_")!==-1){const e=Number(l.semantic.split("_")[1]);return"uv"+(e===0?"":e+1)}return null},yd=l=>{for(const e in l.animations){const t=l.animations[e];if(!t.channels||!t.samplers)continue;let i=null;for(let s=0;s<t.channels.length;s++){const r=t.channels[s],n=t.samplers[r.sampler];if(!n)continue;let a=null,o=null;t.parameters?(a=t.parameters[n.input],o=t.parameters[n.output]):(a=n.input,o=n.output);const h=dt.GetBufferFromAccessor(l,l.accessors[a]),c=dt.GetBufferFromAccessor(l,l.accessors[o]),u=r.target.id;let f=l.scene.getNodeById(u);if(f===null&&(f=l.scene.getNodeByName(u)),f===null){k.Warn("Creating animation named "+e+". But cannot find node named "+u+" to attach to");continue}const d=f instanceof Ue;let _=r.target.path;const p=Rd.indexOf(_);p!==-1&&(_=xd[p]);let m=N.ANIMATIONTYPE_MATRIX;d||(_==="rotationQuaternion"?(m=N.ANIMATIONTYPE_QUATERNION,f.rotationQuaternion=new K):m=N.ANIMATIONTYPE_VECTOR3);let T=null;const S=[];let x=0,b=!1;d&&i&&i.getKeys().length===h.length&&(T=i,b=!0),b||(l.scene._blockEntityCollection=!!l.assetContainer,T=new N(e,d?"_matrix":_,1,m,N.ANIMATIONLOOPMODE_CYCLE),l.scene._blockEntityCollection=!1);for(let I=0;I<h.length;I++){let R=null;if(_==="rotationQuaternion"?(R=K.FromArray([c[x],c[x+1],c[x+2],c[x+3]]),x+=4):(R=E.FromArray([c[x],c[x+1],c[x+2]]),x+=3),d){const C=f;let y=E.Zero(),w=new K,G=E.Zero(),te=C.getBaseMatrix();b&&i&&(te=i.getKeys()[I].value),te.decompose(G,w,y),_==="position"?y=R:_==="rotationQuaternion"?w=R:G=R,R=M.Compose(G,w,y)}b?i&&(i.getKeys()[I].value=R):S.push({frame:h[I],value:R})}!b&&T&&(T.setKeys(S),f.animations.push(T)),i=T,l.scene.stopAnimation(f),l.scene.beginAnimation(f,0,h[h.length-1],!0,1)}}},Kn=l=>{let e=null;if(l.translation||l.rotation||l.scale){const t=E.FromArray(l.scale||[1,1,1]),i=K.FromArray(l.rotation||[0,0,0,1]),s=E.FromArray(l.translation||[0,0,0]);e=M.Compose(t,i,s)}else e=M.FromArray(l.matrix);return e},Qo=(l,e,t,i)=>{for(let r=0;r<i.bones.length;r++)if(i.bones[r].name===t)return i.bones[r];const s=l.nodes;for(const r in s){const n=s[r];if(!n.jointName)continue;const a=n.children;for(let o=0;o<a.length;o++){const h=l.nodes[a[o]];if(h.jointName&&h.jointName===t){const c=Kn(n),u=new Ue(n.name||"",i,Qo(l,e,n.jointName,i),c);return u.id=r,u}}}return null},Md=(l,e)=>{for(let t=0;t<l.length;t++){const i=l[t];for(let s=0;s<i.node.children.length;s++)if(i.node.children[s]===e)return i.bone}return null},jn=(l,e)=>{const t=l.nodes;let i=t[e];if(i)return{node:i,id:e};for(const s in t)if(i=t[s],i.jointName===e)return{node:i,id:s};return null},Pd=(l,e)=>{for(let t=0;t<l.jointNames.length;t++)if(l.jointNames[t]===e)return!0;return!1},Od=(l,e,t,i)=>{for(const s in l.nodes){const r=l.nodes[s],n=s;if(!r.jointName||Pd(t,r.jointName))continue;const a=Kn(r),o=new Ue(r.name||"",e,null,a);o.id=n,i.push({bone:o,node:r,id:n})}for(let s=0;s<i.length;s++){const r=i[s],n=r.node.children;for(let a=0;a<n.length;a++){let o=null;for(let h=0;h<i.length;h++)if(i[h].id===n[a]){o=i[h];break}o&&(o.bone._parent=r.bone,r.bone.children.push(o.bone))}}},Dd=(l,e,t,i)=>{if(i||(i=new qs(e.name||"","",l.scene)),!e.babylonSkeleton)return i;const s=[],r=[];Od(l,i,e,s),i.bones=[];for(let a=0;a<e.jointNames.length;a++){const o=jn(l,e.jointNames[a]);if(!o)continue;const h=o.node;if(!h){k.Warn("Joint named "+e.jointNames[a]+" does not exist");continue}const c=o.id,u=l.scene.getBoneById(c);if(u){i.bones.push(u);continue}let f=!1,d=null;for(let m=0;m<a;m++){const T=jn(l,e.jointNames[m]);if(!T)continue;const S=T.node;if(!S){k.Warn("Joint named "+e.jointNames[m]+" does not exist when looking for parent");continue}const x=S.children;if(x){f=!1;for(let b=0;b<x.length;b++)if(x[b]===c){d=Qo(l,e,e.jointNames[m],i),f=!0;break}if(f)break}}const _=Kn(h);!d&&s.length>0&&(d=Md(s,c),d&&r.indexOf(d)===-1&&r.push(d));const p=new Ue(h.jointName||"",i,d,_);p.id=c}const n=i.bones;i.bones=[];for(let a=0;a<e.jointNames.length;a++){const o=jn(l,e.jointNames[a]);if(o){for(let h=0;h<n.length;h++)if(n[h].id===o.id){i.bones.push(n[h]);break}}}i.prepare();for(let a=0;a<r.length;a++)i.bones.push(r[a]);return i},$o=(l,e,t,i,s)=>{if(s||(l.scene._blockEntityCollection=!!l.assetContainer,s=new ne(e.name||"",l.scene),s._parentContainer=l.assetContainer,l.scene._blockEntityCollection=!1,s.id=i),!e.babylonNode)return s;const r=[];let n=null;const a=new Array,o=new Array,h=new Array,c=new Array;for(let d=0;d<t.length;d++){const _=t[d],p=l.meshes[_];if(p)for(let m=0;m<p.primitives.length;m++){const T=new me,S=p.primitives[m];S.mode;const x=S.attributes;let b=null,I=null;for(const C in x)if(b=l.accessors[x[C]],I=dt.GetBufferFromAccessor(l,b),C==="NORMAL")T.normals=new Float32Array(I.length),T.normals.set(I);else if(C==="POSITION"){if(Ze.HomogeneousCoordinates){T.positions=new Float32Array(I.length-I.length/4);for(let y=0;y<I.length;y+=4)T.positions[y]=I[y],T.positions[y+1]=I[y+1],T.positions[y+2]=I[y+2]}else T.positions=new Float32Array(I.length),T.positions.set(I);o.push(T.positions.length)}else if(C.indexOf("TEXCOORD_")!==-1){const y=Number(C.split("_")[1]),w=A.UVKind+(y===0?"":y+1),G=new Float32Array(I.length);G.set(I),Id(G),T.set(G,w)}else C==="JOINT"?(T.matricesIndices=new Float32Array(I.length),T.matricesIndices.set(I)):C==="WEIGHT"?(T.matricesWeights=new Float32Array(I.length),T.matricesWeights.set(I)):C==="COLOR"&&(T.colors=new Float32Array(I.length),T.colors.set(I));if(b=l.accessors[S.indices],b)I=dt.GetBufferFromAccessor(l,b),T.indices=new Int32Array(I.length),T.indices.set(I),c.push(T.indices.length);else{const C=[];for(let y=0;y<T.positions.length/3;y++)C.push(y);T.indices=new Int32Array(C),c.push(T.indices.length)}n?n.merge(T):n=T;const R=l.scene.getMaterialById(S.material);r.push(R===null?dt.GetDefaultMaterial(l.scene):R),a.push(a.length===0?0:a[a.length-1]+o[o.length-2]),h.push(h.length===0?0:h[h.length-1]+c[c.length-2])}}let u;l.scene._blockEntityCollection=!!l.assetContainer,r.length>1?(u=new Ss("multimat"+i,l.scene),u.subMaterials=r):u=new Y("multimat"+i,l.scene),r.length===1&&(u=r[0]),u._parentContainer=l.assetContainer,s.material||(s.material=u),new Bt(i,l.scene,n,!1,s),s.computeWorldMatrix(!0),l.scene._blockEntityCollection=!1,s.subMeshes=[];let f=0;for(let d=0;d<t.length;d++){const _=t[d],p=l.meshes[_];if(p)for(let m=0;m<p.primitives.length;m++)p.primitives[m].mode,ci.AddToMesh(f,a[f],o[f],h[f],c[f],s,s,!0),f++}return s},qn=(l,e,t,i)=>{l.position&&(l.position=e),(l.rotationQuaternion||l.rotation)&&(l.rotationQuaternion=t),l.scaling&&(l.scaling=i)},Ld=(l,e)=>{if(e.matrix){const t=new E(0,0,0),i=new K,s=new E(0,0,0);M.FromArray(e.matrix).decompose(s,i,t),qn(l,t,i,s)}else e.translation&&e.rotation&&e.scale&&qn(l,E.FromArray(e.translation),K.FromArray(e.rotation),E.FromArray(e.scale));l.computeWorldMatrix(!0)},Nd=(l,e,t)=>{let i=null;if(l.importOnlyMeshes&&(e.skin||e.meshes)&&l.importMeshesNames&&l.importMeshesNames.length>0&&l.importMeshesNames.indexOf(e.name||"")===-1)return null;if(e.skin){if(e.meshes){const s=l.skins[e.skin],r=$o(l,e,e.meshes,t,e.babylonNode);r.skeleton=l.scene.getLastSkeletonById(e.skin),r.skeleton===null&&(r.skeleton=Dd(l,s,r,s.babylonSkeleton),s.babylonSkeleton||(s.babylonSkeleton=r.skeleton)),i=r}}else if(e.meshes)i=$o(l,e,e.mesh?[e.mesh]:e.meshes,t,e.babylonNode);else if(e.light&&!e.babylonNode&&!l.importOnlyMeshes){const s=l.lights[e.light];if(s){if(s.type==="ambient"){const r=s[s.type],n=new Or(e.light,E.Zero(),l.scene);n.name=e.name||"",r.color&&(n.diffuse=z.FromArray(r.color)),i=n}else if(s.type==="directional"){const r=s[s.type],n=new fi(e.light,E.Zero(),l.scene);n.name=e.name||"",r.color&&(n.diffuse=z.FromArray(r.color)),i=n}else if(s.type==="point"){const r=s[s.type],n=new Dr(e.light,E.Zero(),l.scene);n.name=e.name||"",r.color&&(n.diffuse=z.FromArray(r.color)),i=n}else if(s.type==="spot"){const r=s[s.type],n=new Kt(e.light,E.Zero(),E.Zero(),0,0,l.scene);n.name=e.name||"",r.color&&(n.diffuse=z.FromArray(r.color)),r.fallOfAngle&&(n.angle=r.fallOfAngle),r.fallOffExponent&&(n.exponent=r.fallOffExponent),i=n}}}else if(e.camera&&!e.babylonNode&&!l.importOnlyMeshes){const s=l.cameras[e.camera];if(s){if(l.scene._blockEntityCollection=!!l.assetContainer,s.type==="orthographic"){const r=new Cs(e.camera,E.Zero(),l.scene,!1);r.name=e.name||"",r.mode=ie.ORTHOGRAPHIC_CAMERA,r.attachControl(),i=r,r._parentContainer=l.assetContainer}else if(s.type==="perspective"){const r=s[s.type],n=new Cs(e.camera,E.Zero(),l.scene,!1);n.name=e.name||"",n.attachControl(),r.aspectRatio||(r.aspectRatio=l.scene.getEngine().getRenderWidth()/l.scene.getEngine().getRenderHeight()),r.znear&&r.zfar&&(n.maxZ=r.zfar,n.minZ=r.znear),i=n,n._parentContainer=l.assetContainer}l.scene._blockEntityCollection=!1}}if(!e.jointName){if(e.babylonNode)return e.babylonNode;if(i===null){l.scene._blockEntityCollection=!!l.assetContainer;const s=new ne(e.name||"",l.scene);s._parentContainer=l.assetContainer,l.scene._blockEntityCollection=!1,e.babylonNode=s,i=s}}if(i!==null){if(e.matrix&&i instanceof ne)Ld(i,e);else{const s=e.translation||[0,0,0],r=e.rotation||[0,0,0,1],n=e.scale||[1,1,1];qn(i,E.FromArray(s),K.FromArray(r),E.FromArray(n))}i.updateCache(!0),e.babylonNode=i}return i},Lr=(l,e,t,i=!1)=>{const s=l.nodes[e];let r=null;if(l.importOnlyMeshes&&!i&&l.importMeshesNames?l.importMeshesNames.indexOf(s.name||"")!==-1||l.importMeshesNames.length===0?i=!0:i=!1:i=!0,!s.jointName&&i&&(r=Nd(l,s,e),r!==null&&(r.id=e,r.parent=t)),s.children)for(let n=0;n<s.children.length;n++)Lr(l,s.children[n],r,i)},Jo=l=>{let e=l.currentScene;if(e)for(let t=0;t<e.nodes.length;t++)Lr(l,e.nodes[t],null);else for(const t in l.scenes){e=l.scenes[t];for(let i=0;i<e.nodes.length;i++)Lr(l,e.nodes[i],null)}yd(l);for(let t=0;t<l.scene.skeletons.length;t++){const i=l.scene.skeletons[t];l.scene.beginAnimation(i,0,Number.MAX_VALUE,!0,1)}},Fd=(l,e,t,i,s,r,n)=>{const a=r.values||s.parameters;for(const o in t){const h=t[o],c=h.type;if(c===Yt.FLOAT_MAT2||c===Yt.FLOAT_MAT3||c===Yt.FLOAT_MAT4){if(h.semantic&&!h.source&&!h.node)dt.SetMatrix(e.scene,l,h,o,i.getEffect());else if(h.semantic&&(h.source||h.node)){let u=e.scene.getNodeByName(h.source||h.node||"");if(u===null&&(u=e.scene.getNodeById(h.source||h.node||"")),u===null)continue;dt.SetMatrix(e.scene,u,h,o,i.getEffect())}}else{const u=a[s.uniforms[o]];if(!u)continue;if(c===Yt.SAMPLER_2D){const f=e.textures[r.values?u:h.value].babylonTexture;if(f==null)continue;i.getEffect().setTexture(o,f)}else dt.SetUniform(i.getEffect(),o,u,c)}}n(i)},wd=(l,e,t,i,s)=>{const r=i.values||t.parameters,n=t.uniforms;for(const a in s){const o=s[a],h=o.type;let c=r[n[a]];if(c===void 0&&(c=o.value),!c)continue;const u=f=>d=>{o.value&&f&&(e.setTexture(f,d),delete s[f])};h===Yt.SAMPLER_2D?yt.LoadTextureAsync(l,i.values?c:o.value,u(a),()=>u(null)):o.value&&dt.SetUniform(e,a,i.values?c:o.value,h)&&delete s[a]}},Bd=(l,e,t)=>(i,s)=>{e.dispose(!0),t("Cannot compile program named "+l.name+". Error: "+s+". Default material will be applied")},Ud=(l,e,t,i,s,r)=>n=>{wd(l,e,t,i,s),e.onBind=a=>{Fd(a,l,s,e,t,i,r)}},el=(l,e,t)=>{for(const i in e.uniforms){const s=e.uniforms[i],r=e.parameters[s];if(l.currentIdentifier===i&&r.semantic&&!r.source&&!r.node){const n=jo.indexOf(r.semantic);if(n!==-1)return delete t[i],qo[n]}}return l.currentIdentifier},tl=l=>{for(const e in l.materials)yt.LoadMaterialAsync(l,e,()=>{},()=>{})};class Vi{static CreateRuntime(e,t,i){const s={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:i,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&kt(e.extensions,"extensions",s),e.extensionsUsed&&kt(e.extensionsUsed,"extensionsUsed",s),e.buffers&&Cd(e.buffers,s),e.bufferViews&&kt(e.bufferViews,"bufferViews",s),e.accessors&&kt(e.accessors,"accessors",s),e.meshes&&kt(e.meshes,"meshes",s),e.lights&&kt(e.lights,"lights",s),e.cameras&&kt(e.cameras,"cameras",s),e.nodes&&kt(e.nodes,"nodes",s),e.images&&kt(e.images,"images",s),e.textures&&kt(e.textures,"textures",s),e.shaders&&bd(e.shaders,s),e.programs&&kt(e.programs,"programs",s),e.samplers&&kt(e.samplers,"samplers",s),e.techniques&&kt(e.techniques,"techniques",s),e.materials&&kt(e.materials,"materials",s),e.animations&&kt(e.animations,"animations",s),e.skins&&kt(e.skins,"skins",s),e.scenes&&(s.scenes=e.scenes),e.scene&&e.scenes&&(s.currentScene=e.scenes[e.scene]),s}static LoadBufferAsync(e,t,i,s,r){const n=e.buffers[t];k.IsBase64(n.uri)?setTimeout(()=>i(new Uint8Array(k.DecodeBase64(n.uri)))):k.LoadFile(e.rootUrl+n.uri,a=>i(new Uint8Array(a)),r,void 0,!0,a=>{a&&s(a.status+" "+a.statusText)})}static LoadTextureBufferAsync(e,t,i,s){const r=e.textures[t];if(!r||!r.source){s("");return}if(r.babylonTexture){i(null);return}const n=e.images[r.source];k.IsBase64(n.uri)?setTimeout(()=>i(new Uint8Array(k.DecodeBase64(n.uri)))):k.LoadFile(e.rootUrl+n.uri,a=>i(new Uint8Array(a)),void 0,void 0,!0,a=>{a&&s(a.status+" "+a.statusText)})}static CreateTextureAsync(e,t,i,s){const r=e.textures[t];if(r.babylonTexture){s(r.babylonTexture);return}const n=e.samplers[r.sampler],a=n.minFilter===Ei.NEAREST_MIPMAP_NEAREST||n.minFilter===Ei.NEAREST_MIPMAP_LINEAR||n.minFilter===Ei.LINEAR_MIPMAP_NEAREST||n.minFilter===Ei.LINEAR_MIPMAP_LINEAR,o=O.BILINEAR_SAMPLINGMODE,h=i==null?new Blob:new Blob([i]),c=URL.createObjectURL(h),u=()=>URL.revokeObjectURL(c),f=new O(c,e.scene,!a,!0,o,u,u);n.wrapS!==void 0&&(f.wrapU=dt.GetWrapMode(n.wrapS)),n.wrapT!==void 0&&(f.wrapV=dt.GetWrapMode(n.wrapT)),f.name=t,r.babylonTexture=f,s(f)}static LoadShaderStringAsync(e,t,i,s){const r=e.shaders[t];if(k.IsBase64(r.uri)){const n=atob(r.uri.split(",")[1]);i&&i(n)}else k.LoadFile(e.rootUrl+r.uri,i,void 0,void 0,!1,n=>{n&&s&&s(n.status+" "+n.statusText)})}static LoadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r.technique){s&&s("No technique found.");return}const n=e.techniques[r.technique];if(!n){e.scene._blockEntityCollection=!!e.assetContainer;const R=new Y(t,e.scene);R._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,R.diffuseColor=new z(.5,.5,.5),R.sideOrientation=V.CounterClockWiseSideOrientation,i(R);return}const a=e.programs[n.program],o=n.states,h=nt.ShadersStore[a.vertexShader+"VertexShader"],c=nt.ShadersStore[a.fragmentShader+"PixelShader"];let u="",f="";const d=new Ko(h),_=new Ko(c),p={},m=[],T=[],S=[];for(const R in n.uniforms){const C=n.uniforms[R],y=n.parameters[C];if(p[R]=y,y.semantic&&!y.node&&!y.source){const w=jo.indexOf(y.semantic);w!==-1?(m.push(qo[w]),delete p[R]):m.push(R)}else y.type===Yt.SAMPLER_2D?S.push(R):m.push(R)}for(const R in n.attributes){const C=n.attributes[R],y=n.parameters[C];if(y.semantic){const w=Zo(y);w&&T.push(w)}}for(;!d.isEnd()&&d.getNextToken();){if(d.currentToken!==hs.IDENTIFIER){u+=d.currentString;continue}let C=!1;for(const y in n.attributes){const w=n.attributes[y],G=n.parameters[w];if(d.currentIdentifier===y&&G.semantic){u+=Zo(G),C=!0;break}}C||(u+=el(d,n,p))}for(;!_.isEnd()&&_.getNextToken();){if(_.currentToken!==hs.IDENTIFIER){f+=_.currentString;continue}f+=el(_,n,p)}const x={vertex:a.vertexShader+t,fragment:a.fragmentShader+t},b={attributes:T,uniforms:m,samplers:S,needAlphaBlending:o&&o.enable&&o.enable.indexOf(3042)!==-1};nt.ShadersStore[a.vertexShader+t+"VertexShader"]=u,nt.ShadersStore[a.fragmentShader+t+"PixelShader"]=f;const I=new vi(t,e.scene,x,b);if(I.onError=Bd(a,I,s),I.onCompiled=Ud(e,I,n,r,p,i),I.sideOrientation=V.CounterClockWiseSideOrientation,o&&o.functions){const R=o.functions;R.cullFace&&R.cullFace[0]!==Wn.BACK&&(I.backFaceCulling=!1);const C=R.blendFuncSeparate;C&&(C[0]===st.SRC_ALPHA&&C[1]===st.ONE_MINUS_SRC_ALPHA&&C[2]===st.ONE&&C[3]===st.ONE?I.alphaMode=P.ALPHA_COMBINE:C[0]===st.ONE&&C[1]===st.ONE&&C[2]===st.ZERO&&C[3]===st.ONE?I.alphaMode=P.ALPHA_ONEONE:C[0]===st.SRC_ALPHA&&C[1]===st.ONE&&C[2]===st.ZERO&&C[3]===st.ONE?I.alphaMode=P.ALPHA_ADD:C[0]===st.ZERO&&C[1]===st.ONE_MINUS_SRC_COLOR&&C[2]===st.ONE&&C[3]===st.ONE?I.alphaMode=P.ALPHA_SUBTRACT:C[0]===st.DST_COLOR&&C[1]===st.ZERO&&C[2]===st.ONE&&C[3]===st.ONE?I.alphaMode=P.ALPHA_MULTIPLY:C[0]===st.SRC_ALPHA&&C[1]===st.ONE_MINUS_SRC_COLOR&&C[2]===st.ONE&&C[3]===st.ONE&&(I.alphaMode=P.ALPHA_MAXIMIZED))}}}let Zs=class Ka{static RegisterExtension(e){if(Ka.Extensions[e.name]){k.Error('Tool with the same name "'+e.name+'" already exists');return}Ka.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,s,r,n,a,o){return t.useRightHandedSystem=!0,yt.LoadRuntimeAsync(t,i,s,h=>{h.assetContainer=r,h.importOnlyMeshes=!0,e===""?h.importMeshesNames=[]:typeof e=="string"?h.importMeshesNames=[e]:e&&!(e instanceof Array)?h.importMeshesNames=[e]:(h.importMeshesNames=[],k.Warn("Argument meshesNames must be of type string or string[]")),this._createNodes(h);const c=new Array,u=new Array;for(const f in h.nodes){const d=h.nodes[f];d.babylonNode instanceof Vt&&c.push(d.babylonNode)}for(const f in h.skins){const d=h.skins[f];d.babylonSkeleton instanceof qs&&u.push(d.babylonSkeleton)}this._loadBuffersAsync(h,()=>{this._loadShadersAsync(h,()=>{tl(h),Jo(h),!Ze.IncrementalLoading&&n&&n(c,u)})}),Ze.IncrementalLoading&&n&&n(c,u)},o),!0}importMeshAsync(e,t,i,s,r,n){return new Promise((a,o)=>{this._importMeshAsync(e,t,s,r,i,(h,c)=>{a({meshes:h,particleSystems:[],skeletons:c,animationGroups:[],lights:[],transformNodes:[],geometries:[]})},n,h=>{o(new Error(h))})})}_loadAsync(e,t,i,s,r,n){e.useRightHandedSystem=!0,yt.LoadRuntimeAsync(e,t,i,a=>{yt.LoadRuntimeExtensionsAsync(a,()=>{this._createNodes(a),this._loadBuffersAsync(a,()=>{this._loadShadersAsync(a,()=>{tl(a),Jo(a),Ze.IncrementalLoading||s()})}),Ze.IncrementalLoading&&s()},n)},n)}loadAsync(e,t,i,s){return new Promise((r,n)=>{this._loadAsync(e,t,i,()=>{r()},s,a=>{n(new Error(a))})})}_loadShadersAsync(e,t){let i=!1;const s=(r,n)=>{yt.LoadShaderStringAsync(e,r,a=>{a instanceof ArrayBuffer||(e.loadedShaderCount++,a&&(nt.ShadersStore[r+(n.type===Hn.VERTEX?"VertexShader":"PixelShader")]=a),e.loadedShaderCount===e.shaderscount&&t())},()=>{k.Error("Error when loading shader program named "+r+" located at "+n.uri)})};for(const r in e.shaders){i=!0;const n=e.shaders[r];n?s.bind(this,r,n)():k.Error("No shader named: "+r)}i||t()}_loadBuffersAsync(e,t){let i=!1;const s=(r,n)=>{yt.LoadBufferAsync(e,r,a=>{e.loadedBufferCount++,a&&(a.byteLength!=e.buffers[r].byteLength&&k.Error("Buffer named "+r+" is length "+a.byteLength+". Expected: "+n.byteLength),e.loadedBufferViews[r]=a),e.loadedBufferCount===e.buffersCount&&t()},()=>{k.Error("Error when loading buffer named "+r+" located at "+n.uri)})};for(const r in e.buffers){i=!0;const n=e.buffers[r];n?s.bind(this,r,n)():k.Error("No buffer named: "+r)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;i<t.nodes.length;i++)Lr(e,t.nodes[i],null);else for(const i in e.scenes){t=e.scenes[i];for(let s=0;s<t.nodes.length;s++)Lr(e,t.nodes[s],null)}}};Zs.Extensions={};class yt{constructor(e){this._name=e}get name(){return this._name}loadRuntimeAsync(e,t,i,s,r){return!1}loadRuntimeExtensionsAsync(e,t,i){return!1}loadBufferAsync(e,t,i,s,r){return!1}loadTextureBufferAsync(e,t,i,s){return!1}createTextureAsync(e,t,i,s,r){return!1}loadShaderStringAsync(e,t,i,s){return!1}loadMaterialAsync(e,t,i,s){return!1}static LoadRuntimeAsync(e,t,i,s,r){yt._ApplyExtensions(n=>n.loadRuntimeAsync(e,t,i,s,r),()=>{setTimeout(()=>{s&&s(Vi.CreateRuntime(t.json,e,i))})})}static LoadRuntimeExtensionsAsync(e,t,i){yt._ApplyExtensions(s=>s.loadRuntimeExtensionsAsync(e,t,i),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,i,s,r){yt._ApplyExtensions(n=>n.loadBufferAsync(e,t,i,s,r),()=>{Vi.LoadBufferAsync(e,t,i,s,r)})}static LoadTextureAsync(e,t,i,s){yt._LoadTextureBufferAsync(e,t,r=>{r&&yt._CreateTextureAsync(e,t,r,i,s)},s)}static LoadShaderStringAsync(e,t,i,s){yt._ApplyExtensions(r=>r.loadShaderStringAsync(e,t,i,s),()=>{Vi.LoadShaderStringAsync(e,t,i,s)})}static LoadMaterialAsync(e,t,i,s){yt._ApplyExtensions(r=>r.loadMaterialAsync(e,t,i,s),()=>{Vi.LoadMaterialAsync(e,t,i,s)})}static _LoadTextureBufferAsync(e,t,i,s){yt._ApplyExtensions(r=>r.loadTextureBufferAsync(e,t,i,s),()=>{Vi.LoadTextureBufferAsync(e,t,i,s)})}static _CreateTextureAsync(e,t,i,s,r){yt._ApplyExtensions(n=>n.createTextureAsync(e,t,i,s,r),()=>{Vi.CreateTextureAsync(e,t,i,s)})}static _ApplyExtensions(e,t){for(const i in Zs.Extensions){const s=Zs.Extensions[i];if(e(s))return}t()}}Ze._CreateGLTF1Loader=()=>new Zs;const Vd="binary_glTF";class kd extends yt{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,s){const r=t.json.extensionsUsed;return!r||r.indexOf(this.name)===-1||!t.bin?!1:(this._bin=t.bin,s(Vi.CreateRuntime(t.json,e,i)),!0)}loadBufferAsync(e,t,i,s){return e.extensionsUsed.indexOf(this.name)===-1||t!==Vd?!1:(this._bin.readAsync(0,this._bin.byteLength).then(i,r=>s(r.message)),!0)}loadTextureBufferAsync(e,t,i){const s=e.textures[t],r=e.images[s.source];if(!r.extensions||!(this.name in r.extensions))return!1;const n=r.extensions[this.name],a=e.bufferViews[n.bufferView],o=dt.GetBufferFromBufferView(e,a,0,a.byteLength,as.UNSIGNED_BYTE);return i(o),!0}loadShaderStringAsync(e,t,i){const s=e.shaders[t];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],n=e.bufferViews[r.bufferView],a=dt.GetBufferFromBufferView(e,n,0,n.byteLength,as.UNSIGNED_BYTE);return setTimeout(()=>{const o=dt.DecodeBufferToText(a);i(o)}),!0}}Zs.RegisterExtension(new kd);class Gd extends yt{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const t=e.extensions[this.name];if(!t)return!1;const i=t.lights;if(i)for(const s in i){const r=i[s];switch(r.type){case"ambient":{const n=new Or(r.name,new E(0,1,0),e.scene),a=r.ambient;a&&(n.diffuse=z.FromArray(a.color||[1,1,1]));break}case"point":{const n=new Dr(r.name,new E(10,10,10),e.scene),a=r.point;a&&(n.diffuse=z.FromArray(a.color||[1,1,1]));break}case"directional":{const n=new fi(r.name,new E(0,-1,0),e.scene),a=r.directional;a&&(n.diffuse=z.FromArray(a.color||[1,1,1]));break}case"spot":{const n=r.spot;if(n){const a=new Kt(r.name,new E(0,10,0),new E(0,-1,0),n.fallOffAngle||Math.PI,n.fallOffExponent||0,e.scene);a.diffuse=z.FromArray(n.color||[1,1,1])}break}default:k.Warn('GLTF Material Common extension: light type "'+r.type+"” not supported");break}}return!1}loadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r||!r.extensions)return!1;const n=r.extensions[this.name];if(!n)return!1;const a=new Y(t,e.scene);return a.sideOrientation=V.CounterClockWiseSideOrientation,n.technique==="CONSTANT"&&(a.disableLighting=!0),a.backFaceCulling=n.doubleSided===void 0?!1:!n.doubleSided,a.alpha=n.values.transparency===void 0?1:n.values.transparency,a.specularPower=n.values.shininess===void 0?0:n.values.shininess,typeof n.values.ambient=="string"?this._loadTexture(e,n.values.ambient,a,"ambientTexture",s):a.ambientColor=z.FromArray(n.values.ambient||[0,0,0]),typeof n.values.diffuse=="string"?this._loadTexture(e,n.values.diffuse,a,"diffuseTexture",s):a.diffuseColor=z.FromArray(n.values.diffuse||[0,0,0]),typeof n.values.emission=="string"?this._loadTexture(e,n.values.emission,a,"emissiveTexture",s):a.emissiveColor=z.FromArray(n.values.emission||[0,0,0]),typeof n.values.specular=="string"?this._loadTexture(e,n.values.specular,a,"specularTexture",s):a.specularColor=z.FromArray(n.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,s,r){Vi.LoadTextureBufferAsync(e,t,n=>{Vi.CreateTextureAsync(e,t,n,a=>i[s]=a)},r)}}Zs.RegisterExtension(new Gd);class Nr{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}class Hd{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class Fr{get from(){return this._from}get to(){return this._to}get isStarted(){return this._isStarted}get isPlaying(){return this._isStarted&&!this._isPaused}get speedRatio(){return this._speedRatio}set speedRatio(e){if(this._speedRatio!==e){this._speedRatio=e;for(let t=0;t<this._animatables.length;t++){const i=this._animatables[t];i.speedRatio=this._speedRatio}}}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){if(this._loopAnimation!==e){this._loopAnimation=e;for(let t=0;t<this._animatables.length;t++){const i=this._animatables[t];i.loopAnimation=this._loopAnimation}}}get isAdditive(){return this._isAdditive}set isAdditive(e){if(this._isAdditive!==e){this._isAdditive=e;for(let t=0;t<this._animatables.length;t++){const i=this._animatables[t];i.isAdditive=this._isAdditive}}}get weight(){return this._weight}set weight(e){this._weight!==e&&(this._weight=e,this.setWeightForAllAnimatables(this._weight))}get targetedAnimations(){return this._targetedAnimations}get animatables(){return this._animatables}get children(){return this._targetedAnimations}get playOrder(){return this._playOrder}set playOrder(e){if(this._playOrder!==e&&(this._playOrder=e,this._animatables.length>0)){for(let t=0;t<this._animatables.length;t++)this._animatables[t].playOrder=this._playOrder;this._scene.sortActiveAnimatables()}}enableBlending(e){for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.enableBlending=!0,this._targetedAnimations[t].animation.blendingSpeed=e}disableBlending(){for(let e=0;e<this._targetedAnimations.length;++e)this._targetedAnimations[e].animation.enableBlending=!1}static MergeAnimationGroups(e,t=!0,i=!1,s){if(e.length===0)return null;s=s??e[0].weight;let r=Number.MAX_VALUE,n=Number.MIN_VALUE;if(i)for(const o of e)o.from<r&&(r=o.from),o.to>n&&(n=o.to);const a=new Fr(e[0].name+"_merged",e[0]._scene,s);for(const o of e){i&&o.normalize(r,n);for(const h of o.targetedAnimations)a.addTargetedAnimation(h.animation,h.target);t&&o.dispose()}return a}constructor(e,t=null,i=-1,s=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._parentContainer=null,this.onAnimationEndObservable=new B,this.onAnimationLoopObservable=new B,this.onAnimationGroupLoopObservable=new B,this.onAnimationGroupEndObservable=new B,this.onAnimationGroupPauseObservable=new B,this.onAnimationGroupPlayObservable=new B,this.metadata=null,this._animationLoopFlags=[],this._scene=t||Ee.LastCreatedScene,this._weight=i,this._playOrder=s,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new Hd;i.animation=e,i.target=t;const s=e.getKeys();return this._from>s[0].frame&&(this._from=s[0].frame),this._to<s[s.length-1].frame&&(this._to=s[s.length-1].frame),this._targetedAnimations.push(i),i}removeTargetedAnimation(e){for(let t=this._targetedAnimations.length-1;t>-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){e==null&&(e=this._from),t==null&&(t=this._to);for(let i=0;i<this._targetedAnimations.length;i++){const r=this._targetedAnimations[i].animation.getKeys(),n=r[0],a=r[r.length-1];if(n.frame>e){const o={frame:e,value:n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation};r.splice(0,0,o)}if(a.frame<t){const o={frame:t,value:a.value,inTangent:a.inTangent,outTangent:a.outTangent,interpolation:a.interpolation};r.push(o)}}return this._from=e,this._to=t,this}_processLoop(e,t,i){e.onAnimationLoop=()=>{this.onAnimationLoopObservable.notifyObservers(t),!this._animationLoopFlags[i]&&(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._targetedAnimations.length&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,s,r){if(this._isStarted||this._targetedAnimations.length===0)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n<this._targetedAnimations.length;n++){const a=this._targetedAnimations[n],o=this._scene.beginDirectAnimation(a.target,[a.animation],i!==void 0?i:this._from,s!==void 0?s:this._to,e,t,void 0,void 0,r!==void 0?r:this._isAdditive);o.weight=this._weight,o.playOrder=this._playOrder,o.onAnimationEnd=()=>{this.onAnimationEndObservable.notifyObservers(a),this._checkAnimationGroupEnded(o)},this._processLoop(o,a,n),this._animatables.push(o)}return this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e<this._animatables.length;e++)this._animatables[e].pause();return this.onAnimationGroupPauseObservable.notifyObservers(this),this}play(e){return this.isStarted&&this._animatables.length===this._targetedAnimations.length?(e!==void 0&&(this.loopAnimation=e),this.restart()):(this.stop(),this.start(e,this._speedRatio)),this._isPaused=!1,this}reset(){if(!this._isStarted)return this.play(),this.goToFrame(0),this.stop(),this;for(let e=0;e<this._animatables.length;e++)this._animatables[e].reset();return this}restart(){if(!this._isStarted)return this;for(let e=0;e<this._animatables.length;e++)this._animatables[e].restart();return this.onAnimationGroupPlayObservable.notifyObservers(this),this}stop(){if(!this._isStarted)return this;const e=this._animatables.slice();for(let i=0;i<e.length;i++)e[i].stop(void 0,void 0,!0);let t=0;for(let i=0;i<this._scene._activeAnimatables.length;i++){const s=this._scene._activeAnimatables[i];s._runtimeAnimations.length>0&&(this._scene._activeAnimatables[t++]=s)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t<this._animatables.length;t++){const i=this._animatables[t];i.weight=e}return this}syncAllAnimationsWith(e){for(let t=0;t<this._animatables.length;t++)this._animatables[t].syncWith(e);return this}goToFrame(e){if(!this._isStarted)return this;for(let t=0;t<this._animatables.length;t++)this._animatables[t].goToFrame(e);return this}dispose(){this._targetedAnimations.length=0,this._animatables.length=0;const e=this._scene.animationGroups.indexOf(this);if(e>-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const t=this._parentContainer.animationGroups.indexOf(this);t>-1&&this._parentContainer.animationGroups.splice(t,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e){const t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),this._animatables.length===0&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const s=new Fr(e||this.name,this._scene);for(const r of this._targetedAnimations)s.addTargetedAnimation(i?r.animation.clone():r.animation,t?t(r.target):r.target);return s}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.targetedAnimations=[];for(let t=0;t<this.targetedAnimations.length;t++){const i=this.targetedAnimations[t];e.targetedAnimations[t]=i.serialize()}return xe&&xe.HasTags(this)&&(e.tags=xe.GetTags(this)),this.metadata&&(e.metadata=this.metadata),e}static Parse(e,t){const i=new Fr(e.name,t);for(let s=0;s<e.targetedAnimations.length;s++){const r=e.targetedAnimations[s],n=N.Parse(r.animation),a=r.targetId;if(r.animation.property==="influence"){const o=t.getMorphTargetById(a);o&&i.addTargetedAnimation(n,o)}else{const o=t.getNodeById(a);o!=null&&i.addTargetedAnimation(n,o)}}return e.from!==null&&e.to!==null&&i.normalize(e.from,e.to),xe&&xe.AddTagsTo(i,e.tags),e.metadata!==void 0&&(i.metadata=e.metadata),i}static MakeAnimationAdditive(e,t=0,i,s=!1,r){let n=e;s&&(n=e.clone(r||n.name));const a=n.targetedAnimations;for(let o=0;o<a.length;o++){const h=a[o];N.MakeAnimationAdditive(h.animation,t,i)}return n.isAdditive=!0,n}getClassName(){return"AnimationGroup"}toString(e){let t="Name: "+this.name;return t+=", type: "+this.getClassName(),e&&(t+=", from: "+this._from,t+=", to: "+this._to,t+=", isStarted: "+this._isStarted,t+=", speedRatio: "+this._speedRatio,t+=", targetedAnimations length: "+this._targetedAnimations.length,t+=", animatables length: "+this._animatables),t}}const Wd="rgbdDecodePixelShader",zd=`varying vec2 vUV;
3570
3570
  uniform sampler2D textureSampler;
3571
3571
  #include<helperFunctions>
3572
3572
  #define CUSTOM_FRAGMENT_DEFINITIONS